context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: prototype_server_client.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace PbPrototype.PS2C {
/// <summary>Holder for reflection information generated from prototype_server_client.proto</summary>
public static partial class PrototypeServerClientReflection {
#region Descriptor
/// <summary>File descriptor for prototype_server_client.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PrototypeServerClientReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch1wcm90b3R5cGVfc2VydmVyX2NsaWVudC5wcm90bxIRcGJfcHJvdG90eXBl",
"LlBTMkMaFnByb3RvdHlwZV9jb21tb24ucHJvdG8iFgoDV2hvEg8KB21lc3Nh",
"Z2UYASABKAkiFwoEQ2hhdBIPCgdtZXNzYWdlGAEgASgJIlMKBEF1dGgSEwoL",
"YXV0aF9yZXN1bHQYASABKAgSNgoQcGxheWVyX3VuaXRfZGF0YRgCIAEoCzIc",
"LnBiX3Byb3RvdHlwZS5QbGF5ZXJVbml0RGF0YSowCg5Qcm90b2NvbE51bWJl",
"chIICgRFV2hvEAASCQoFRUNoYXQQARIJCgVFQXV0aBACUABiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::PbPrototype.PrototypeCommonReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::PbPrototype.PS2C.ProtocolNumber), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::PbPrototype.PS2C.Who), global::PbPrototype.PS2C.Who.Parser, new[]{ "Message" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::PbPrototype.PS2C.Chat), global::PbPrototype.PS2C.Chat.Parser, new[]{ "Message" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::PbPrototype.PS2C.Auth), global::PbPrototype.PS2C.Auth.Parser, new[]{ "AuthResult", "PlayerUnitData" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum ProtocolNumber {
[pbr::OriginalName("EWho")] Ewho = 0,
[pbr::OriginalName("EChat")] Echat = 1,
[pbr::OriginalName("EAuth")] Eauth = 2,
}
#endregion
#region Messages
public sealed partial class Who : pb::IMessage<Who> {
private static readonly pb::MessageParser<Who> _parser = new pb::MessageParser<Who>(() => new Who());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Who> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::PbPrototype.PS2C.PrototypeServerClientReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Who() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Who(Who other) : this() {
message_ = other.message_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Who Clone() {
return new Who(this);
}
/// <summary>Field number for the "message" field.</summary>
public const int MessageFieldNumber = 1;
private string message_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Message {
get { return message_; }
set {
message_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Who);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Who other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Message != other.Message) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Message.Length != 0) hash ^= Message.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Message.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Message);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Who other) {
if (other == null) {
return;
}
if (other.Message.Length != 0) {
Message = other.Message;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Message = input.ReadString();
break;
}
}
}
}
}
public sealed partial class Chat : pb::IMessage<Chat> {
private static readonly pb::MessageParser<Chat> _parser = new pb::MessageParser<Chat>(() => new Chat());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Chat> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::PbPrototype.PS2C.PrototypeServerClientReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Chat() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Chat(Chat other) : this() {
message_ = other.message_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Chat Clone() {
return new Chat(this);
}
/// <summary>Field number for the "message" field.</summary>
public const int MessageFieldNumber = 1;
private string message_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Message {
get { return message_; }
set {
message_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Chat);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Chat other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Message != other.Message) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Message.Length != 0) hash ^= Message.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Message.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Message);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Chat other) {
if (other == null) {
return;
}
if (other.Message.Length != 0) {
Message = other.Message;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Message = input.ReadString();
break;
}
}
}
}
}
public sealed partial class Auth : pb::IMessage<Auth> {
private static readonly pb::MessageParser<Auth> _parser = new pb::MessageParser<Auth>(() => new Auth());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Auth> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::PbPrototype.PS2C.PrototypeServerClientReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Auth() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Auth(Auth other) : this() {
authResult_ = other.authResult_;
PlayerUnitData = other.playerUnitData_ != null ? other.PlayerUnitData.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Auth Clone() {
return new Auth(this);
}
/// <summary>Field number for the "auth_result" field.</summary>
public const int AuthResultFieldNumber = 1;
private bool authResult_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool AuthResult {
get { return authResult_; }
set {
authResult_ = value;
}
}
/// <summary>Field number for the "player_unit_data" field.</summary>
public const int PlayerUnitDataFieldNumber = 2;
private global::PbPrototype.PlayerUnitData playerUnitData_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::PbPrototype.PlayerUnitData PlayerUnitData {
get { return playerUnitData_; }
set {
playerUnitData_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Auth);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Auth other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (AuthResult != other.AuthResult) return false;
if (!object.Equals(PlayerUnitData, other.PlayerUnitData)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (AuthResult != false) hash ^= AuthResult.GetHashCode();
if (playerUnitData_ != null) hash ^= PlayerUnitData.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (AuthResult != false) {
output.WriteRawTag(8);
output.WriteBool(AuthResult);
}
if (playerUnitData_ != null) {
output.WriteRawTag(18);
output.WriteMessage(PlayerUnitData);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (AuthResult != false) {
size += 1 + 1;
}
if (playerUnitData_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PlayerUnitData);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Auth other) {
if (other == null) {
return;
}
if (other.AuthResult != false) {
AuthResult = other.AuthResult;
}
if (other.playerUnitData_ != null) {
if (playerUnitData_ == null) {
playerUnitData_ = new global::PbPrototype.PlayerUnitData();
}
PlayerUnitData.MergeFrom(other.PlayerUnitData);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
AuthResult = input.ReadBool();
break;
}
case 18: {
if (playerUnitData_ == null) {
playerUnitData_ = new global::PbPrototype.PlayerUnitData();
}
input.ReadMessage(playerUnitData_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using ALinq.Mapping;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using ALinq.SqlClient;
namespace ALinq.EffiProz
{
internal class SqlBuilder
{
private ALinq.SqlClient.SqlIdentifier sqlIdentifier;
public SqlBuilder(ALinq.SqlClient.SqlIdentifier sqlIdentifier)
{
this.sqlIdentifier = sqlIdentifier;
}
public SqlIdentifier SqlIdentifier
{
get { return sqlIdentifier; }
}
// Methods
public void BuildFieldDeclarations(MetaTable table, StringBuilder sb)
{
int num = 0;
var memberNameToMappedName = new Dictionary<object, string>();
foreach (MetaType type in table.RowType.InheritanceTypes)
{
num += BuildFieldDeclarations(type, memberNameToMappedName, sb);
}
if (num == 0)
{
throw SqlClient.Error.CreateDatabaseFailedBecauseOfClassWithNoMembers(table.RowType.Type);
}
}
private int BuildFieldDeclarations(MetaType type, IDictionary<object, string> memberNameToMappedName,
StringBuilder sb)
{
int num = 0;
foreach (MetaDataMember member in type.DataMembers)
{
string str;
if ((!member.IsDeclaredBy(type) || member.IsAssociation) || !member.IsPersistent)
{
continue;
}
object key = InheritanceRules.DistinguishedMemberName(member.Member);
if (memberNameToMappedName.TryGetValue(key, out str))
{
if (!(str == member.MappedName))
{
goto Label_0075;
}
continue;
}
memberNameToMappedName.Add(key, member.MappedName);
Label_0075:
if (sb.Length > 0)
{
sb.Append(", ");
}
sb.AppendLine();
sb.Append(string.Format(CultureInfo.InvariantCulture, " {0} ",
new object[] { SqlIdentifier.QuoteCompoundIdentifier(member.MappedName) }));
if (!string.IsNullOrEmpty(member.Expression))
{
sb.Append("AS " + member.Expression);
}
else
{
sb.Append(GetDbType(member));
}
num++;
}
return num;
}
private string BuildKey(IEnumerable<MetaDataMember> members)
{
var builder = new StringBuilder();
foreach (MetaDataMember member in members)
{
if (builder.Length > 0)
{
builder.Append(", ");
}
builder.Append(SqlIdentifier.QuoteCompoundIdentifier(member.MappedName));
}
return builder.ToString();
}
private void BuildPrimaryKey(MetaTable table, StringBuilder sb)
{
foreach (MetaDataMember member in table.RowType.IdentityMembers)
{
if (member.IsDbGenerated)
continue;
if (sb.Length > 0)
{
sb.Append(", ");
}
sb.Append(SqlIdentifier.QuoteCompoundIdentifier(member.MappedName));
}
}
public string GetCreateDatabaseCommand(string catalog, string dataFilename, string logFilename)
{
var builder = new StringBuilder();
builder.AppendFormat("CREATE DATABASE {0}", SqlIdentifier.QuoteIdentifier(catalog));
if (dataFilename != null)
{
builder.AppendFormat(" ON PRIMARY (NAME='{0}', FILENAME='{1}')", Path.GetFileName(dataFilename),
dataFilename);
builder.AppendFormat(" LOG ON (NAME='{0}', FILENAME='{1}')", Path.GetFileName(logFilename), logFilename);
}
return builder.ToString();
}
public IEnumerable<string> GetCreateForeignKeyCommands(MetaTable table)
{
foreach (var metaType in table.RowType.InheritanceTypes)
{
foreach (var command in GetCreateForeignKeyCommands(metaType))
{
yield return command;
}
}
}
private IEnumerable<string> GetCreateForeignKeyCommands(MetaType metaType)
{
foreach (var member in metaType.DataMembers)
{
if (member.IsDeclaredBy(metaType) && member.IsAssociation)
{
MetaAssociation association = member.Association;
if (association.IsForeignKey)
{
var stringBuilder = new StringBuilder();
var thisKey = BuildKey(association.ThisKey);
var otherKey = BuildKey(association.OtherKey);
var otherTable = association.OtherType.Table.TableName;
var mappedName = member.MappedName;
if (mappedName == member.Name)
{
mappedName = string.Format(CultureInfo.InvariantCulture, "FK_{0}_{1}",
new object[] { metaType.Table.TableName, member.Name });
}
var command = "ALTER TABLE {0}" + Environment.NewLine +
" ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3}({4})";
var otherMember = association.OtherMember;
if (otherMember != null)
{
string deleteRule = association.DeleteRule;
if (deleteRule != null)
{
command += Environment.NewLine + " ON DELETE " + deleteRule;
}
}
yield return stringBuilder.AppendFormat(command, new object[]
{
SqlIdentifier.QuoteCompoundIdentifier(metaType.Table.TableName),
SqlIdentifier.QuoteIdentifier(mappedName),
SqlIdentifier.QuoteCompoundIdentifier(thisKey),
SqlIdentifier.QuoteCompoundIdentifier(otherTable),
SqlIdentifier.QuoteCompoundIdentifier(otherKey)
}).ToString();
}
}
}
}
public string GetCreateSchemaForTableCommand(MetaTable table)
{
var builder = new StringBuilder();
var list = new List<string>(SqlIdentifier.GetCompoundIdentifierParts(table.TableName));
if (list.Count < 2)
{
return null;
}
string strA = list[list.Count - 2];
if ((string.Compare(strA, "DBO", StringComparison.OrdinalIgnoreCase) != 0) &&
(string.Compare(strA, "[DBO]", StringComparison.OrdinalIgnoreCase) != 0))
{
builder.AppendFormat("CREATE SCHEMA {0}", SqlIdentifier.QuoteIdentifier(strA));
}
return builder.ToString();
}
public string GetCreateTableCommand(MetaTable table)
{
var builder = new StringBuilder();
var sb = new StringBuilder();
BuildFieldDeclarations(table, sb);
builder.AppendFormat("CREATE TABLE {0}", SqlIdentifier.QuoteCompoundIdentifier(table.TableName));
builder.Append("(");
builder.Append(sb.ToString());
sb = new StringBuilder();
BuildPrimaryKey(table, sb);
if (sb.Length > 0)
{
string s = string.Format(CultureInfo.InvariantCulture, "PK_{0}", new object[] { table.TableName });
builder.Append(", ");
builder.AppendLine();
builder.AppendFormat(" CONSTRAINT {0} PRIMARY KEY ({1})", SqlIdentifier.QuoteIdentifier(s), sb);
}
builder.AppendLine();
builder.Append(" )");
return builder.ToString();
}
private string GetDbType(MetaDataMember mm)
{
string dbType = mm.DbType;
if (dbType != null)
{
return dbType;
}
var builder = new StringBuilder();
Type type = mm.Type;
bool canBeNull = mm.CanBeNull;
if (type.IsValueType && IsNullable(type))
{
type = type.GetGenericArguments()[0];
}
if (mm.IsVersion)
{
builder.Append("Timestamp");
}
else if (mm.IsPrimaryKey && mm.IsDbGenerated)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Object:
if (type != typeof(Guid))
{
throw SqlClient.Error.CouldNotDetermineDbGeneratedSqlType(type);
}
builder.Append("UniqueIdentifier");
goto Label_02AD;
case TypeCode.DBNull:
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.Single:
case TypeCode.Double:
goto Label_02AD;
case TypeCode.SByte:
case TypeCode.Int16:
builder.Append("SmallInt");
goto Label_02AD;
case TypeCode.Byte:
builder.Append("TinyInt");
goto Label_02AD;
case TypeCode.UInt16:
case TypeCode.Int32:
builder.Append("Int");
goto Label_02AD;
case TypeCode.UInt32:
case TypeCode.Int64:
builder.Append("BigInt");
goto Label_02AD;
case TypeCode.UInt64:
case TypeCode.Decimal:
builder.Append("Decimal(20)");
goto Label_02AD;
}
}
else
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Object:
if (type != typeof(Guid))
{
if (type == typeof(byte[]))
{
builder.Append("VarBinary(8000)");
}
else
{
if (type == typeof(char[]) || type == typeof(XDocument) ||
type == typeof(XElement))
{
builder.Append("VarChar(4000)");
}
else if (type == typeof(ALinq.Binary))
{
builder.Append("Image");
}
else
{
throw SqlClient.Error.CouldNotDetermineSqlType(type);
}
}
}
else
{
builder.Append("UniqueIdentifier");
}
goto Label_02AD;
case TypeCode.DBNull:
case (TypeCode.DateTime | TypeCode.Object):
goto Label_02AD;
case TypeCode.Boolean:
builder.Append("Bit");
goto Label_02AD;
case TypeCode.Char:
builder.Append("Char(1)");
goto Label_02AD;
case TypeCode.SByte:
case TypeCode.Int16:
builder.Append("SmallInt");
goto Label_02AD;
case TypeCode.Byte:
builder.Append("TinyInt");
goto Label_02AD;
case TypeCode.UInt16:
case TypeCode.Int32:
builder.Append("Int");
goto Label_02AD;
case TypeCode.UInt32:
case TypeCode.Int64:
builder.Append("BigInt");
goto Label_02AD;
case TypeCode.UInt64:
builder.Append("Decimal(20)");
goto Label_02AD;
case TypeCode.Single:
builder.Append("Real");
goto Label_02AD;
case TypeCode.Double:
builder.Append("Float");
goto Label_02AD;
case TypeCode.Decimal:
builder.Append("Decimal(29, 4)");
goto Label_02AD;
case TypeCode.DateTime:
builder.Append("DateTime");
goto Label_02AD;
case TypeCode.String:
builder.Append("VarChar(4000)");
goto Label_02AD;
}
}
Label_02AD:
if (!canBeNull)
{
builder.Append(" NOT NULL");
}
if (mm.IsPrimaryKey && mm.IsDbGenerated)
{
if (type == typeof(Guid))
{
builder.Append(" DEFAULT NEWID()");
}
else
{
builder.Append(" IDENTITY");
}
}
return builder.ToString();
}
internal string GetDropDatabaseCommand(string catalog)
{
StringBuilder builder = new StringBuilder();
builder.AppendFormat("DROP DATABASE {0}", SqlIdentifier.QuoteIdentifier(catalog));
return builder.ToString();
}
internal bool IsNullable(Type type)
{
return (type.IsGenericType && typeof(Nullable<>).IsAssignableFrom(type.GetGenericTypeDefinition()));
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WebCam_Capture
{
/// <summary>
/// Class to abstract Webcam capturing
/// </summary>
public class WebCamCapture : System.Windows.Forms.UserControl
{
#region Member Data
private System.Windows.Forms.Timer timer1;
// property variables
private int m_TimeToCapture_milliseconds = 100;
private int m_Width = 320;
private int m_Height = 240;
private int mCapHwnd;
private ulong m_FrameNumber = 0;
// global variables to make the video capture go faster
private WebCam_Capture.WebcamEventArgs x = new WebCam_Capture.WebcamEventArgs();
private IDataObject tempObj;
private System.Drawing.Image tempImg;
private bool bStopped = true;
// event delegate
public delegate void WebCamEventHandler (object source, WebCam_Capture.WebcamEventArgs e);
// fired when a new image is captured
public event WebCamEventHandler ImageCaptured;
#endregion
#region Constructor, Deconstructor, Dispose
public WebCamCapture()
{
this.timer1 = new System.Windows.Forms.Timer();
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
}
/// <summary>
/// Override the class's finalize method, so we can stop
/// the video capture on exit
/// </summary>
~WebCamCapture()
{
this.Stop();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
this.timer1.Stop();
this.timer1.Dispose();
if(this.tempImg != null)
this.tempImg.Dispose();
}
base.Dispose( disposing );
}
#endregion
#region API Declarations
[DllImport("user32", EntryPoint="SendMessage")]
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
[DllImport("avicap32.dll", EntryPoint="capCreateCaptureWindowA")]
public static extern int capCreateCaptureWindowA(string lpszWindowName, int dwStyle, int X, int Y, int nWidth, int nHeight, int hwndParent, int nID);
[DllImport("user32", EntryPoint="OpenClipboard")]
public static extern int OpenClipboard(int hWnd);
[DllImport("user32", EntryPoint="EmptyClipboard")]
public static extern int EmptyClipboard();
[DllImport("user32", EntryPoint="CloseClipboard")]
public static extern int CloseClipboard();
#endregion
#region API Constants
public const int WM_USER = 1024;
public const int WM_CAP_CONNECT = 1034;
public const int WM_CAP_DISCONNECT = 1035;
public const int WM_CAP_GET_FRAME = 1084;
public const int WM_CAP_COPY = 1054;
public const int WM_CAP_START = WM_USER;
public const int WM_CAP_DLG_VIDEOFORMAT = WM_CAP_START + 41;
public const int WM_CAP_DLG_VIDEOSOURCE = WM_CAP_START + 42;
public const int WM_CAP_DLG_VIDEODISPLAY = WM_CAP_START + 43;
public const int WM_CAP_GET_VIDEOFORMAT = WM_CAP_START + 44;
public const int WM_CAP_SET_VIDEOFORMAT = WM_CAP_START + 45;
public const int WM_CAP_DLG_VIDEOCOMPRESSION = WM_CAP_START + 46;
public const int WM_CAP_SET_PREVIEW = WM_CAP_START + 50;
#endregion
#region NOTES
/*
* If you want to allow the user to change the display size and
* color format of the video capture, call:
* SendMessage (mCapHwnd, WM_CAP_DLG_VIDEOFORMAT, 0, 0);
* You will need to requery the capture device to get the new settings
*/
#endregion
#region Control Properties
/// <summary>
/// The time intervale between frame captures
/// </summary>
public int TimeToCapture_milliseconds
{
get
{ return m_TimeToCapture_milliseconds; }
set
{ m_TimeToCapture_milliseconds = value; }
}
/// <summary>
/// The height of the video capture image
/// </summary>
public int CaptureHeight
{
get
{ return m_Height; }
set
{ m_Height = value; }
}
/// <summary>
/// The width of the video capture image
/// </summary>
public int CaptureWidth
{
get
{ return m_Width; }
set
{ m_Width = value; }
}
/// <summary>
/// The sequence number to start at for the frame number. OPTIONAL
/// </summary>
public ulong FrameNumber
{
get
{ return m_FrameNumber; }
set
{ m_FrameNumber = value; }
}
#endregion
#region Start and Stop Capture Functions
/// <summary>
/// Starts the video capture
/// </summary>
/// <param name="FrameNumber">the frame number to start at.
/// Set to 0 to let the control allocate the frame number</param>
public void Start(ulong FrameNum)
{
try
{
// for safety, call stop, just in case we are already running
this.Stop();
// setup a capture window
mCapHwnd = capCreateCaptureWindowA("WebCap", 0, 0, 0, m_Width, m_Height, this.Handle.ToInt32(), 0);
// connect to the capture device
Application.DoEvents();
SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0);
SendMessage(mCapHwnd, WM_CAP_SET_PREVIEW, 0, 0);
// set the frame number
m_FrameNumber = FrameNum;
// set the timer information
this.timer1.Interval = m_TimeToCapture_milliseconds;
bStopped = false;
this.timer1.Start();
}
catch (Exception excep)
{
MessageBox.Show("An error ocurred while starting the video capture. Check that your webcamera is connected properly and turned on.\r\n\n" + excep.Message);
this.Stop();
}
}
/// <summary>
/// Stops the video capture
/// </summary>
public void Stop()
{
try
{
// stop the timer
bStopped = true;
this.timer1.Stop();
// disconnect from the video source
Application.DoEvents();
SendMessage(mCapHwnd, WM_CAP_DISCONNECT, 0, 0);
}
catch (Exception excep)
{
LibUSBLauncher.Log.Instance.Out(excep);
}
}
#endregion
#region Video Capture Code
/// <summary>
/// Capture the next frame from the video feed
/// </summary>
private void timer1_Tick(object sender, System.EventArgs e)
{
try
{
// pause the timer
this.timer1.Stop();
// get the next frame;
SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0);
// copy the frame to the clipboard
SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0);
// paste the frame into the event args image
if (ImageCaptured != null)
{
// get from the clipboard
tempObj = Clipboard.GetDataObject();
tempImg = (System.Drawing.Bitmap) tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap);
GC.Collect();
/*
* For some reason, the API is not resizing the video
* feed to the width and height provided when the video
* feed was started, so we must resize the image here
*/
x.WebCamImage = tempImg.GetThumbnailImage(m_Width, m_Height, null, System.IntPtr.Zero);
// raise the event
this.ImageCaptured(this, x);
}
// restart the timer
Application.DoEvents();
if (! bStopped)
this.timer1.Start();
}
catch (Exception excep)
{
LibUSBLauncher.Log.Instance.Out(excep);
this.Stop(); // stop the process
}
}
public bool Stopped
{
get { return this.bStopped; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Hosting.Providers;
using Microsoft.Scripting.Runtime;
using IronPython.Modules;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
namespace IronPython.Hosting {
/// <summary>
/// Provides helpers for interacting with IronPython.
/// </summary>
public static class Python {
#region Public APIs
/// <summary>
/// Creates a new ScriptRuntime with the IronPython scipting engine pre-configured.
/// </summary>
/// <returns></returns>
public static ScriptRuntime/*!*/ CreateRuntime() {
return new ScriptRuntime(CreateRuntimeSetup(null));
}
/// <summary>
/// Creates a new ScriptRuntime with the IronPython scipting engine pre-configured and
/// additional options.
/// </summary>
public static ScriptRuntime/*!*/ CreateRuntime(IDictionary<string, object> options) {
return new ScriptRuntime(CreateRuntimeSetup(options));
}
#if FEATURE_REMOTING
/// <summary>
/// Creates a new ScriptRuntime with the IronPython scripting engine pre-configured
/// in the specified AppDomain. The remote ScriptRuntime may be manipulated from
/// the local domain but all code will run in the remote domain.
/// </summary>
public static ScriptRuntime/*!*/ CreateRuntime(AppDomain/*!*/ domain) {
ContractUtils.RequiresNotNull(domain, "domain");
return ScriptRuntime.CreateRemote(domain, CreateRuntimeSetup(null));
}
/// <summary>
/// Creates a new ScriptRuntime with the IronPython scripting engine pre-configured
/// in the specified AppDomain with additional options. The remote ScriptRuntime may
/// be manipulated from the local domain but all code will run in the remote domain.
/// </summary>
public static ScriptRuntime/*!*/ CreateRuntime(AppDomain/*!*/ domain, IDictionary<string, object> options) {
ContractUtils.RequiresNotNull(domain, "domain");
return ScriptRuntime.CreateRemote(domain, CreateRuntimeSetup(options));
}
#endif
/// <summary>
/// Creates a new ScriptRuntime and returns the ScriptEngine for IronPython. If
/// the ScriptRuntime is required it can be acquired from the Runtime property
/// on the engine.
/// </summary>
public static ScriptEngine/*!*/ CreateEngine() {
return GetEngine(CreateRuntime());
}
/// <summary>
/// Creates a new ScriptRuntime with the specified options and returns the
/// ScriptEngine for IronPython. If the ScriptRuntime is required it can be
/// acquired from the Runtime property on the engine.
/// </summary>
public static ScriptEngine/*!*/ CreateEngine(IDictionary<string, object> options) {
return GetEngine(CreateRuntime(options));
}
#if FEATURE_REMOTING
/// <summary>
/// Creates a new ScriptRuntime and returns the ScriptEngine for IronPython. If
/// the ScriptRuntime is required it can be acquired from the Runtime property
/// on the engine.
///
/// The remote ScriptRuntime may be manipulated from the local domain but
/// all code will run in the remote domain.
/// </summary>
public static ScriptEngine/*!*/ CreateEngine(AppDomain/*!*/ domain) {
return GetEngine(CreateRuntime(domain));
}
/// <summary>
/// Creates a new ScriptRuntime with the specified options and returns the
/// ScriptEngine for IronPython. If the ScriptRuntime is required it can be
/// acquired from the Runtime property on the engine.
///
/// The remote ScriptRuntime may be manipulated from the local domain but
/// all code will run in the remote domain.
/// </summary>
public static ScriptEngine/*!*/ CreateEngine(AppDomain/*!*/ domain, IDictionary<string, object> options) {
return GetEngine(CreateRuntime(domain, options));
}
#endif
/// <summary>
/// Given a ScriptRuntime gets the ScriptEngine for IronPython.
/// </summary>
public static ScriptEngine/*!*/ GetEngine(ScriptRuntime/*!*/ runtime) {
return runtime.GetEngineByTypeName(typeof(PythonContext).AssemblyQualifiedName);
}
/// <summary>
/// Gets a ScriptScope which is the Python sys module for the provided ScriptRuntime.
/// </summary>
public static ScriptScope/*!*/ GetSysModule(this ScriptRuntime/*!*/ runtime) {
ContractUtils.RequiresNotNull(runtime, "runtime");
return GetSysModule(GetEngine(runtime));
}
/// <summary>
/// Gets a ScriptScope which is the Python sys module for the provided ScriptEngine.
/// </summary>
public static ScriptScope/*!*/ GetSysModule(this ScriptEngine/*!*/ engine) {
ContractUtils.RequiresNotNull(engine, "engine");
return GetPythonService(engine).GetSystemState();
}
/// <summary>
/// Gets a ScriptScope which is the Python __builtin__ module for the provided ScriptRuntime.
/// </summary>
public static ScriptScope/*!*/ GetBuiltinModule(this ScriptRuntime/*!*/ runtime) {
ContractUtils.RequiresNotNull(runtime, "runtime");
return GetBuiltinModule(GetEngine(runtime));
}
/// <summary>
/// Gets a ScriptScope which is the Python __builtin__ module for the provided ScriptEngine.
/// </summary>
public static ScriptScope/*!*/ GetBuiltinModule(this ScriptEngine/*!*/ engine) {
ContractUtils.RequiresNotNull(engine, "engine");
return GetPythonService(engine).GetBuiltins();
}
/// <summary>
/// Gets a ScriptScope which is the Python clr module for the provided ScriptRuntime.
/// </summary>
public static ScriptScope/*!*/ GetClrModule(this ScriptRuntime/*!*/ runtime) {
ContractUtils.RequiresNotNull(runtime, "runtime");
return GetClrModule(GetEngine(runtime));
}
/// <summary>
/// Gets a ScriptScope which is the Python clr module for the provided ScriptEngine.
/// </summary>
public static ScriptScope/*!*/ GetClrModule(this ScriptEngine/*!*/ engine) {
ContractUtils.RequiresNotNull(engine, "engine");
return GetPythonService(engine).GetClr();
}
/// <summary>
/// Imports the Python module by the given name and returns its ScriptSCope. If the
/// module does not exist an exception is raised.
/// </summary>
public static ScriptScope/*!*/ ImportModule(this ScriptRuntime/*!*/ runtime, string/*!*/ moduleName) {
ContractUtils.RequiresNotNull(runtime, "runtime");
ContractUtils.RequiresNotNull(moduleName, "moduleName");
return ImportModule(GetEngine(runtime), moduleName);
}
/// <summary>
/// Imports the Python module by the given name and returns its ScriptSCope. If the
/// module does not exist an exception is raised.
/// </summary>
public static ScriptScope/*!*/ ImportModule(this ScriptEngine/*!*/ engine, string/*!*/ moduleName) {
ContractUtils.RequiresNotNull(engine, "engine");
ContractUtils.RequiresNotNull(moduleName, "moduleName");
return GetPythonService(engine).ImportModule(engine, moduleName);
}
/// <summary>
/// Imports the Python module by the given name and inserts it into the ScriptScope as that name. If the
/// module does not exist an exception is raised.
/// </summary>
/// <param name="scope"></param>
/// <param name="moduleName"></param>
public static void ImportModule (this ScriptScope/*!*/ scope, string/*!*/ moduleName) {
ContractUtils.RequiresNotNull (scope, "scope");
ContractUtils.RequiresNotNull (moduleName, "moduleName");
scope.SetVariable (moduleName, scope.Engine.ImportModule (moduleName));
}
/// <summary>
/// Sets sys.exec_prefix, sys.executable and sys.version and adds the prefix to sys.path
/// </summary>
public static void SetHostVariables(this ScriptRuntime/*!*/ runtime, string/*!*/ prefix, string/*!*/ executable, string/*!*/ version) {
ContractUtils.RequiresNotNull(runtime, "runtime");
ContractUtils.RequiresNotNull(prefix, "prefix");
ContractUtils.RequiresNotNull(executable, "executable");
ContractUtils.RequiresNotNull(version, "version");
GetPythonContext(GetEngine(runtime)).SetHostVariables(prefix, executable, version);
}
/// <summary>
/// Sets sys.exec_prefix, sys.executable and sys.version and adds the prefix to sys.path
/// </summary>
public static void SetHostVariables(this ScriptEngine/*!*/ engine, string/*!*/ prefix, string/*!*/ executable, string/*!*/ version) {
ContractUtils.RequiresNotNull(engine, "engine");
ContractUtils.RequiresNotNull(prefix, "prefix");
ContractUtils.RequiresNotNull(executable, "executable");
ContractUtils.RequiresNotNull(version, "version");
GetPythonContext(engine).SetHostVariables(prefix, executable, version);
}
/// <summary>
/// Enables call tracing for the current thread in this ScriptEngine.
///
/// TracebackDelegate will be called back for each function entry, exit, exception, and line change.
/// </summary>
public static void SetTrace(this ScriptEngine/*!*/ engine, TracebackDelegate traceFunc) {
SysModule.settrace(GetPythonContext(engine).SharedContext, traceFunc);
}
/// <summary>
/// Enables call tracing for the current thread for the Python engine in this ScriptRuntime.
///
/// TracebackDelegate will be called back for each function entry, exit, exception, and line change.
/// </summary>
public static void SetTrace(this ScriptRuntime/*!*/ runtime, TracebackDelegate traceFunc) {
SetTrace(GetEngine(runtime), traceFunc);
}
/// <summary>
/// Provides nested level debugging support when SetTrace or SetProfile are used.
///
/// This saves the current tracing information and then calls the provided object.
/// </summary>
public static void CallTracing(this ScriptRuntime/*!*/ runtime, object traceFunc, params object[] args) {
CallTracing(GetEngine(runtime), traceFunc, args);
}
/// <summary>
/// Provides nested level debugging support when SetTrace or SetProfile are used.
///
/// This saves the current tracing information and then calls the provided object.
/// </summary>
public static void CallTracing(this ScriptEngine/*!*/ engine, object traceFunc, params object[] args) {
SysModule.call_tracing(GetPythonContext(engine).SharedContext, traceFunc, PythonTuple.MakeTuple(args));
}
/// <summary>
/// Creates a ScriptRuntimeSetup object which includes the Python script engine with the specified options.
///
/// The ScriptRuntimeSetup object can then be additional configured and used to create a ScriptRuntime.
/// </summary>
public static ScriptRuntimeSetup/*!*/ CreateRuntimeSetup(IDictionary<string, object> options) {
ScriptRuntimeSetup setup = new ScriptRuntimeSetup();
setup.LanguageSetups.Add(CreateLanguageSetup(options));
if (options != null) {
object value;
if (options.TryGetValue("Debug", out value) &&
value is bool &&
(bool)value) {
setup.DebugMode = true;
}
if (options.TryGetValue("PrivateBinding", out value) &&
value is bool &&
(bool)value) {
setup.PrivateBinding = true;
}
}
return setup;
}
/// <summary>
/// Creates a LanguageSetup object which includes the Python script engine with the specified options.
///
/// The LanguageSetup object can be used with other LanguageSetup objects from other languages to
/// configure a ScriptRuntimeSetup object.
/// </summary>
public static LanguageSetup/*!*/ CreateLanguageSetup(IDictionary<string, object> options) {
var setup = new LanguageSetup(
typeof(PythonContext).AssemblyQualifiedName,
PythonContext.IronPythonDisplayName,
PythonContext.IronPythonNames.Split(';'),
PythonContext.IronPythonFileExtensions.Split(';')
);
if (options != null) {
foreach (var entry in options) {
setup.Options.Add(entry.Key, entry.Value);
}
}
return setup;
}
/// <summary>
/// Creates a new PythonModule with the specified name and published it in sys.modules.
///
/// Returns the ScriptScope associated with the module.
/// </summary>
public static ScriptScope CreateModule(this ScriptEngine engine, string name) {
return GetPythonService(engine).CreateModule(name, String.Empty, String.Empty);
}
/// <summary>
/// Creates a new PythonModule with the specified name and filename published it
/// in sys.modules.
///
/// Returns the ScriptScope associated with the module.
/// </summary>
public static ScriptScope CreateModule(this ScriptEngine engine, string name, string filename) {
return GetPythonService(engine).CreateModule(name, filename, String.Empty);
}
/// <summary>
/// Creates a new PythonModule with the specified name, filename, and doc string and
/// published it in sys.modules.
///
/// Returns the ScriptScope associated with the module.
/// </summary>
public static ScriptScope CreateModule(this ScriptEngine engine, string name, string filename, string docString) {
return GetPythonService(engine).CreateModule(name, filename, docString);
}
/// <summary>
/// Gets the list of loaded Python module files names which are available in the provided ScriptEngine.
/// </summary>
public static string[] GetModuleFilenames(this ScriptEngine engine) {
return GetPythonService(engine).GetModuleFilenames();
}
#endregion
#region Private helpers
private static PythonService/*!*/ GetPythonService(ScriptEngine/*!*/ engine) {
return engine.GetService<PythonService>(engine);
}
private static PythonContext/*!*/ GetPythonContext(ScriptEngine/*!*/ engine) {
return HostingHelpers.GetLanguageContext(engine) as PythonContext;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// UnionQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Operator that yields the union of two data sources.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
internal sealed class UnionQueryOperator<TInputOutput> :
BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput>
{
private readonly IEqualityComparer<TInputOutput> _comparer; // An equality comparer.
//---------------------------------------------------------------------------------------
// Constructs a new union operator.
//
internal UnionQueryOperator(ParallelQuery<TInputOutput> left, ParallelQuery<TInputOutput> right, IEqualityComparer<TInputOutput> comparer)
: base(left, right)
{
Debug.Assert(left != null && right != null, "child data sources cannot be null");
_comparer = comparer;
_outputOrdered = LeftChild.OutputOrdered || RightChild.OutputOrdered;
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TInputOutput> Open(
QuerySettings settings, bool preferStriping)
{
// We just open our child operators, left and then right. Do not propagate the preferStriping value, but
// instead explicitly set it to false. Regardless of whether the parent prefers striping or range
// partitioning, the output will be hash-partititioned.
QueryResults<TInputOutput> leftChildResults = LeftChild.Open(settings, false);
QueryResults<TInputOutput> rightChildResults = RightChild.Open(settings, false);
return new BinaryQueryOperatorResults(leftChildResults, rightChildResults, this, settings, false);
}
public override void WrapPartitionedStream<TLeftKey, TRightKey>(
PartitionedStream<TInputOutput, TLeftKey> leftStream, PartitionedStream<TInputOutput, TRightKey> rightStream,
IPartitionedStreamRecipient<TInputOutput> outputRecipient, bool preferStriping, QuerySettings settings)
{
Debug.Assert(leftStream.PartitionCount == rightStream.PartitionCount);
int partitionCount = leftStream.PartitionCount;
// Wrap both child streams with hash repartition
if (LeftChild.OutputOrdered)
{
PartitionedStream<Pair, TLeftKey> leftHashStream =
ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TLeftKey>(
leftStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken);
WrapPartitionedStreamFixedLeftType<TLeftKey, TRightKey>(
leftHashStream, rightStream, outputRecipient, partitionCount, settings.CancellationState.MergedCancellationToken);
}
else
{
PartitionedStream<Pair, int> leftHashStream =
ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TLeftKey>(
leftStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken);
WrapPartitionedStreamFixedLeftType<int, TRightKey>(
leftHashStream, rightStream, outputRecipient, partitionCount, settings.CancellationState.MergedCancellationToken);
}
}
//---------------------------------------------------------------------------------------
// A helper method that allows WrapPartitionedStream to fix the TLeftKey type parameter.
//
private void WrapPartitionedStreamFixedLeftType<TLeftKey, TRightKey>(
PartitionedStream<Pair, TLeftKey> leftHashStream, PartitionedStream<TInputOutput, TRightKey> rightStream,
IPartitionedStreamRecipient<TInputOutput> outputRecipient, int partitionCount, CancellationToken cancellationToken)
{
if (RightChild.OutputOrdered)
{
PartitionedStream<Pair, TRightKey> rightHashStream =
ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TRightKey>(
rightStream, null, null, _comparer, cancellationToken);
WrapPartitionedStreamFixedBothTypes<TLeftKey, TRightKey>(
leftHashStream, rightHashStream, outputRecipient, partitionCount, cancellationToken);
}
else
{
PartitionedStream<Pair, int> rightHashStream =
ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TRightKey>(
rightStream, null, null, _comparer, cancellationToken);
WrapPartitionedStreamFixedBothTypes<TLeftKey, int>(
leftHashStream, rightHashStream, outputRecipient, partitionCount, cancellationToken);
}
}
//---------------------------------------------------------------------------------------
// A helper method that allows WrapPartitionedStreamHelper to fix the TRightKey type parameter.
//
private void WrapPartitionedStreamFixedBothTypes<TLeftKey, TRightKey>(
PartitionedStream<Pair, TLeftKey> leftHashStream,
PartitionedStream<Pair, TRightKey> rightHashStream,
IPartitionedStreamRecipient<TInputOutput> outputRecipient, int partitionCount,
CancellationToken cancellationToken)
{
if (LeftChild.OutputOrdered || RightChild.OutputOrdered)
{
IComparer<ConcatKey> compoundKeyComparer =
ConcatKey.MakeComparer(leftHashStream.KeyComparer, rightHashStream.KeyComparer);
PartitionedStream<TInputOutput, ConcatKey> outputStream =
new PartitionedStream<TInputOutput, ConcatKey>(partitionCount, compoundKeyComparer, OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new OrderedUnionQueryOperatorEnumerator<TLeftKey, TRightKey>(
leftHashStream[i], rightHashStream[i], LeftChild.OutputOrdered, RightChild.OutputOrdered,
_comparer, compoundKeyComparer, cancellationToken);
}
outputRecipient.Receive(outputStream);
}
else
{
PartitionedStream<TInputOutput, int> outputStream =
new PartitionedStream<TInputOutput, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new UnionQueryOperatorEnumerator<TLeftKey, TRightKey>(
leftHashStream[i], rightHashStream[i], i, _comparer, cancellationToken);
}
outputRecipient.Receive(outputStream);
}
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TInputOutput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token);
IEnumerable<TInputOutput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token);
return wrappedLeftChild.Union(wrappedRightChild, _comparer);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// This enumerator performs the union operation incrementally. It does this by maintaining
// a history -- in the form of a set -- of all data already seen. It is careful not to
// return any duplicates.
//
class UnionQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TInputOutput, int>
{
private QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left data source.
private QueryOperatorEnumerator<Pair, TRightKey> _rightSource; // Right data source.
private readonly int _partitionIndex; // The current partition.
private Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the union.
private CancellationToken _cancellationToken;
private Shared<int> _outputLoopCount;
private readonly IEqualityComparer<TInputOutput> _comparer;
//---------------------------------------------------------------------------------------
// Instantiates a new union operator.
//
internal UnionQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TLeftKey> leftSource,
QueryOperatorEnumerator<Pair, TRightKey> rightSource,
int partitionIndex, IEqualityComparer<TInputOutput> comparer,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(rightSource != null);
_leftSource = leftSource;
_rightSource = rightSource;
_partitionIndex = partitionIndex;
_comparer = comparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the two data sources, left and then right, to produce the union.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey)
{
if (_hashLookup == null)
{
_hashLookup = new Set<TInputOutput>(_comparer);
_outputLoopCount = new Shared<int>(0);
}
Debug.Assert(_hashLookup != null);
// Enumerate the left and then right data source. When each is done, we set the
// field to null so we will skip it upon subsequent calls to MoveNext.
if (_leftSource != null)
{
// Iterate over this set's elements until we find a unique element.
TLeftKey keyUnused = default(TLeftKey);
Pair currentLeftElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired));
int i = 0;
while (_leftSource.MoveNext(ref currentLeftElement, ref keyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We ensure we never return duplicates by tracking them in our set.
if (_hashLookup.Add((TInputOutput)currentLeftElement.First))
{
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
currentElement = (TInputOutput)currentLeftElement.First;
return true;
}
}
_leftSource.Dispose();
_leftSource = null;
}
if (_rightSource != null)
{
// Iterate over this set's elements until we find a unique element.
TRightKey keyUnused = default(TRightKey);
Pair currentRightElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired));
while (_rightSource.MoveNext(ref currentRightElement, ref keyUnused))
{
if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We ensure we never return duplicates by tracking them in our set.
if (_hashLookup.Add((TInputOutput)currentRightElement.First))
{
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
currentElement = (TInputOutput)currentRightElement.First;
return true;
}
}
_rightSource.Dispose();
_rightSource = null;
}
return false;
}
protected override void Dispose(bool disposing)
{
if (_leftSource != null)
{
_leftSource.Dispose();
}
if (_rightSource != null)
{
_rightSource.Dispose();
}
}
}
class OrderedUnionQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TInputOutput, ConcatKey>
{
private QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left data source.
private QueryOperatorEnumerator<Pair, TRightKey> _rightSource; // Right data source.
private IComparer<ConcatKey> _keyComparer; // Comparer for compound order keys.
private IEnumerator<KeyValuePair<Wrapper<TInputOutput>, Pair>> _outputEnumerator; // Enumerator over the output of the union.
private bool _leftOrdered; // Whether the left data source is ordered.
private bool _rightOrdered; // Whether the right data source is ordered.
private IEqualityComparer<TInputOutput> _comparer; // Comparer for the elements.
private CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new union operator.
//
internal OrderedUnionQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TLeftKey> leftSource,
QueryOperatorEnumerator<Pair, TRightKey> rightSource,
bool leftOrdered, bool rightOrdered, IEqualityComparer<TInputOutput> comparer, IComparer<ConcatKey> keyComparer,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(rightSource != null);
_leftSource = leftSource;
_rightSource = rightSource;
_keyComparer = keyComparer;
_leftOrdered = leftOrdered;
_rightOrdered = rightOrdered;
_comparer = comparer;
if (_comparer == null)
{
_comparer = EqualityComparer<TInputOutput>.Default;
}
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the two data sources, left and then right, to produce the union.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref ConcatKey currentKey)
{
Debug.Assert(_leftSource != null);
Debug.Assert(_rightSource != null);
if (_outputEnumerator == null)
{
IEqualityComparer<Wrapper<TInputOutput>> wrapperComparer = new WrapperEqualityComparer<TInputOutput>(_comparer);
Dictionary<Wrapper<TInputOutput>, Pair> union =
new Dictionary<Wrapper<TInputOutput>, Pair>(wrapperComparer);
Pair elem = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired));
TLeftKey leftKey = default(TLeftKey);
int i = 0;
while (_leftSource.MoveNext(ref elem, ref leftKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
ConcatKey key =
ConcatKey.MakeLeft<TLeftKey, TRightKey>(_leftOrdered ? leftKey : default(TLeftKey));
Pair oldEntry;
Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>((TInputOutput)elem.First);
if (!union.TryGetValue(wrappedElem, out oldEntry) || _keyComparer.Compare(key, (ConcatKey)oldEntry.Second) < 0)
{
union[wrappedElem] = new Pair(elem.First, key);
}
}
TRightKey rightKey = default(TRightKey);
while (_rightSource.MoveNext(ref elem, ref rightKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
ConcatKey key =
ConcatKey.MakeRight<TLeftKey, TRightKey>(_rightOrdered ? rightKey : default(TRightKey));
Pair oldEntry;
Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>((TInputOutput)elem.First);
if (!union.TryGetValue(wrappedElem, out oldEntry) || _keyComparer.Compare(key, (ConcatKey)oldEntry.Second) < 0)
{
union[wrappedElem] = new Pair(elem.First, key); ;
}
}
_outputEnumerator = union.GetEnumerator();
}
if (_outputEnumerator.MoveNext())
{
Pair current = _outputEnumerator.Current.Value;
currentElement = (TInputOutput)current.First;
currentKey = (ConcatKey)current.Second;
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_leftSource != null && _rightSource != null);
_leftSource.Dispose();
_rightSource.Dispose();
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Residence type: Apartment complex.
/// </summary>
public class ApartmentComplex_Core : TypeCore, IResidence
{
public ApartmentComplex_Core()
{
this._TypeId = 17;
this._Id = "ApartmentComplex";
this._Schema_Org_Url = "http://schema.org/ApartmentComplex";
string label = "";
GetLabel(out label, "ApartmentComplex", typeof(ApartmentComplex_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,227};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{227};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using NUnit.Framework;
using Sendwithus;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace SendwithusTest
{
/// <summary>
/// A class to test the sendwithus API's retry functionality.
/// Covers the number of retries and the interval between retries
/// </summary>
[TestFixture]
public class RetryTest
{
private const int FAILURE_TIMEOUT_MILLISECONDS = 1; // 1ms
private const string DEFAULT_TEMPLATE_ID = "tem_SxZKpxJSHPbYDWRSQnAQUR";
private const string DEFAULT_ESP_ACCOUNT_ID = "esp_pmUQQ7aRUhWYUrfeJqwPwB";
private const int NON_DEFAULT_RETRY_COUNT = SendwithusClient.DEFAULT_RETRY_COUNT + 2;
private const int NON_DEFAULT_RETRY_INTERVAL_MILLISECONDS = 1000; // 1 second
/// <summary>
/// Sets the API
/// </summary>
[SetUp]
public void InitializeUnitTesting()
{
// Set the API key
SendwithusClient.ApiKey = SendwithusClientTest.API_KEY_TEST;
}
/// <summary>
/// Tests that the default retry count works with an HTTP GET request
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestDefaultRetryCountWithGetAsync()
{
// Set the timeout low enough that the API call is guaranteed to fail
SendwithusClient.SetTimeoutInMilliseconds(FAILURE_TIMEOUT_MILLISECONDS);
// Make sure we're using the default number of retries
SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
// Send a GET request
try
{
var response = await Template.GetTemplateAsync(DEFAULT_TEMPLATE_ID);
}
catch (Exception ex)
{
SendwithusClientTest.ValidateAggregateException<TaskCanceledException>(SendwithusClient.DEFAULT_RETRY_COUNT, ex);
}
finally
{
// Set the timeout back to its default value
SendwithusClient.SetTimeoutInMilliseconds(SendwithusClient.DEFAULT_TIMEOUT_MILLISECONDS);
}
}
/// <summary>
/// Tests that the default retry count works with an HTTP PUT request
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestDefaultRetryCountWithPutAsync()
{
// Set the timeout low enough that the API call is guaranteed to fail
SendwithusClient.SetTimeoutInMilliseconds(FAILURE_TIMEOUT_MILLISECONDS);
// Make sure we're using the default number of retries
SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
// Send a PUT request
try
{
var updateTemplateResponse = await TemplateTest.UpdateTemplateVersionAsync();
}
catch (Exception ex)
{
SendwithusClientTest.ValidateAggregateException<TaskCanceledException>(SendwithusClient.DEFAULT_RETRY_COUNT, ex);
}
finally
{
// Set the timeout back to its default value
SendwithusClient.SetTimeoutInMilliseconds(SendwithusClient.DEFAULT_TIMEOUT_MILLISECONDS);
}
}
/// <summary>
/// Tests that the default retry count works with an HTTP POST request
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestDefaultRetryCountWithPostAsync()
{
// Set the timeout low enough that the API call is guaranteed to fail
SendwithusClient.SetTimeoutInMilliseconds(FAILURE_TIMEOUT_MILLISECONDS);
// Make sure we're using the default number of retries
SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
// Send a POST request
try
{
var createTemplateResponse = await TemplateTest.BuildAndSendCreateTemplateRequestWithAllParametersAsync();
}
catch (Exception ex)
{
SendwithusClientTest.ValidateAggregateException<TaskCanceledException>(SendwithusClient.DEFAULT_RETRY_COUNT, ex);
}
finally
{
// Set the timeout back to its default value
SendwithusClient.SetTimeoutInMilliseconds(SendwithusClient.DEFAULT_TIMEOUT_MILLISECONDS);
}
}
/// <summary>
/// Tests that the default retry count works with an HTTP DELETE request
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestDefaultRetryCountWithDeleteAsync()
{
// Set the timeout low enough that the API call is guaranteed to fail
SendwithusClient.SetTimeoutInMilliseconds(FAILURE_TIMEOUT_MILLISECONDS);
// Make sure we're using the default number of retries
SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
// Send a DELETE request
try
{
var deleteCustomerReponse = await Customer.DeleteCustomerAsync(CustomerTest.NEW_CUSTOMER_EMAIL_ADDRESS);
}
catch (Exception ex)
{
SendwithusClientTest.ValidateAggregateException<TaskCanceledException>(SendwithusClient.DEFAULT_RETRY_COUNT, ex);
}
finally
{
// Set the timeout back to its default value
SendwithusClient.SetTimeoutInMilliseconds(SendwithusClient.DEFAULT_TIMEOUT_MILLISECONDS);
}
}
/// <summary>
/// Tests that the default retry count can be set to a non-default value
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestNonDefaultRetryCountAsync()
{
// Set the timeout low enough that the API call is guaranteed to fail
SendwithusClient.SetTimeoutInMilliseconds(FAILURE_TIMEOUT_MILLISECONDS);
// Use a non-default number of retries
SendwithusClient.RetryCount = NON_DEFAULT_RETRY_COUNT;
// Send a GET request
try
{
var response = await Template.GetTemplateAsync(DEFAULT_TEMPLATE_ID);
}
catch (Exception ex)
{
SendwithusClientTest.ValidateAggregateException<TaskCanceledException>(NON_DEFAULT_RETRY_COUNT, ex);
}
finally
{
// Set the timeout back to its default value
SendwithusClient.SetTimeoutInMilliseconds(SendwithusClient.DEFAULT_TIMEOUT_MILLISECONDS);
// Set the retry count back to its default value
SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
}
}
/// <summary>
/// Tests that the default retry interval is used properly
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestDefaultRetryInterval()
{
// Set the timeout low enough that the API call is guaranteed to fail and has a negligible effect on the run time
SendwithusClient.SetTimeoutInMilliseconds(FAILURE_TIMEOUT_MILLISECONDS);
// Make sure we're using the default number of retries
SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
// Make sure we're using the default retry interval
SendwithusClient.RetryIntervalMilliseconds = SendwithusClient.DEFAULT_RETRY_INTERVAL_MILLISECONDS;
// Send a GET request
var startTime = Stopwatch.GetTimestamp();
try
{
var response = await Template.GetTemplateAsync(DEFAULT_TEMPLATE_ID);
}
catch (Exception ex)
{
var endTime = Stopwatch.GetTimestamp();
// Make sure the API call failed on a timeout
SendwithusClientTest.ValidateAggregateException<TaskCanceledException>(SendwithusClient.DEFAULT_RETRY_COUNT, ex);
// Validate the API call's execution time
var elapsedTime = endTime - startTime;
var elapsedMilliSeconds = elapsedTime * (1000.0 / Stopwatch.Frequency);
SendwithusClientTest.ValidateApiCallExecutionTime(elapsedMilliSeconds);
}
finally
{
// Set the timeout back to its default value
SendwithusClient.SetTimeoutInMilliseconds(SendwithusClient.DEFAULT_TIMEOUT_MILLISECONDS);
// Set the retry count back to its default value
SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
}
}
/// <summary>
/// Tests that the retry interval works properly when set to a non-default value
/// </summary>
/// <returns>The associated task</returns>
[Test]
public async Task TestNonDefaultRetryInterval()
{
// Set the timeout low enough that the API call is guaranteed to fail and has a negligible effect on the run time
SendwithusClient.SetTimeoutInMilliseconds(FAILURE_TIMEOUT_MILLISECONDS);
// Make sure we're using the default number of retries
//SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
SendwithusClient.RetryCount = NON_DEFAULT_RETRY_COUNT;
// Make sure we're using the default retry interval
SendwithusClient.RetryIntervalMilliseconds = NON_DEFAULT_RETRY_INTERVAL_MILLISECONDS;
// Send a GET request
var startTime = Stopwatch.GetTimestamp();
try
{
var response = await Template.GetTemplateAsync(DEFAULT_TEMPLATE_ID);
}
catch (Exception ex)
{
var endTime = Stopwatch.GetTimestamp();
// Make sure the API call failed on a timeout
//SendwithusClientTest.ValidateAggregateException<TaskCanceledException>(SendwithusClient.DEFAULT_RETRY_COUNT, ex);
SendwithusClientTest.ValidateAggregateException<TaskCanceledException>(NON_DEFAULT_RETRY_COUNT, ex);
// Validate the API call's execution time
var elapsedTime = endTime - startTime;
var elapsedMilliSeconds = elapsedTime * (1000.0 / Stopwatch.Frequency);
SendwithusClientTest.ValidateApiCallExecutionTime(elapsedMilliSeconds);
}
finally
{
// Set the timeout back to its default value
SendwithusClient.SetTimeoutInMilliseconds(SendwithusClient.DEFAULT_TIMEOUT_MILLISECONDS);
// Set the retry count back to its default value
SendwithusClient.RetryCount = SendwithusClient.DEFAULT_RETRY_COUNT;
// Set the retry interval back to its default value
SendwithusClient.RetryIntervalMilliseconds = SendwithusClient.DEFAULT_RETRY_INTERVAL_MILLISECONDS;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableDictionaryBuilderTest : ImmutableDictionaryBuilderTestBase
{
[Fact]
public void CreateBuilder()
{
var builder = ImmutableDictionary.CreateBuilder<string, string>();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, builder.ValueComparer);
builder = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
Assert.Same(StringComparer.Ordinal, builder.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, builder.ValueComparer);
builder = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.Ordinal, builder.KeyComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.ValueComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableDictionary<int, string>.Empty.ToBuilder();
builder.Add(3, "3");
builder.Add(5, "5");
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey(3));
Assert.True(builder.ContainsKey(5));
Assert.False(builder.ContainsKey(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
builder.Add(8, "8");
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.ContainsKey(8));
Assert.False(set.ContainsKey(8));
}
[Fact]
public void BuilderFromMap()
{
var set = ImmutableDictionary<int, string>.Empty.Add(1, "1");
var builder = set.ToBuilder();
Assert.True(builder.ContainsKey(1));
builder.Add(3, "3");
builder.Add(5, "5");
Assert.Equal(3, builder.Count);
Assert.True(builder.ContainsKey(3));
Assert.True(builder.ContainsKey(5));
Assert.False(builder.ContainsKey(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.ContainsKey(1));
builder.Add(8, "8");
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.ContainsKey(8));
Assert.False(set.ContainsKey(8));
Assert.False(set2.ContainsKey(8));
}
[Fact]
public void SeveralChanges()
{
var mutable = ImmutableDictionary<int, string>.Empty.ToBuilder();
var immutable1 = mutable.ToImmutable();
Assert.Same(immutable1, mutable.ToImmutable()); // "The Immutable property getter is creating new objects without any differences."
mutable.Add(1, "a");
var immutable2 = mutable.ToImmutable();
Assert.NotSame(immutable1, immutable2); // "Mutating the collection did not reset the Immutable property."
Assert.Same(immutable2, mutable.ToImmutable()); // "The Immutable property getter is creating new objects without any differences."
Assert.Equal(1, immutable2.Count);
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableDictionary<int, string>.Empty
.AddRange(Enumerable.Range(1, 10).Select(n => new KeyValuePair<int, string>(n, null)))
.ToBuilder();
Assert.Equal(
Enumerable.Range(1, 10).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11, null);
// Verify that a new enumerator will succeed.
Assert.Equal(
Enumerable.Range(1, 11).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(
Enumerable.Range(1, 11).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableDictionary<int, string>.Empty.Add(1, null);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2, null);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void AddRange()
{
var builder = ImmutableDictionary.Create<string, int>().ToBuilder();
builder.AddRange(new Dictionary<string, int> { { "a", 1 }, { "b", 2 } });
Assert.Equal(2, builder.Count);
Assert.Equal(1, builder["a"]);
Assert.Equal(2, builder["b"]);
}
[Fact]
public void RemoveRange()
{
var builder =
ImmutableDictionary.Create<string, int>()
.AddRange(new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } })
.ToBuilder();
Assert.Equal(3, builder.Count);
builder.RemoveRange(new[] { "a", "b" });
Assert.Equal(1, builder.Count);
Assert.Equal(3, builder["c"]);
}
[Fact]
public void Clear()
{
var builder = ImmutableDictionary.Create<string, int>().ToBuilder();
builder.Add("five", 5);
Assert.Equal(1, builder.Count);
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void ContainsValue()
{
var map = ImmutableDictionary.Create<string, int>().Add("five", 5);
var builder = map.ToBuilder();
Assert.True(builder.ContainsValue(5));
Assert.False(builder.ContainsValue(4));
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableDictionary.Create<string, string>()
.Add("a", "1").Add("B", "1").ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
Assert.True(builder.ContainsKey("a"));
Assert.False(builder.ContainsKey("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey("a"));
Assert.True(builder.ContainsKey("A"));
Assert.True(builder.ContainsKey("b"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.True(set.ContainsKey("a"));
Assert.True(set.ContainsKey("A"));
Assert.True(set.ContainsKey("b"));
}
[Fact]
public void KeyComparerCollisions()
{
// First check where collisions have matching values.
var builder = ImmutableDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.ContainsKey("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.ContainsKey("a"));
// Now check where collisions have conflicting values.
builder = ImmutableDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3").ToBuilder();
Assert.Throws<ArgumentException>(() => builder.KeyComparer = StringComparer.OrdinalIgnoreCase);
// Force all values to be considered equal.
builder.ValueComparer = EverythingEqual<string>.Default;
Assert.Same(EverythingEqual<string>.Default, builder.ValueComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase; // should not throw because values will be seen as equal.
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey("a"));
Assert.True(builder.ContainsKey("b"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableDictionary.Create<string, string>()
.Add("a", "1").Add("B", "1").ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void GetValueOrDefaultOfConcreteType()
{
var empty = ImmutableDictionary.Create<string, int>().ToBuilder();
var populated = ImmutableDictionary.Create<string, int>().Add("a", 5).ToBuilder();
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableDictionary.CreateBuilder<string, int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableDictionary.CreateBuilder<int, string>());
}
protected override IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>()
{
return ImmutableDictionary.Create<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableDictionary.Create<string, TValue>(comparer);
}
protected override bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey)
{
return ((ImmutableDictionary<TKey, TValue>.Builder)dictionary).TryGetKey(equalKey, out actualKey);
}
protected override IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis)
{
return ((ImmutableDictionary<TKey, TValue>)(basis ?? GetEmptyImmutableDictionary<TKey, TValue>())).ToBuilder();
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using wkt = Google.Protobuf.WellKnownTypes;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Video.Transcoder.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedTranscoderServiceClientTest
{
[xunit::FactAttribute]
public void CreateJobRequestObject()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobRequest request = new CreateJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Job = new Job(),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job response = client.CreateJob(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateJobRequestObjectAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobRequest request = new CreateJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Job = new Job(),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job responseCallSettings = await client.CreateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Job responseCancellationToken = await client.CreateJobAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateJob()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobRequest request = new CreateJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Job = new Job(),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job response = client.CreateJob(request.Parent, request.Job);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateJobAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobRequest request = new CreateJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Job = new Job(),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job responseCallSettings = await client.CreateJobAsync(request.Parent, request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Job responseCancellationToken = await client.CreateJobAsync(request.Parent, request.Job, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateJobResourceNames()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobRequest request = new CreateJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Job = new Job(),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job response = client.CreateJob(request.ParentAsLocationName, request.Job);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateJobResourceNamesAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobRequest request = new CreateJobRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Job = new Job(),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job responseCallSettings = await client.CreateJobAsync(request.ParentAsLocationName, request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Job responseCancellationToken = await client.CreateJobAsync(request.ParentAsLocationName, request.Job, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetJobRequestObject()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobRequest request = new GetJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job response = client.GetJob(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetJobRequestObjectAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobRequest request = new GetJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job responseCallSettings = await client.GetJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Job responseCancellationToken = await client.GetJobAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetJob()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobRequest request = new GetJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job response = client.GetJob(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetJobAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobRequest request = new GetJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job responseCallSettings = await client.GetJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Job responseCancellationToken = await client.GetJobAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetJobResourceNames()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobRequest request = new GetJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job response = client.GetJob(request.JobName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetJobResourceNamesAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobRequest request = new GetJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
Job expectedResponse = new Job
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
InputUri = "input_uriec9462a7",
OutputUri = "output_urice759a4d",
TemplateId = "template_id6435f574",
Config = new JobConfig(),
State = Job.Types.ProcessingState.Succeeded,
CreateTime = new wkt::Timestamp(),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
TtlAfterCompletionDays = 1495978457,
Error = new gr::Status(),
};
mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
Job responseCallSettings = await client.GetJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Job responseCancellationToken = await client.GetJobAsync(request.JobName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteJobRequestObject()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobRequest request = new DeleteJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
AllowMissing = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteJob(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteJobRequestObjectAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobRequest request = new DeleteJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
AllowMissing = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteJobAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteJob()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobRequest request = new DeleteJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteJob(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteJobAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobRequest request = new DeleteJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteJobAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteJobResourceNames()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobRequest request = new DeleteJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteJob(request.JobName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteJobResourceNamesAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobRequest request = new DeleteJobRequest
{
JobName = JobName.FromProjectLocationJob("[PROJECT]", "[LOCATION]", "[JOB]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteJobAsync(request.JobName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateJobTemplateRequestObject()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobTemplateRequest request = new CreateJobTemplateRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
JobTemplate = new JobTemplate(),
JobTemplateId = "job_template_id7acfca7e",
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.CreateJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate response = client.CreateJobTemplate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateJobTemplateRequestObjectAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobTemplateRequest request = new CreateJobTemplateRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
JobTemplate = new JobTemplate(),
JobTemplateId = "job_template_id7acfca7e",
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.CreateJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<JobTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate responseCallSettings = await client.CreateJobTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
JobTemplate responseCancellationToken = await client.CreateJobTemplateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateJobTemplate()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobTemplateRequest request = new CreateJobTemplateRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
JobTemplate = new JobTemplate(),
JobTemplateId = "job_template_id7acfca7e",
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.CreateJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate response = client.CreateJobTemplate(request.Parent, request.JobTemplate, request.JobTemplateId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateJobTemplateAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobTemplateRequest request = new CreateJobTemplateRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
JobTemplate = new JobTemplate(),
JobTemplateId = "job_template_id7acfca7e",
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.CreateJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<JobTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate responseCallSettings = await client.CreateJobTemplateAsync(request.Parent, request.JobTemplate, request.JobTemplateId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
JobTemplate responseCancellationToken = await client.CreateJobTemplateAsync(request.Parent, request.JobTemplate, request.JobTemplateId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateJobTemplateResourceNames()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobTemplateRequest request = new CreateJobTemplateRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
JobTemplate = new JobTemplate(),
JobTemplateId = "job_template_id7acfca7e",
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.CreateJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate response = client.CreateJobTemplate(request.ParentAsLocationName, request.JobTemplate, request.JobTemplateId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateJobTemplateResourceNamesAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
CreateJobTemplateRequest request = new CreateJobTemplateRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
JobTemplate = new JobTemplate(),
JobTemplateId = "job_template_id7acfca7e",
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.CreateJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<JobTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate responseCallSettings = await client.CreateJobTemplateAsync(request.ParentAsLocationName, request.JobTemplate, request.JobTemplateId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
JobTemplate responseCancellationToken = await client.CreateJobTemplateAsync(request.ParentAsLocationName, request.JobTemplate, request.JobTemplateId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetJobTemplateRequestObject()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobTemplateRequest request = new GetJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.GetJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate response = client.GetJobTemplate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetJobTemplateRequestObjectAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobTemplateRequest request = new GetJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.GetJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<JobTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate responseCallSettings = await client.GetJobTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
JobTemplate responseCancellationToken = await client.GetJobTemplateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetJobTemplate()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobTemplateRequest request = new GetJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.GetJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate response = client.GetJobTemplate(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetJobTemplateAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobTemplateRequest request = new GetJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.GetJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<JobTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate responseCallSettings = await client.GetJobTemplateAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
JobTemplate responseCancellationToken = await client.GetJobTemplateAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetJobTemplateResourceNames()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobTemplateRequest request = new GetJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.GetJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate response = client.GetJobTemplate(request.JobTemplateName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetJobTemplateResourceNamesAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
GetJobTemplateRequest request = new GetJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
JobTemplate expectedResponse = new JobTemplate
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
Config = new JobConfig(),
};
mockGrpcClient.Setup(x => x.GetJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<JobTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
JobTemplate responseCallSettings = await client.GetJobTemplateAsync(request.JobTemplateName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
JobTemplate responseCancellationToken = await client.GetJobTemplateAsync(request.JobTemplateName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteJobTemplateRequestObject()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobTemplateRequest request = new DeleteJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
AllowMissing = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteJobTemplate(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteJobTemplateRequestObjectAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobTemplateRequest request = new DeleteJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
AllowMissing = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteJobTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteJobTemplateAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteJobTemplate()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobTemplateRequest request = new DeleteJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteJobTemplate(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteJobTemplateAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobTemplateRequest request = new DeleteJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteJobTemplateAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteJobTemplateAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteJobTemplateResourceNames()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobTemplateRequest request = new DeleteJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteJobTemplate(request.JobTemplateName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteJobTemplateResourceNamesAsync()
{
moq::Mock<TranscoderService.TranscoderServiceClient> mockGrpcClient = new moq::Mock<TranscoderService.TranscoderServiceClient>(moq::MockBehavior.Strict);
DeleteJobTemplateRequest request = new DeleteJobTemplateRequest
{
JobTemplateName = JobTemplateName.FromProjectLocationJobTemplate("[PROJECT]", "[LOCATION]", "[JOB_TEMPLATE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteJobTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranscoderServiceClient client = new TranscoderServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteJobTemplateAsync(request.JobTemplateName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteJobTemplateAsync(request.JobTemplateName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// <copyright file="BeanReaderImpl.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Diagnostics;
using System.IO;
using JetBrains.Annotations;
namespace BeanIO.Internal.Parser
{
internal class BeanReaderImpl : BeanReader
{
[CanBeNull]
private UnmarshallingContext _context;
[CanBeNull]
private ISelector _layout;
/// <summary>
/// Initializes a new instance of the <see cref="BeanReaderImpl"/> class.
/// </summary>
/// <param name="context">the <see cref="UnmarshallingContext"/></param>
/// <param name="layout">the root component of the parser tree</param>
public BeanReaderImpl([NotNull] UnmarshallingContext context, [CanBeNull] ISelector layout)
{
_context = context;
_layout = layout;
}
/// <summary>
/// Gets the number of records read from the underlying input stream for the
/// most recent bean object read from this reader. This typically returns 1
/// unless a bean object was mapped to a record group which may span
/// multiple records.
/// </summary>
public override int RecordCount => _context?.RecordCount ?? 0;
/// <summary>
/// Gets or sets a value indicating whether to ignore unidentified records
/// </summary>
public bool IgnoreUnidentifiedRecords { get; set; }
/// <summary>
/// Gets the record information for all bean objects read from this reader.
/// If a bean object can span multiple records, <see cref="IBeanReader.RecordCount"/> can be used
/// to determine how many records were read from the stream.
/// </summary>
/// <param name="index">the index of the record, starting at 0</param>
/// <returns>the <see cref="IRecordContext"/></returns>
public override IRecordContext GetRecordContext(int index)
{
if (_context == null)
throw new InvalidOperationException();
return _context.GetRecordContext(index);
}
/// <summary>
/// Reads a single bean from the input stream.
/// </summary>
/// <remarks>
/// If the end of the stream is reached, null is returned.
/// </remarks>
/// <returns>The bean read, or null if the end of the stream was reached.</returns>
public override object Read()
{
EnsureOpen();
Debug.Assert(_context != null, "_context != null");
while (true)
{
if (_layout == null)
return null;
try
{
var bean = InternalRead();
if (bean != null)
return bean;
if (_context.IsEof)
return null;
}
catch (BeanReaderException ex)
{
// if an exception is thrown when parsing a dependent record,
// there is little chance of recovery
if (!OnError(ex))
throw;
}
catch (BeanIOException ex)
{
// wrap the generic exception in a BeanReaderException
var e = new BeanReaderException("Fatal BeanIOException caught", ex);
if (!OnError(e))
throw;
}
}
}
/// <summary>
/// Skips ahead in the input stream.
/// </summary>
/// <remarks>
/// Record validation errors are ignored, but a malformed record, unidentified
/// record, or record out of sequence, will cause an exception that halts stream
/// reading. Exceptions thrown by this method are not passed to the error handler.
/// </remarks>
/// <param name="count">The number of bean objects to skip over that would have been
/// returned by calling <see cref="IBeanReader.Read"/>.
/// </param>
/// <returns>the number of skipped bean objects, which may be less than <paramref name="count"/>
/// if the end of the stream was reached
/// </returns>
public override int Skip(int count)
{
EnsureOpen();
if (_layout == null)
return 0;
var n = 0;
while (n < count)
{
// find the next matching record node
var node = NextRecord();
// node is null when the end of the stream is reached
if (node == null)
return n;
node.Skip(_context);
// if the bean definition does not have a property type configured, it would not
// have been mapped to a bean object
if (node.Property != null)
++n;
}
return n;
}
/// <summary>
/// Closes the underlying input stream.
/// </summary>
public override void Close()
{
EnsureOpen();
Debug.Assert(_context != null, "_context != null");
try
{
_context.RecordReader.Close();
}
catch (IOException ex)
{
throw new BeanReaderIOException("Failed to close record reader", ex);
}
finally
{
_context = null;
}
}
private void EnsureOpen()
{
if (_context == null)
throw new BeanReaderIOException("Stream closed");
}
private object InternalRead()
{
Debug.Assert(_context != null, "_context != null");
ISelector parser = null;
try
{
// match the next record, parser may be null if EOF was reached
parser = NextRecord();
if (parser == null)
return null;
// notify the unmarshalling context that we are about to unmarshal a new record
_context.Prepare(parser.Name, parser.IsRecordGroup);
// unmarshal the record
try
{
parser.Unmarshal(_context);
}
catch (AbortRecordUnmarshalligException)
{
// Ignore abortion errors
}
// this will throw an exception if an invalid record was unmarshalled
_context.Validate();
// return the unmarshalled bean object
return parser.GetValue(_context);
}
finally
{
parser?.ClearValue(_context);
}
}
/// <summary>
/// Reads the next record from the input stream and returns the matching record node.
/// </summary>
/// <returns>the next matching record node, or <code>null</code> if the end of the stream was reached</returns>
private ISelector NextRecord()
{
Debug.Assert(_context != null, "_context != null");
Debug.Assert(_layout != null, "_layout != null");
ISelector parser = null;
// clear the current record name
RecordName = null;
do
{
// read the next record
_context.NextRecord();
// validate all record nodes are satisfied when the end of the file is reached
if (_context.IsEof)
{
try
{
// calling close will determine if all min occurs have been met
var unsatisfied = _layout.Close(_context);
if (unsatisfied != null)
{
if (unsatisfied.IsRecordGroup)
throw _context.NewUnsatisfiedGroupException(unsatisfied.Name);
throw _context.NewUnsatisfiedRecordException(unsatisfied.Name);
}
return null;
}
finally
{
_layout = null;
LineNumber = -1;
}
}
// update the last line number read
LineNumber = _context.LineNumber;
try
{
parser = _layout.MatchNext(_context);
}
catch (UnexpectedRecordException)
{
// when thrown, 'parser' is null and the error is handled below
}
if (parser != null || !IgnoreUnidentifiedRecords)
break;
_context.RecordSkipped();
}
while (true);
if (parser == null)
{
parser = _layout.MatchAny(_context);
if (parser != null)
throw _context.RecordUnexpectedException(parser.Name);
throw _context.RecordUnidentifiedException();
}
RecordName = parser.Name;
return parser;
}
}
}
| |
using Microsoft.Xna.Framework;
using RandomExtensions;
using System;
namespace Vector2Extensions
{
public static class Vector2Ext
{
/// <summary>
/// Given a string of two numbers separated by a space, get a 2d vector
/// This method takes a string created from Vector2.StringFromVector() and does the reverse
/// </summary>
/// <param name="strVector">the vector string</param>
/// <returns>a 2d vector with the values from the string!</returns>
public static Vector2 ToVector2(this string strVector)
{
Vector2 myVector = Vector2.Zero;
if (!string.IsNullOrEmpty(strVector))
{
//tokenize teh string
string[] pathinfo = strVector.Split(new Char[] { ' ' });
if (pathinfo.Length >= 1)
{
myVector.X = Convert.ToSingle(pathinfo[0]);
}
if (pathinfo.Length >= 2)
{
myVector.Y = Convert.ToSingle(pathinfo[1]);
}
}
return myVector;
}
/// <summary>
/// Extension method to simply convert between vector2 and string
/// </summary>
/// <returns>string created from the vector</returns>
/// <param name="myVector">A vector to convert to string</param>
public static string StringFromVector(this Vector2 myVector)
{
return $"{myVector.X.ToString()} {myVector.Y.ToString()}";
}
/// <summary>
/// Given a vector, get the vector perpendicular to that vect
/// </summary>
/// <param name="myVector"></param>
/// <returns></returns>
public static Vector2 Perp(this Vector2 myVector)
{
return new Vector2(-myVector.Y, myVector.X);
}
/// <summary>
/// returns positive if v2 is clockwise of this vector,
/// negative if anticlockwise (assuming the Y axis is pointing down, X axis to right like a Window app)
/// </summary>
/// <param name="myVector"></param>
/// <param name="v2"></param>
/// <returns></returns>
public static int Sign(this Vector2 myVector, Vector2 v2)
{
if ((myVector.Y * v2.X) > (myVector.X * v2.Y))
{
return -1;
}
else
{
return 1;
}
}
/// <summary>
/// If a vector is longer than the max length, chop it off
/// </summary>
/// <param name="myVector"></param>
/// <param name="maxLength"></param>
/// <returns></returns>
public static Vector2 Truncate(this Vector2 myVector, float maxLength)
{
if (myVector.LengthSquared() > (maxLength * maxLength))
{
myVector.Normalize();
myVector *= maxLength;
}
return myVector;
}
/// <summary>
/// Given 2 lines in 2D space AB, CD this returns true if an intersection occurs
/// and sets dist to the distance the intersection occurs along AB.
/// Also sets the 2d vector point to the point of intersection
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
/// <param name="C"></param>
/// <param name="D"></param>
/// <param name="dist"></param>
/// <param name="point"></param>
/// <returns></returns>
public static bool LineIntersection2D(Vector2 A,
Vector2 B,
Vector2 C,
Vector2 D,
ref float dist,
ref Vector2 point)
{
float rTop = (A.Y - C.Y) * (D.X - C.X) - (A.X - C.X) * (D.Y - C.Y);
float rBot = (B.X - A.X) * (D.Y - C.Y) - (B.Y - A.Y) * (D.X - C.X);
float sTop = (A.Y - C.Y) * (B.X - A.X) - (A.X - C.X) * (B.Y - A.Y);
float sBot = (B.X - A.X) * (D.Y - C.Y) - (B.Y - A.Y) * (D.X - C.X);
if ((rBot == 0.0f) || (sBot == 0.0f))
{
//lines are parallel
return false;
}
float r = rTop / rBot;
float s = sTop / sBot;
if ((r > 0) && (r < 1) && (s > 0) && (s < 1))
{
dist = Vector2.Distance(A, B) * r;
point = A + r * (B - A);
return true;
}
else
{
dist = 0;
return false;
}
}
/// <summary>
/// Get a random vector2 within the specified constraints
/// </summary>
/// <param name="rand"></param>
/// <param name="minX"></param>
/// <param name="maxX"></param>
/// <param name="minY"></param>
/// <param name="maxY"></param>
/// <returns></returns>
public static Vector2 NextVector2(this Random rand, float minX, float maxX, float minY, float maxY)
{
return new Vector2(rand.NextFloat(minX, maxX), rand.NextFloat(minY, maxY));
}
/// <summary>
/// Given a vector, return the angle of that vector.
/// </summary>
/// <param name="vector"></param>
/// <returns>angle of the vector in radians</returns>
public static float Angle(this Vector2 vector)
{
return (float)Math.Atan2(vector.Y, vector.X);
}
/// <summary>
/// Given two vectors, find the angle between the two of them
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns>angle between the two vectors in radians</returns>
public static float AngleBetweenVectors(this Vector2 a, Vector2 b)
{
return b.Angle() - a.Angle();
}
/// <summary>
/// given an angle, return a unit vector pointing in that direction
/// </summary>
/// <param name="angle"></param>
/// <returns></returns>
public static Vector2 ToVector2(this float angle)
{
return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
}
/// <summary>
/// given an angle, return a unit vector pointing in that direction
/// </summary>
/// <param name="angle"></param>
/// <returns></returns>
public static Vector2 ToVector2(this double angle)
{
return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
}
public static Point ToPoint(this Vector2 vect)
{
return new Point((int)vect.X, (int)vect.Y);
}
public static bool IsNaN(this Vector2 vect)
{
return (!float.IsNaN(vect.X) && !float.IsNaN(vect.Y));
}
public static Vector2 Normalized(this Vector2 myVector)
{
var lenth = myVector.Length();
return new Vector2(myVector.X / lenth, myVector.Y / lenth);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using HtmlHelp;
namespace HtmlHelp.UIComponents
{
/// <summary>
/// The class <c>TocTree</c> implements a user control which displays the HtmlHelp table of contents pane to the user.
/// </summary>
public class TocTree : System.Windows.Forms.UserControl
{
/// <summary>
/// Event if the user changes the selection in the toc tree
/// </summary>
public event TocSelectedEventHandler TocSelected;
private System.Windows.Forms.TreeView tocTreeView;
private System.Windows.Forms.ImageList hhImages;
private System.ComponentModel.IContainer components;
/// <summary>
/// Constructor of the class
/// </summary>
public TocTree()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
ReloadImageList();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.tocTreeView = new System.Windows.Forms.TreeView();
this.hhImages = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// tocTreeView
//
this.tocTreeView.Dock = System.Windows.Forms.DockStyle.Fill;
this.tocTreeView.HideSelection = false;
this.tocTreeView.ImageList = this.hhImages;
this.tocTreeView.Location = new System.Drawing.Point(2, 2);
this.tocTreeView.Name = "tocTreeView";
this.tocTreeView.Size = new System.Drawing.Size(228, 252);
this.tocTreeView.TabIndex = 0;
this.tocTreeView.AfterExpand += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterExpand);
this.tocTreeView.AfterCollapse += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterCollapse);
this.tocTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tocTreeView_AfterSelect);
//
// hhImages
//
this.hhImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit;
this.hhImages.ImageSize = new System.Drawing.Size(16, 16);
this.hhImages.TransparentColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(64)), ((System.Byte)(0)));
//
// TocTree
//
this.Controls.Add(this.tocTreeView);
this.DockPadding.All = 2;
this.Name = "TocTree";
this.Size = new System.Drawing.Size(232, 256);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Fireing the on selected event
/// </summary>
/// <param name="e">event parameters</param>
protected virtual void OnTocSelected(TocEventArgs e)
{
if(TocSelected != null)
{
TocSelected(this,e);
}
}
/// <summary>
/// Reloads the imagelist using the HtmlHelpSystem.UseHH2TreePics preference
/// </summary>
public void ReloadImageList()
{
ResourceHelper resHelper = new ResourceHelper( this.GetType().Assembly );
resHelper.DefaultBitmapNamespace = "Resources";
if(hhImages.Images.Count > 0)
{
hhImages.Images.Clear();
}
hhImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit;
if(HtmlHelpSystem.UseHH2TreePics)
{
hhImages.TransparentColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(64)), ((System.Byte)(0)));
hhImages.Images.AddStrip(resHelper.LoadBitmap("ContentTree.bmp"));
}
else
{
hhImages.TransparentColor = Color.Fuchsia;
hhImages.Images.AddStrip(resHelper.LoadBitmap("HH11.bmp"));
}
}
/// <summary>
/// Clears the items displayed in the toc pane
/// </summary>
public void ClearContents()
{
tocTreeView.Nodes.Clear();
}
/// <summary>
/// Call this method to build the table of contents (TOC) tree.
/// </summary>
/// <param name="tocItems">TOC instance (tree) extracted from the chm file</param>
public void BuildTOC(TableOfContents tocItems)
{
BuildTOC(tocItems, null);
}
/// <summary>
/// Call this method to build the table of contents (TOC) tree.
/// </summary>
/// <param name="tocItems">TOC instance (tree) extracted from the chm file</param>
/// <param name="filter">information type/category filter</param>
public void BuildTOC(TableOfContents tocItems, InfoTypeCategoryFilter filter)
{
tocTreeView.Nodes.Clear();
BuildTOC(tocItems.TOC, tocTreeView.Nodes, filter);
tocTreeView.Update();
}
/// <summary>
/// Snychronizes the table of content tree with the currently displayed browser url.
/// </summary>
/// <param name="URL">url to search</param>
public void Synchronize(string URL)
{
string local = URL;
string sFile = "";
if( URL.StartsWith(HtmlHelpSystem.UrlPrefix) )
{
local = local.Substring(HtmlHelpSystem.UrlPrefix.Length);
}
if( local.IndexOf("::")>-1)
{
sFile = local.Substring(0, local.IndexOf("::"));
local = local.Substring( local.IndexOf("::")+2 );
}
SelectTOCItem(tocTreeView.Nodes, sFile, local);
}
/// <summary>
/// Called if the user has expanded a tree item
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event parameter</param>
private void tocTreeView_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TOCItem curItem = (TOCItem)(e.Node.Tag);
if(curItem != null)
{
if(HtmlHelpSystem.UseHH2TreePics)
{
if(curItem.ImageIndex <= 15)
{
e.Node.ImageIndex = curItem.ImageIndex+2;
e.Node.SelectedImageIndex = curItem.ImageIndex+2;
}
}
else
{
if(curItem.ImageIndex < 8)
{
e.Node.ImageIndex = curItem.ImageIndex+1;
e.Node.SelectedImageIndex = curItem.ImageIndex+1;
}
}
}
}
/// <summary>
/// Called if the user has collapsed a tree item
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event parameter</param>
private void tocTreeView_AfterCollapse(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TOCItem curItem = (TOCItem)(e.Node.Tag);
if(curItem != null)
{
if(HtmlHelpSystem.UseHH2TreePics)
{
if(curItem.ImageIndex <= 15)
{
e.Node.ImageIndex = curItem.ImageIndex;
e.Node.SelectedImageIndex = curItem.ImageIndex;
}
}
else
{
if(curItem.ImageIndex < 8)
{
e.Node.ImageIndex = curItem.ImageIndex;
e.Node.SelectedImageIndex = curItem.ImageIndex;
}
}
}
}
/// <summary>
/// Called if the user selects a tree item.
/// This method will fire the <c>TocSelected</c> event notifying the parent window, that the user whants
/// to view a new help topic.
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event parameter</param>
private void tocTreeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
OnTocSelected( new TocEventArgs((TOCItem)(e.Node.Tag)) );
}
/// <summary>
/// Selects a node identified by its chm file and local
/// </summary>
/// <param name="col">treenode collection to search</param>
/// <param name="chmFile">chm filename</param>
/// <param name="local">local of the toc item</param>
private void SelectTOCItem(TreeNodeCollection col, string chmFile, string local)
{
foreach(TreeNode curNode in col)
{
TOCItem curItem = curNode.Tag as TOCItem;
if(curItem!=null)
{
if((curItem.Local == local)||(("/"+curItem.Local) == local))
{
if(chmFile.Length>0)
{
if(curItem.AssociatedFile.ChmFilePath == chmFile)
{
tocTreeView.SelectedNode = curNode;
return;
}
}
else
{
tocTreeView.SelectedNode = curNode;
return;
}
}
}
SelectTOCItem(curNode.Nodes, chmFile, local);
}
}
/// <summary>
/// Recursively builds the toc tree and fills the treeview
/// </summary>
/// <param name="tocItems">list of toc-items</param>
/// <param name="col">treenode collection of the current level</param>
/// <param name="filter">information type/category filter</param>
private void BuildTOC(ArrayList tocItems, TreeNodeCollection col, InfoTypeCategoryFilter filter)
{
foreach( TOCItem curItem in tocItems )
{
bool bAdd = true;
if(filter!=null)
{
bAdd=false;
if(curItem.InfoTypeStrings.Count <= 0)
{
bAdd=true;
}
else
{
for(int i=0;i<curItem.InfoTypeStrings.Count;i++)
{
bAdd |= filter.Match( curItem.InfoTypeStrings[i].ToString() );
}
}
}
if(bAdd)
{
TreeNode newNode = new TreeNode( curItem.Name, curItem.ImageIndex, curItem.ImageIndex );
newNode.Tag = curItem;
if(curItem.Children.Count > 0)
{
BuildTOC(curItem.Children, newNode.Nodes, filter);
}
// check if we have a book/folder which doesn't have any children
// after applied filter.
if( (curItem.Children.Count > 0) && (newNode.Nodes.Count <= 0) )
{
// check if the item has a local value
// if not, this don't display this item in the tree
if( curItem.Local.Length > 0)
{
col.Add(newNode);
}
}
else
{
col.Add(newNode);
}
}
}
}
}
}
| |
using System;
using System.Linq.Expressions;
using StructureMap.Pipeline;
using StructureMap.TypeRules;
namespace StructureMap.Configuration.DSL.Expressions
{
/// <summary>
/// Expression Builder to define an Instance
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IsExpression<T>
{
/// <summary>
/// Gives you full access to all the different ways to specify an "Instance"
/// </summary>
IInstanceExpression<T> Is { get; }
/// <summary>
/// Register a previously built Instance. This provides a "catch all"
/// method to attach custom Instance objects. Synonym for Instance()
/// </summary>
/// <param name="instance"></param>
void IsThis(Instance instance);
/// <summary>
/// Inject this object directly. Synonym to Object()
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
ObjectInstance<TReturned, T> IsThis<TReturned>(TReturned obj) where TReturned : class, T;
}
/// <summary>
/// An Expression Builder to define Instances of a PluginType.
/// This is mostly used for configuring open generic types
/// </summary>
public class GenericIsExpression
{
private readonly Action<Instance> _action;
public GenericIsExpression(Action<Instance> action)
{
_action = action;
}
/// <summary>
/// Shortcut to register a Concrete Type as an instance. This method supports
/// method chaining to allow you to add constructor and setter arguments for
/// the concrete type
/// </summary>
/// <param name="concreteType"></param>
/// <returns></returns>
public ConfiguredInstance Is(Type concreteType)
{
var instance = new ConfiguredInstance(concreteType);
_action(instance);
return instance;
}
/// <summary>
/// Shortcut to simply use the Instance with the given name
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public ReferencedInstance TheInstanceNamed(string name)
{
var instance = new ReferencedInstance(name);
_action(instance);
return instance;
}
}
/// <summary>
/// An Expression Builder that is used throughout the Registry DSL to
/// add and define Instances
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IInstanceExpression<T> : IsExpression<T>
{
/// <summary>
/// Register a previously built Instance. This provides a "catch all"
/// method to attach custom Instance objects. Synonym for IsThis()
/// </summary>
/// <param name="instance"></param>
void Instance(Instance instance);
/// <summary>
/// Inject this object directly. Synonym to IsThis()
/// </summary>
/// <param name="theObject"></param>
/// <returns></returns>
ObjectInstance<TReturned, T> Object<TReturned>(TReturned theObject) where TReturned : class, T;
/// <summary>
/// Build the Instance with the constructor function and setter arguments. Starts
/// the definition of a <see cref="SmartInstance{T}">SmartInstance</see>
/// </summary>
/// <typeparam name="TPluggedType"></typeparam>
/// <returns></returns>
SmartInstance<TPluggedType, T> Type<TPluggedType>() where TPluggedType : T;
/// <summary>
/// Build the Instance with the constructor function and setter arguments. Use this
/// method for open generic types, and favor the generic version of Type()
/// for all other types
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
ConfiguredInstance Type(Type type);
/// <summary>
/// Create an Instance that builds an object by calling a Lambda or
/// an anonymous delegate with no arguments
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
LambdaInstance<TReturned, T> ConstructedBy<TReturned>(Expression<Func<TReturned>> func) where TReturned : T;
/// <summary>
/// Create an Instance that builds an object by calling a Lambda or
/// an anonymous delegate with no arguments
/// </summary>
/// <param name="func"></param>
/// <param name="description">Diagnostic description of func</param>
/// <returns></returns>
LambdaInstance<TReturned, T> ConstructedBy<TReturned>(string description, Func<TReturned> func) where TReturned : T;
/// <summary>
/// Create an Instance that builds an object by calling a Lambda or
/// an anonymous delegate with the <see cref="IContext">IContext</see> representing
/// the current object graph.
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
LambdaInstance<TReturned, T> ConstructedBy<TReturned>(Expression<Func<IContext, TReturned>> func) where TReturned : T;
/// <summary>
/// Create an Instance that builds an object by calling a Lambda or
/// an anonymous delegate with the <see cref="IContext">IContext</see> representing
/// the current object graph.
/// </summary>
/// <param name="func"></param>
/// <param name="description">Diagnostic description of the func</param>
/// <returns></returns>
LambdaInstance<TReturned, T> ConstructedBy<TReturned>(string description, Func<IContext, TReturned> func) where TReturned : T;
/// <summary>
/// Use the Instance of this PluginType with the specified name. This is
/// generally only used while configuring child dependencies within a deep
/// object graph
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
ReferencedInstance TheInstanceNamed(string name);
/// <summary>
/// Use the default Instance of this PluginType. This is
/// generally only used while configuring child dependencies within a deep
/// object graph
/// </summary>
/// <returns></returns>
DefaultInstance TheDefault();
}
public class InstanceExpression<T> : IInstanceExpression<T>
{
private readonly Action<Instance> _action;
internal InstanceExpression(Action<Instance> action)
{
_action = action;
}
#region IsExpression<T> Members
IInstanceExpression<T> IsExpression<T>.Is
{
get { return this; }
}
/// <summary>
/// Use the specified Instance as the inline dependency
/// </summary>
/// <param name="instance"></param>
public void IsThis(Instance instance)
{
returnInstance(instance);
}
/// <summary>
/// Use a specific object as the inline dependency
/// </summary>
/// <typeparam name="TReturned"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public ObjectInstance<TReturned, T> IsThis<TReturned>(TReturned obj) where TReturned : class, T
{
return returnInstance(new ObjectInstance<TReturned, T>(obj));
}
#endregion
public void Instance(Instance instance)
{
_action(instance);
}
public SmartInstance<TPluggedType, T> Type<TPluggedType>() where TPluggedType : T
{
if (!typeof (TPluggedType).IsConcrete())
{
throw new InvalidOperationException("This class can only be created for concrete TPluginType types");
}
return returnInstance(new SmartInstance<TPluggedType, T>());
}
public ConfiguredInstance Type(Type type)
{
return returnInstance(new ConfiguredInstance(type));
}
public ObjectInstance<TReturned, T> Object<TReturned>(TReturned theObject) where TReturned : class, T
{
return returnInstance(new ObjectInstance<TReturned, T>(theObject));
}
public ReferencedInstance TheInstanceNamed(string name)
{
return returnInstance(new ReferencedInstance(name));
}
public DefaultInstance TheDefault()
{
return returnInstance(new DefaultInstance());
}
public LambdaInstance<TReturned, T> ConstructedBy<TReturned>(Expression<Func<TReturned>> func) where TReturned : T
{
return returnInstance(new LambdaInstance<TReturned, T>(func));
}
public LambdaInstance<TReturned, T> ConstructedBy<TReturned>(string description, Func<TReturned> func) where TReturned : T
{
return returnInstance(new LambdaInstance<TReturned, T>(description, func));
}
public LambdaInstance<TReturned, T> ConstructedBy<TReturned>(Expression<Func<IContext, TReturned>> func) where TReturned : T
{
return returnInstance(new LambdaInstance<TReturned, T>(func));
}
public LambdaInstance<TReturned, T> ConstructedBy<TReturned>(string description, Func<IContext, TReturned> func) where TReturned : T
{
return returnInstance(new LambdaInstance<TReturned, T>(description, func));
}
private TInstance returnInstance<TInstance>(TInstance instance) where TInstance : Instance
{
Instance(instance);
return instance;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public class File_Copy_str_str : FileSystemTest
{
#region Utilities
public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" };
public virtual void Copy(string source, string dest)
{
File.Copy(source, dest);
}
#endregion
#region UniversalTests
[Fact]
public void NullFileName()
{
Assert.Throws<ArgumentNullException>(() => Copy(null, "."));
Assert.Throws<ArgumentNullException>(() => Copy(".", null));
}
[Fact]
public void EmptyFileName()
{
Assert.Throws<ArgumentException>(() => Copy(string.Empty, "."));
Assert.Throws<ArgumentException>(() => Copy(".", string.Empty));
}
[Fact]
public void CopyOntoDirectory()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<IOException>(() => Copy(testFile, TestDirectory));
}
[Fact]
public void CopyOntoSelf()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<IOException>(() => Copy(testFile, testFile));
}
[Fact]
public void NonExistentPath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Throws<FileNotFoundException>(() => Copy(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Copy(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<DirectoryNotFoundException>(() => Copy(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
else
{
Assert.Throws<FileNotFoundException>(() => Copy(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Copy(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<FileNotFoundException>(() => Copy(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
}
[Fact]
public void CopyValid()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
File.Create(testFileSource).Dispose();
Copy(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.True(File.Exists(testFileSource));
}
[Fact]
public void ShortenLongPath()
{
string testFileSource = GetTestFilePath();
string testFileDest = Path.GetDirectoryName(testFileSource) + string.Concat(Enumerable.Repeat(Path.DirectorySeparatorChar + ".", 90).ToArray()) + Path.DirectorySeparatorChar + Path.GetFileName(testFileSource);
File.Create(testFileSource).Dispose();
Assert.Throws<IOException>(() => Copy(testFileSource, testFileDest));
}
[Fact]
public void InvalidFileNames()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<ArgumentException>(() => Copy(testFile, "\0"));
Assert.Throws<ArgumentException>(() => Copy(testFile, "*\0*"));
Assert.Throws<ArgumentException>(() => Copy("*\0*", testFile));
Assert.Throws<ArgumentException>(() => Copy("\0", testFile));
}
[Fact]
public void CopyFileWithData()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
char[] data = { 'a', 'A', 'b' };
// Write and copy file
using (StreamWriter stream = new StreamWriter(File.Create(testFileSource)))
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
Copy(testFileSource, testFileDest);
// Ensure copy transferred written data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[data.Length];
stream.Read(readData, 0, data.Length);
Assert.Equal(data, readData);
}
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsWhitespacePath()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
foreach (string invalid in WindowsInvalidUnixValid)
{
Assert.Throws<ArgumentException>(() => Copy(testFile, invalid));
Assert.Throws<ArgumentException>(() => Copy(invalid, testFile));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixWhitespacePath()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
foreach (string valid in WindowsInvalidUnixValid)
{
Copy(testFile, Path.Combine(TestDirectory, valid));
Assert.True(File.Exists(testFile));
Assert.True(File.Exists(Path.Combine(TestDirectory, valid)));
}
}
#endregion
}
public class File_Copy_str_str_b : File_Copy_str_str
{
#region Utilities
public override void Copy(string source, string dest)
{
File.Copy(source, dest, false);
}
public virtual void Copy(string source, string dest, bool overwrite)
{
File.Copy(source, dest, overwrite);
}
#endregion
#region UniversalTests
[Fact]
public void OverwriteTrue()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
char[] sourceData = { 'a', 'A', 'b' };
char[] destData = { 'x', 'X', 'y' };
// Write and copy file
using (StreamWriter sourceStream = new StreamWriter(File.Create(testFileSource)))
using (StreamWriter destStream = new StreamWriter(File.Create(testFileDest)))
{
sourceStream.Write(sourceData, 0, sourceData.Length);
destStream.Write(destData, 0, destData.Length);
}
Copy(testFileSource, testFileDest, true);
// Ensure copy transferred written data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[sourceData.Length];
stream.Read(readData, 0, sourceData.Length);
Assert.Equal(sourceData, readData);
}
}
[Fact]
public void OverwriteFalse()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
char[] sourceData = { 'a', 'A', 'b' };
char[] destData = { 'x', 'X', 'y' };
// Write and copy file
using (StreamWriter sourceStream = new StreamWriter(File.Create(testFileSource)))
using (StreamWriter destStream = new StreamWriter(File.Create(testFileDest)))
{
sourceStream.Write(sourceData, 0, sourceData.Length);
destStream.Write(destData, 0, destData.Length);
}
Assert.Throws<IOException>(() => Copy(testFileSource, testFileDest, false));
// Ensure copy didn't overwrite existing data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[sourceData.Length];
stream.Read(readData, 0, sourceData.Length);
Assert.Equal(destData, readData);
}
}
#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.Runtime.InteropServices;
using System.Security;
namespace OLEDB.Test.ModuleCore
{
////////////////////////////////////////////////////////////////////////
// VARIATION_STATUS
//
////////////////////////////////////////////////////////////////////////
public enum tagVARIATION_STATUS
{
eVariationStatusFailed = 0,
eVariationStatusPassed,
eVariationStatusNotRun,
eVariationStatusNonExistent,
eVariationStatusUnknown,
eVariationStatusTimedOut,
eVariationStatusConformanceWarning,
eVariationStatusException,
eVariationStatusAborted
}
////////////////////////////////////////////////////////////////////////
// ERRORLEVEL
//
////////////////////////////////////////////////////////////////////////
public enum tagERRORLEVEL
{
HR_STRICT,
HR_OPTIONAL,
HR_SUCCEED,
HR_FAIL,
HR_WARNING
}
////////////////////////////////////////////////////////////////////////
// CONSOLEFLAGS
//
////////////////////////////////////////////////////////////////////////
public enum tagCONSOLEFLAGS
{
CONSOLE_RAW = 0x00000000, //No fixup - Don't use, unless you know the text contains no CR/LF, no Xml reserved tokens, or no other non-representable characters
CONSOLE_TEXT = 0x00000001, //Default - Automatically fixup CR/LF correctly for log files, fixup xml tokens, etc
CONSOLE_XML = 0x00000002, //For Xml - User text is placed into a CDATA section (with no xml fixups)
CONSOLE_IGNORE = 0x00000004, //Ignore - User text is placed into ignore tags (can combine this with console_xml as well)
}
////////////////////////////////////////////////////////////////////////
// IError
//
////////////////////////////////////////////////////////////////////////
public interface IError
{
// These two methods get/set the ErrorLevel property. This property affects the
// behavior of the 'Validate' method. The enum values have the following
// effects on that method:
// HR_STRICT: The 'hrActual' parameter MUST match the 'hrExpected' parameter,
// or else the error count in incremented.
// HR_SUCCEED: The 'hrActual' MUST be a success code, or else the error count
// is incremented.
// HR_FAIL: The 'hrActual' MUST be an error code, or else the error count
// is incremented.
// HR_OPTIONAL:The error count will not be incremented, regardless of the
// parameters passed in to 'Validate.'
//
tagERRORLEVEL GetErrorLevel();
void SetErrorLevel(tagERRORLEVEL ErrorLevel);
// 'GetActualHr' returns the HRESULT recorded from the last call to 'Validate'.
//
int GetActualHr();
// 'Validate' compares the two HRESULT values passed in and, depending on
// the current ErrorLevel, possibly increment the error count and output
// an error message to the LTM window. In the cases where validation fails,
// the pfResult parameter will be returned as FALSE -- otherwise TRUE.
// When an error message is output to LTM, the file name and line numbers
// are recorded there as well.
//
bool Validate(int hrActual,
string bstrFileName,
int lLineNo,
int hrExpected);
// 'Compare' will output an error message (similar to that output by 'Validate')
// if the fWereEqual parameter passed in is FALSE.
//
bool Compare(bool fWereEqual,
string bstrFileName,
int lLineNo);
// The 'LogxxxxxxxxHr' methods output error or status message to the LTM
// window. The HRESULT parameters passed in are converted to string
// messages for this purpose.
//
void LogExpectedHr(int hrExpected);
void LogReceivedHr(int hrReceived,
string bstrFileName,
int lLineNo);
// The 'ResetxxxxErrors' methods simply reset the internal error count of
// a Module, Case, or Variation (respectively.)
//
void ResetModErrors();
void ResetCaseErrors();
void ResetVarErrors();
void ResetModWarnings();
void ResetCaseWarnings();
void ResetVarWarnings();
// 'GetxxxxErrors' retrieve the current number of errors at the Module,
// Test Case, or Variation level.
//
int GetModErrors();
int GetCaseErrors();
int GetVarErrors();
int GetModWarnings();
int GetCaseWarnings();
int GetVarWarnings();
// 'Increment' will increment the error count of the currently running
// Test Module, the currently running Test Case, as well as the currently
// running Variation.
//
void Increment();
// 'Transmit' is the way a Test Module can send text messages to LTM. These will
// be displayed in LTM's main window, and can be used to inform the user of
// any pertinent information at run-time.
//
void Transmit(string bstrTextString);
// 'Initialize'
//
void Initialize();
}
////////////////////////////////////////////////////////////////////////
// ITestConsole
//
////////////////////////////////////////////////////////////////////////
public interface ITestConsole
{
//(Error) Logging routines
void Log(string bstrActual,
string bstrExpected,
string bstrSource,
string bstrMessage,
string bstrDetails,
tagCONSOLEFLAGS flags,
string bstrFilename,
int iline);
void Write(tagCONSOLEFLAGS flags,
string bstrString);
void WriteLine();
}
////////////////////////////////////////////////////////////////////////
// IProviderInfo
//
////////////////////////////////////////////////////////////////////////
public interface IProviderInfo
{
// The IProviderInfo interface is just a wrapper around a structure which
// contains all of the information LTM & Test Modules needs to know about
// the provider they are running against (if any.)
//
// The properties are described as follows:
// >Name: The name the provider gives itself. For Kagera this is MSDASQL.
// >FriendlyName: A special name the user has given this provider configuration.
// >InitString: A string which contains initialization data. The interpretation
// of this string is Test Module-specific -- so you simply must
// make users of LTM aware of what your particular Test Module
// wants to see in this string.
// >MachineName: If you will be testing a remote provider, the user will pass
// the machine name the provider is located on to you through
// this property.
// >CLSID: This is the CLSID of the provider you are to run against.
// >CLSCTX: This tells you whether the provider will be InProc, Local, or
// Remote (values of this property are identical to the values
// of the CLSCTX enumeration in wtypes.h)
string GetName();
void SetName(string bstrProviderName);
string GetFriendlyName();
void SetFriendlyName(string bstrFriendlyName);
string GetInitString();
void SetInitString(string bstrInitString);
string GetMachineName();
void SetMachineName(string bstrMachineName);
string GetCLSID();
void SetCLSID(string bstrCLSID);
int GetCLSCTX();
void SetCLSCTX(int ClsCtx);
}
////////////////////////////////////////////////////////////////////////
// IAliasInfo
//
////////////////////////////////////////////////////////////////////////
public interface IAliasInfo //: IProviderInfo
{
//IProviderInfo (as defined above)
//TODO: Why do I have to repeat them here. Inheriting from IProviderInfo succeeds,
//but the memory layout is incorrect (GetCommandLine actually calls GetName).
string GetName();
void SetName(string bstrProviderName);
string GetFriendlyName();
void SetFriendlyName(string bstrFriendlyName);
string GetInitString();
void SetInitString(string bstrInitString);
string GetMachineName();
void SetMachineName(string bstrMachineName);
string GetCLSID();
void SetCLSID(string bstrCLSID);
int GetCLSCTX();
void SetCLSCTX(int ClsCtx);
//IAliasInfo
string GetCommandLine();
}
////////////////////////////////////////////////////////////////////////
// ITestCases
//
////////////////////////////////////////////////////////////////////////
public interface ITestCases
{
// LTM will use these methods to get information about this test case.
//
string GetName();
string GetDescription();
// SyncProviderInterface() should cause this TestCase to release its current
// IProviderInterface (if any) and retrieve a new IProviderInterface
// from its owning ITestModule (via the 'GetProviderInterface' call)
//
// GetProviderInterface() returns the current IProviderInterface for
// this test case.
//
void SyncProviderInterface();
IProviderInfo GetProviderInterface();
// 'GetOwningITestModule' should retrieve the back-pointer
// to this test case's owning ITestModule object.
//
ITestModule GetOwningITestModule();
// LTM will call 'Init' before it runs any variations in this Test Case.
// Any code that sets up objects for use by the Variations should go here.
//
int Init();
// LTM will call 'Terminate' after it runs any variations on this
// object -- regardless of the outcome of those calls (even regardless
// of whether ITestCases::Init() fails or not.)
//
bool Terminate();
// 'GetVariationCount' should return the number of variations
// this Test Case contains.
//
int GetVariationCount();
// For these next three, the first parameter is the variation index. 'Index' in
// this case means the 0-based index into the complete list of variations
// for this test case (if 'GetVariationCount' returns the value 'n', these
// functions will always be passed values between 0 and (n - 1) as the first
// parameter).
// Do not confuse 'index' with 'Variation ID'. The latter is a non-sequential
// unique identifier for the variation, which can be any 32-bit number. This
// exists so that even when variations are added or removed during test
// development, the ID is ALWAYS the same for the same variation (though
// the Index will surely change.)
//
tagVARIATION_STATUS ExecuteVariation(int lIndex);
int GetVariationID(int lIndex);
string GetVariationDesc(int lIndex);
}
////////////////////////////////////////////////////////////////////////
// ITestModule
//
////////////////////////////////////////////////////////////////////////
public interface ITestModule
{
string GetName();
string GetDescription();
string GetOwnerName();
string GetCLSID();
int GetVersion();
// LTM will call 'SetProviderInterface' after the ITestModule object is instantiated
// (if appropriate).
// 'GetProviderInterface' is added for the implementor's convenience, but is not
// called by LTM.
//
void SetProviderInterface(IProviderInfo pProvInfo);
IProviderInfo GetProviderInterface();
// LTM will call 'SetErrorInterface' after the ITestModule object is instantiated.
// 'GetErrorInterface' is added for the implementor's convenience, but is not
// called by LTM.
//
void SetErrorInterface(IError pIError);
IError GetErrorInterface();
// 'Init' is called at the beginning of each test run. Any global
// data that all Test Cases in this module will use should be setup
// here.
//
int Init();
// 'Terminate' is called at the end of each test run, regardless of the
// outcome of the tests (even regardless of whether ITestModule::Init()
// succeeds or fails.)
//
bool Terminate();
// 'GetCaseCount' returns the number of test cases this test module
// contains. This value must not be zero.
//
int GetCaseCount();
// 'GetCase' should create an ITestCases instance for LTM to use.
// The first parameter is the 0-based index of the test case. If
// 'GetCaseCount' returns 'n' cases, this parameter will always
// be between 0 and (n - 1), inclusive.
//
ITestCases GetCase(int lIndex);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using SoulService.Areas.HelpPage.Models;
namespace SoulService.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
namespace Internal.Cryptography.Pal.Native
{
/// <summary>
/// Base class for safe handles representing NULL-based pointers.
/// </summary>
internal abstract class SafePointerHandle<T> : SafeHandle where T : SafeHandle, new()
{
protected SafePointerHandle()
: base(IntPtr.Zero, true)
{
}
public sealed override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
public static T InvalidHandle
{
get { return SafeHandleCache<T>.GetInvalidHandle(() => new T()); }
}
protected override void Dispose(bool disposing)
{
if (!SafeHandleCache<T>.IsCachedInvalidHandle(this))
{
base.Dispose(disposing);
}
}
}
/// <summary>
/// SafeHandle for the CERT_CONTEXT structure defined by crypt32.
/// </summary>
internal class SafeCertContextHandle : SafePointerHandle<SafeCertContextHandle>
{
private SafeCertContextHandle _parent;
public SafeCertContextHandle() { }
public SafeCertContextHandle(SafeCertContextHandle parent)
{
if (parent == null)
throw new ArgumentNullException(nameof(parent));
Debug.Assert(!parent.IsInvalid);
Debug.Assert(!parent.IsClosed);
bool ignored = false;
parent.DangerousAddRef(ref ignored);
_parent = parent;
SetHandle(_parent.handle);
}
protected override bool ReleaseHandle()
{
if (_parent != null)
{
_parent.DangerousRelease();
_parent = null;
}
else
{
Interop.Crypt32.CertFreeCertificateContext(handle);
}
SetHandle(IntPtr.Zero);
return true;
}
public unsafe CERT_CONTEXT* CertContext
{
get { return (CERT_CONTEXT*)handle; }
}
// Extract the raw CERT_CONTEXT* pointer and reset the SafeHandle to the invalid state so it no longer auto-destroys the CERT_CONTEXT.
public unsafe CERT_CONTEXT* Disconnect()
{
CERT_CONTEXT* pCertContext = (CERT_CONTEXT*)handle;
SetHandle(IntPtr.Zero);
return pCertContext;
}
public bool HasPersistedPrivateKey
{
get { return CertHasProperty(CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID); }
}
public bool HasEphemeralPrivateKey
{
get { return CertHasProperty(CertContextPropId.CERT_KEY_CONTEXT_PROP_ID); }
}
public bool ContainsPrivateKey
{
get { return HasPersistedPrivateKey || HasEphemeralPrivateKey; }
}
public SafeCertContextHandle Duplicate()
{
return Interop.crypt32.CertDuplicateCertificateContext(handle);
}
private bool CertHasProperty(CertContextPropId propertyId)
{
int cb = 0;
bool hasProperty = Interop.crypt32.CertGetCertificateContextProperty(
this,
propertyId,
null,
ref cb);
return hasProperty;
}
}
/// <summary>
/// SafeHandle for the CERT_CONTEXT structure defined by crypt32. Unlike SafeCertContextHandle, disposition already deletes any associated key containers.
/// </summary>
internal sealed class SafeCertContextHandleWithKeyContainerDeletion : SafeCertContextHandle
{
protected sealed override bool ReleaseHandle()
{
using (SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(handle))
{
DeleteKeyContainer(certContext);
}
base.ReleaseHandle();
return true;
}
public static void DeleteKeyContainer(SafeCertContextHandle pCertContext)
{
if (pCertContext.IsInvalid)
return;
int cb = 0;
bool containsPrivateKey = Interop.crypt32.CertGetCertificateContextProperty(pCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cb);
if (!containsPrivateKey)
return;
byte[] provInfoAsBytes = new byte[cb];
if (!Interop.crypt32.CertGetCertificateContextProperty(pCertContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, provInfoAsBytes, ref cb))
return;
unsafe
{
fixed (byte* pProvInfoAsBytes = provInfoAsBytes)
{
CRYPT_KEY_PROV_INFO* pProvInfo = (CRYPT_KEY_PROV_INFO*)pProvInfoAsBytes;
if (pProvInfo->dwProvType == 0)
{
// dwProvType being 0 indicates that the key is stored in CNG.
// dwProvType being non-zero indicates that the key is stored in CAPI.
string providerName = Marshal.PtrToStringUni((IntPtr)(pProvInfo->pwszProvName));
string keyContainerName = Marshal.PtrToStringUni((IntPtr)(pProvInfo->pwszContainerName));
try
{
using (CngKey cngKey = CngKey.Open(keyContainerName, new CngProvider(providerName)))
{
cngKey.Delete();
}
}
catch (CryptographicException)
{
// While leaving the file on disk is undesirable, an inability to perform this cleanup
// should not manifest itself to a user.
}
}
else
{
CryptAcquireContextFlags flags = (pProvInfo->dwFlags & CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET) | CryptAcquireContextFlags.CRYPT_DELETEKEYSET;
IntPtr hProv;
bool success = Interop.cryptoapi.CryptAcquireContext(out hProv, pProvInfo->pwszContainerName, pProvInfo->pwszProvName, pProvInfo->dwProvType, flags);
// Called CryptAcquireContext solely for the side effect of deleting the key containers. When called with these flags, no actual
// hProv is returned (so there's nothing to clean up.)
Debug.Assert(hProv == IntPtr.Zero);
}
}
}
}
}
/// <summary>
/// SafeHandle for the HCERTSTORE handle defined by crypt32.
/// </summary>
internal sealed class SafeCertStoreHandle : SafePointerHandle<SafeCertStoreHandle>
{
protected sealed override bool ReleaseHandle()
{
bool success = Interop.Crypt32.CertCloseStore(handle, 0);
return success;
}
}
/// <summary>
/// SafeHandle for the HCRYPTMSG handle defined by crypt32.
/// </summary>
internal sealed class SafeCryptMsgHandle : SafePointerHandle<SafeCryptMsgHandle>
{
protected sealed override bool ReleaseHandle()
{
bool success = Interop.Crypt32.CryptMsgClose(handle);
return success;
}
}
/// <summary>
/// SafeHandle for LocalAlloc'd memory.
/// </summary>
internal sealed class SafeLocalAllocHandle : SafePointerHandle<SafeLocalAllocHandle>
{
public static SafeLocalAllocHandle Create(int cb)
{
var h = new SafeLocalAllocHandle();
h.SetHandle(Marshal.AllocHGlobal(cb));
return h;
}
protected sealed override bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle);
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ThorIOClient.Protocol
{
public static class Endian
{
public static byte[] ToBigEndianBytes<T>(this int source)
{
var bytes = new byte[] {};
Type type = typeof (T);
if (type == typeof (ushort))
bytes = BitConverter.GetBytes((ushort) source);
else if (type == typeof (ulong))
bytes = BitConverter.GetBytes((ulong) source);
else if (type == typeof (int))
bytes = BitConverter.GetBytes(source);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
return bytes;
}
public static int ToLittleEndianInt(this byte[] source)
{
if (BitConverter.IsLittleEndian)
Array.Reverse(source);
if (source.Length == 2)
return BitConverter.ToUInt16(source, 0);
if (source.Length == 8)
return (int) BitConverter.ToUInt64(source, 0);
return 0;
}
}
public enum FrameType
{
Continuation = 0,
Text = 1,
Binary = 2,
Close = 8,
Ping = 9,
Pong = 10,
}
public class ReadState
{
public ReadState()
{
Data = new List<byte>();
}
public List<byte> Data { get; private set; }
public FrameType? FrameType { get; set; }
public void Clear()
{
Data.Clear();
FrameType = null;
}
}
public class DataFrame
{
public DataFrame(List<byte> payload){
this.IsFinal = true;
this.IsMasked = true;
this.MaskKey = new Random().Next(0, 34298);
this.Payload = payload.ToArray();
}
private bool IsFinal { get; set; }
private bool IsMasked { get; set; }
private long PayloadLength
{
get { return Payload.Length; }
}
private int MaskKey { get; set; }
public byte[] Payload { get; set; }
public byte[] ToBytes()
{
var memoryStream = new MemoryStream();
const bool rsv1 = false;
const bool rsv2 = false;
const bool rsv3 = false;
var bt = (IsFinal ? 1 : 0) * 0x80;
bt += (rsv1 ? 0x40 : 0x0);
bt += (rsv2 ? 0x20 : 0x0);
bt += (rsv3 ? 0x10 : 0x0);
bt += (byte)2;
memoryStream.WriteByte((byte)bt);
byte[] payloadLengthBytes = GetLengthBytes();
memoryStream.Write(payloadLengthBytes, 0, payloadLengthBytes.Length);
byte[] payload = Payload;
if (IsMasked)
{
byte[] keyBytes = BitConverter.GetBytes(MaskKey);
if (BitConverter.IsLittleEndian)
Array.Reverse(keyBytes);
memoryStream.Write(keyBytes, 0, keyBytes.Length);
payload = TransformBytes(Payload, MaskKey);
}
memoryStream.Write(payload, 0, Payload.Length);
return memoryStream.ToArray();
}
private byte[] GetLengthBytes()
{
var payloadLengthBytes = new List<byte>(9);
if (PayloadLength > ushort.MaxValue)
{
payloadLengthBytes.Add(127);
byte[] lengthBytes = BitConverter.GetBytes(PayloadLength);
if (BitConverter.IsLittleEndian)
Array.Reverse(lengthBytes);
payloadLengthBytes.AddRange(lengthBytes);
}
else if (PayloadLength > 125)
{
payloadLengthBytes.Add(126);
byte[] lengthBytes = BitConverter.GetBytes((UInt16)PayloadLength);
if (BitConverter.IsLittleEndian)
Array.Reverse(lengthBytes);
payloadLengthBytes.AddRange(lengthBytes);
}
else
{
payloadLengthBytes.Add((byte)PayloadLength);
}
payloadLengthBytes[0] += (byte)(IsMasked ? 128 : 0);
return payloadLengthBytes.ToArray();
}
public static byte[] TransformBytes(byte[] bytes, int mask)
{
var output = new byte[bytes.Length];
byte[] maskBytes = BitConverter.GetBytes(mask);
if (BitConverter.IsLittleEndian)
Array.Reverse(maskBytes);
for (int i = 0; i < bytes.Length; i++)
{
output[i] = (byte)(bytes[i] ^ maskBytes[i % 4]);
}
return output;
}
}
static class DataFrameReader{
public static void Read(List<byte> data, ReadState readState, Action<FrameType, byte[]> completed)
{
while (data.Count >= 2)
{
bool isFinal = (data[0] & 128) != 0;
var frameType = (FrameType)(data[0] & 15);
int length = (data[1] & 127);
var isMasked = (data[1] & 128) != 0;
var reservedBits = (data[0] & 112);
if (reservedBits != 0)
{
return;
}
int index = 2;
int payloadLength;
if (length == 127)
{
if (data.Count < index + 8)
return; //Not complete
payloadLength = data.Skip(index).Take(8).ToArray().ToLittleEndianInt();
index += 8;
}
else if (length == 126)
{
if (data.Count < index + 2)
return; //Not complete
payloadLength = data.Skip(index).Take(2).ToArray().ToLittleEndianInt();
index += 2;
}
else
{
payloadLength = length;
}
var maskBytes = data.Skip(index).Take(4).ToArray();
index += 4;
if (data.Count < index + payloadLength)
return; //Not complete
IEnumerable<byte> payload = data
.Skip(index)
.Take(payloadLength)
.Select((x, i) => (byte)(x ^ maskBytes[i % 4]));
readState.Data.AddRange(payload);
data.RemoveRange(0, index + payloadLength);
if (frameType != FrameType.Continuation)
readState.FrameType = frameType;
if (!isFinal || !readState.FrameType.HasValue) continue;
byte[] stateData = readState.Data.ToArray();
FrameType? stateFrameType = readState.FrameType;
readState.Clear();
completed(stateFrameType.Value, stateData);
}
}
}
}
| |
/*
* Copyright (c) 2015, Wisconsin Robotics
* 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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 BadgerJaus.Util;
namespace BadgerJaus.Messages.VelocityStateSensor
{
public class ReportVelocityState : QueryVelocityState
{
JausUnsignedInteger x;
JausUnsignedInteger y;
JausUnsignedInteger z;
JausUnsignedShort roll;
JausUnsignedShort pitch;
JausUnsignedShort yaw;
JausUnsignedShort waypointTolerance;
JausUnsignedInteger pathTolerance;
JausTimeStamp timeStamp;
private const double POSE_MIN = -327.68;
private const double POSE_MAX = 327.67;
private const double ORIENT_MIN = -32.768;
private const double ORIENT_MAX = 32.767;
protected override int CommandCode
{
get { return JausCommandCode.REPORT_VELOCITY_STATE; }
}
protected override void InitFieldData()
{
base.InitFieldData();
x = new JausUnsignedInteger();
y = new JausUnsignedInteger();
z = new JausUnsignedInteger();
roll = new JausUnsignedShort();
pitch = new JausUnsignedShort();
yaw = new JausUnsignedShort();
pathTolerance = new JausUnsignedInteger();
timeStamp = new JausTimeStamp();
}
public void SetX(double xValue)
{
x.SetValueFromDouble(xValue, POSE_MIN, POSE_MAX);
presence.setBit(X_BIT);
}
public void SetY(double yValue)
{
y.SetValueFromDouble(yValue, POSE_MIN, POSE_MAX);
presence.setBit(Y_BIT);
}
public void SetZ(double zValue)
{
z.setFromDouble(zValue, POSE_MIN, POSE_MAX);
presence.setBit(Z_BIT);
}
public void SetRoll(double rollValue)
{
roll.SetValueFromDouble(rollValue, ORIENT_MIN, ORIENT_MAX);
presence.setBit(ROLL_BIT);
}
public void SetPitch(double pitchValue)
{
pitch.SetValueFromDouble(pitchValue, ORIENT_MIN, ORIENT_MAX);
presence.setBit(PITCH_BIT);
}
public void SetYaw(double yawValue)
{
yaw.SetValueFromDouble(yawValue, ORIENT_MIN, ORIENT_MAX);
presence.setBit(YAW_BIT);
}
public void SetTimestamp(int timeValue)
{
//timeStamp.setValue(timeValue);
presence.setBit(TS_BIT);
}
public double GetX()
{
return x.ScaleValueToDouble(POSE_MIN, POSE_MAX);
}
public double GetY()
{
return y.ScaleValueToDouble(POSE_MIN, POSE_MAX);
}
public double GetZ()
{
return z.ScaleValueToDouble(POSE_MIN, POSE_MAX);
}
public double GetRoll()
{
return roll.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
}
public double GetPitch()
{
return pitch.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
}
public double GetYaw()
{
return yaw.ScaleValueToDouble(ORIENT_MIN, ORIENT_MAX);
}
public override int GetPayloadSize()
{
int payloadSize = 0;
payloadSize += base.GetPayloadSize();
if (presence.IsBitSet(X_BIT))
payloadSize += JausBaseType.INT_BYTE_SIZE;
if (presence.IsBitSet(Y_BIT))
payloadSize += JausBaseType.INT_BYTE_SIZE;
if (presence.IsBitSet(Z_BIT))
payloadSize += JausBaseType.INT_BYTE_SIZE;
if (presence.IsBitSet(YAW_BIT))
payloadSize += JausBaseType.SHORT_BYTE_SIZE;
if (presence.IsBitSet(TS_BIT))
payloadSize += JausBaseType.INT_BYTE_SIZE;
return payloadSize;
}
protected override bool PayloadToJausBuffer(byte[] buffer, int index, out int indexOffset)
{
indexOffset = index;
if(!base.PayloadToJausBuffer(buffer, indexOffset, out indexOffset))
return false;
if (presence.IsBitSet(X_BIT))
{
if (!x.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(Y_BIT))
{
if (!y.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(Z_BIT))
{
if (!z.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(YAW_BIT))
{
if (!y.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
if (presence.IsBitSet(TS_BIT))
{
if (!timeStamp.Serialize(buffer, indexOffset, out indexOffset))
return false;
}
return true;
}
protected override bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset)
{
if (!base.SetPayloadFromJausBuffer(buffer, index, out indexOffset))
return false;
if (presence.IsBitSet(X_BIT))
{
x.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(Y_BIT))
{
y.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(Z_BIT))
{
z.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(YAW_BIT))
{
yaw.Deserialize(buffer, indexOffset, out indexOffset);
}
if (presence.IsBitSet(TS_BIT))
{
timeStamp.Deserialize(buffer, indexOffset, out indexOffset);
}
return true;
}
public void SetToCurrentTime()
{
presence.setBit(TS_BIT);
timeStamp.setToCurrentTime();
}
}
}
| |
// 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.Net.Sockets;
using System.Net.Test.Common;
using Xunit;
namespace System.Net.NameResolution.PalTests
{
public class NameResolutionPalTests
{
static NameResolutionPalTests()
{
NameResolutionPal.EnsureSocketsAreInitialized();
}
[Fact]
public void HostName_NotNull()
{
Assert.NotNull(NameResolutionPal.GetHostName());
}
[Fact]
public void GetHostByName_LocalHost()
{
IPHostEntry hostEntry = NameResolutionPal.GetHostByName("localhost");
Assert.NotNull(hostEntry);
Assert.NotNull(hostEntry.HostName);
Assert.NotNull(hostEntry.AddressList);
Assert.NotNull(hostEntry.Aliases);
}
[Fact]
public void GetHostByName_HostName()
{
string hostName = NameResolutionPal.GetHostName();
Assert.NotNull(hostName);
IPHostEntry hostEntry = NameResolutionPal.GetHostByName(hostName);
Assert.NotNull(hostEntry);
Assert.NotNull(hostEntry.HostName);
Assert.NotNull(hostEntry.AddressList);
Assert.NotNull(hostEntry.Aliases);
}
[Fact]
public void GetHostByAddr_LocalHost()
{
Assert.NotNull(NameResolutionPal.GetHostByAddr(new IPAddress(0x0100007f)));
}
[Fact]
public void GetHostByName_LocalHost_GetHostByAddr()
{
IPHostEntry hostEntry1 = NameResolutionPal.GetHostByName("localhost");
Assert.NotNull(hostEntry1);
IPHostEntry hostEntry2 = NameResolutionPal.GetHostByAddr(hostEntry1.AddressList[0]);
Assert.NotNull(hostEntry2);
IPAddress[] list1 = hostEntry1.AddressList;
IPAddress[] list2 = hostEntry2.AddressList;
for (int i = 0; i < list1.Length; i++)
{
Assert.NotEqual(-1, Array.IndexOf(list2, list1[i]));
}
}
[Fact]
public void GetHostByName_HostName_GetHostByAddr()
{
IPHostEntry hostEntry1 = NameResolutionPal.GetHostByName(Configuration.Http.Http2Host);
Assert.NotNull(hostEntry1);
IPAddress[] list1 = hostEntry1.AddressList;
Assert.InRange(list1.Length, 1, Int32.MaxValue);
foreach (IPAddress addr1 in list1)
{
IPHostEntry hostEntry2 = NameResolutionPal.GetHostByAddr(addr1);
Assert.NotNull(hostEntry2);
IPAddress[] list2 = hostEntry2.AddressList;
Assert.InRange(list2.Length, 1, list1.Length);
foreach (IPAddress addr2 in list2)
{
Assert.NotEqual(-1, Array.IndexOf(list1, addr2));
}
}
}
[Fact]
public void TryGetAddrInfo_LocalHost()
{
IPHostEntry hostEntry;
int nativeErrorCode;
SocketError error = NameResolutionPal.TryGetAddrInfo("localhost", out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
Assert.NotNull(hostEntry.HostName);
Assert.NotNull(hostEntry.AddressList);
Assert.NotNull(hostEntry.Aliases);
}
[Fact]
public void TryGetAddrInfo_HostName()
{
string hostName = NameResolutionPal.GetHostName();
Assert.NotNull(hostName);
IPHostEntry hostEntry;
int nativeErrorCode;
SocketError error = NameResolutionPal.TryGetAddrInfo(hostName, out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
Assert.NotNull(hostEntry.HostName);
Assert.NotNull(hostEntry.AddressList);
Assert.NotNull(hostEntry.Aliases);
}
[Fact]
public void TryGetNameInfo_LocalHost_IPv4()
{
SocketError error;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 127, 0, 0, 1 }), out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
}
[Fact]
public void TryGetNameInfo_LocalHost_IPv6()
{
SocketError error;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }), out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
}
[Fact]
public void TryGetAddrInfo_LocalHost_TryGetNameInfo()
{
IPHostEntry hostEntry;
int nativeErrorCode;
SocketError error = NameResolutionPal.TryGetAddrInfo("localhost", out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
string name = NameResolutionPal.TryGetNameInfo(hostEntry.AddressList[0], out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
}
[ActiveIssue(10764, PlatformID.AnyUnix)]
[Fact]
public void TryGetAddrInfo_HostName_TryGetNameInfo()
{
string hostName = NameResolutionPal.GetHostName();
Assert.NotNull(hostName);
IPHostEntry hostEntry;
int nativeErrorCode;
SocketError error = NameResolutionPal.TryGetAddrInfo(hostName, out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
string name = NameResolutionPal.TryGetNameInfo(hostEntry.AddressList[0], out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
}
[Fact]
public void TryGetNameInfo_LocalHost_IPv4_TryGetAddrInfo()
{
SocketError error;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 127, 0, 0, 1 }), out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
IPHostEntry hostEntry;
error = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
}
[Fact]
public void TryGetNameInfo_LocalHost_IPv6_TryGetAddrInfo()
{
SocketError error;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }), out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
IPHostEntry hostEntry;
error = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
}
}
}
| |
// <copyright file="OperaOptions.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium.Opera
{
/// <summary>
/// Class to manage options specific to <see cref="OperaDriver"/>
/// </summary>
/// <remarks>
/// Used with OperaDriver.exe for Chromium v0.1.0 and higher.
/// </remarks>
/// <example>
/// <code>
/// OperaOptions options = new OperaOptions();
/// options.AddExtensions("\path\to\extension.crx");
/// options.BinaryLocation = "\path\to\opera";
/// </code>
/// <para></para>
/// <para>For use with OperaDriver:</para>
/// <para></para>
/// <code>
/// OperaDriver driver = new OperaDriver(options);
/// </code>
/// <para></para>
/// <para>For use with RemoteWebDriver:</para>
/// <para></para>
/// <code>
/// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities());
/// </code>
/// </example>
public class OperaOptions : DriverOptions
{
/// <summary>
/// Gets the name of the capability used to store Opera options in
/// an <see cref="ICapabilities"/> object.
/// </summary>
public static readonly string Capability = "operaOptions";
private const string BrowserNameValue = "opera";
private const string ArgumentsOperaOption = "args";
private const string BinaryOperaOption = "binary";
private const string ExtensionsOperaOption = "extensions";
private const string LocalStateOperaOption = "localState";
private const string PreferencesOperaOption = "prefs";
private const string DetachOperaOption = "detach";
private const string DebuggerAddressOperaOption = "debuggerAddress";
private const string ExcludeSwitchesOperaOption = "excludeSwitches";
private const string MinidumpPathOperaOption = "minidumpPath";
private bool leaveBrowserRunning;
private string binaryLocation;
private string debuggerAddress;
private string minidumpPath;
private List<string> arguments = new List<string>();
private List<string> extensionFiles = new List<string>();
private List<string> encodedExtensions = new List<string>();
private List<string> excludedSwitches = new List<string>();
private Dictionary<string, object> additionalOperaOptions = new Dictionary<string, object>();
private Dictionary<string, object> userProfilePreferences;
private Dictionary<string, object> localStatePreferences;
/// <summary>
/// Initializes a new instance of the <see cref="OperaOptions"/> class.
/// </summary>
public OperaOptions() : base()
{
this.BrowserName = BrowserNameValue;
this.AddKnownCapabilityName(OperaOptions.Capability, "current OperaOptions class instance");
this.AddKnownCapabilityName(OperaOptions.ArgumentsOperaOption, "AddArguments method");
this.AddKnownCapabilityName(OperaOptions.BinaryOperaOption, "BinaryLocation property");
this.AddKnownCapabilityName(OperaOptions.ExtensionsOperaOption, "AddExtensions method");
this.AddKnownCapabilityName(OperaOptions.LocalStateOperaOption, "AddLocalStatePreference method");
this.AddKnownCapabilityName(OperaOptions.PreferencesOperaOption, "AddUserProfilePreference method");
this.AddKnownCapabilityName(OperaOptions.DetachOperaOption, "LeaveBrowserRunning property");
this.AddKnownCapabilityName(OperaOptions.DebuggerAddressOperaOption, "DebuggerAddress property");
this.AddKnownCapabilityName(OperaOptions.ExcludeSwitchesOperaOption, "AddExcludedArgument property");
this.AddKnownCapabilityName(OperaOptions.MinidumpPathOperaOption, "MinidumpPath property");
}
/// <summary>
/// Gets or sets the location of the Opera browser's binary executable file.
/// </summary>
public string BinaryLocation
{
get { return this.binaryLocation; }
set { this.binaryLocation = value; }
}
/// <summary>
/// Gets or sets a value indicating whether Opera should be left running after the
/// OperaDriver instance is exited. Defaults to <see langword="false"/>.
/// </summary>
public bool LeaveBrowserRunning
{
get { return this.leaveBrowserRunning; }
set { this.leaveBrowserRunning = value; }
}
/// <summary>
/// Gets the list of arguments appended to the Opera command line as a string array.
/// </summary>
public ReadOnlyCollection<string> Arguments
{
get { return this.arguments.AsReadOnly(); }
}
/// <summary>
/// Gets the list of extensions to be installed as an array of base64-encoded strings.
/// </summary>
public ReadOnlyCollection<string> Extensions
{
get
{
List<string> allExtensions = new List<string>(this.encodedExtensions);
foreach (string extensionFile in this.extensionFiles)
{
byte[] extensionByteArray = File.ReadAllBytes(extensionFile);
string encodedExtension = Convert.ToBase64String(extensionByteArray);
allExtensions.Add(encodedExtension);
}
return allExtensions.AsReadOnly();
}
}
/// <summary>
/// Gets or sets the address of a Opera debugger server to connect to.
/// Should be of the form "{hostname|IP address}:port".
/// </summary>
public string DebuggerAddress
{
get { return this.debuggerAddress; }
set { this.debuggerAddress = value; }
}
/// <summary>
/// Gets or sets the directory in which to store minidump files.
/// </summary>
public string MinidumpPath
{
get { return this.minidumpPath; }
set { this.minidumpPath = value; }
}
/// <summary>
/// Adds a single argument to the list of arguments to be appended to the Opera.exe command line.
/// </summary>
/// <param name="argument">The argument to add.</param>
public void AddArgument(string argument)
{
if (string.IsNullOrEmpty(argument))
{
throw new ArgumentException("argument must not be null or empty", "argument");
}
this.AddArguments(argument);
}
/// <summary>
/// Adds arguments to be appended to the Opera.exe command line.
/// </summary>
/// <param name="argumentsToAdd">An array of arguments to add.</param>
public void AddArguments(params string[] argumentsToAdd)
{
this.AddArguments(new List<string>(argumentsToAdd));
}
/// <summary>
/// Adds arguments to be appended to the Opera.exe command line.
/// </summary>
/// <param name="argumentsToAdd">An <see cref="IEnumerable{T}"/> object of arguments to add.</param>
public void AddArguments(IEnumerable<string> argumentsToAdd)
{
if (argumentsToAdd == null)
{
throw new ArgumentNullException("argumentsToAdd", "argumentsToAdd must not be null");
}
this.arguments.AddRange(argumentsToAdd);
}
/// <summary>
/// Adds a single argument to be excluded from the list of arguments passed by default
/// to the Opera.exe command line by operadriver.exe.
/// </summary>
/// <param name="argument">The argument to exclude.</param>
public void AddExcludedArgument(string argument)
{
if (string.IsNullOrEmpty(argument))
{
throw new ArgumentException("argument must not be null or empty", "argument");
}
this.AddExcludedArguments(argument);
}
/// <summary>
/// Adds arguments to be excluded from the list of arguments passed by default
/// to the Opera.exe command line by operadriver.exe.
/// </summary>
/// <param name="argumentsToExclude">An array of arguments to exclude.</param>
public void AddExcludedArguments(params string[] argumentsToExclude)
{
this.AddExcludedArguments(new List<string>(argumentsToExclude));
}
/// <summary>
/// Adds arguments to be excluded from the list of arguments passed by default
/// to the Opera.exe command line by operadriver.exe.
/// </summary>
/// <param name="argumentsToExclude">An <see cref="IEnumerable{T}"/> object of arguments to exclude.</param>
public void AddExcludedArguments(IEnumerable<string> argumentsToExclude)
{
if (argumentsToExclude == null)
{
throw new ArgumentNullException("argumentsToExclude", "argumentsToExclude must not be null");
}
this.excludedSwitches.AddRange(argumentsToExclude);
}
/// <summary>
/// Adds a path to a packed Opera extension (.crx file) to the list of extensions
/// to be installed in the instance of Opera.
/// </summary>
/// <param name="pathToExtension">The full path to the extension to add.</param>
public void AddExtension(string pathToExtension)
{
if (string.IsNullOrEmpty(pathToExtension))
{
throw new ArgumentException("pathToExtension must not be null or empty", "pathToExtension");
}
this.AddExtensions(pathToExtension);
}
/// <summary>
/// Adds a list of paths to packed Opera extensions (.crx files) to be installed
/// in the instance of Opera.
/// </summary>
/// <param name="extensions">An array of full paths to the extensions to add.</param>
public void AddExtensions(params string[] extensions)
{
this.AddExtensions(new List<string>(extensions));
}
/// <summary>
/// Adds a list of paths to packed Opera extensions (.crx files) to be installed
/// in the instance of Opera.
/// </summary>
/// <param name="extensions">An <see cref="IEnumerable{T}"/> of full paths to the extensions to add.</param>
public void AddExtensions(IEnumerable<string> extensions)
{
if (extensions == null)
{
throw new ArgumentNullException("extensions", "extensions must not be null");
}
foreach (string extension in extensions)
{
if (!File.Exists(extension))
{
throw new FileNotFoundException("No extension found at the specified path", extension);
}
this.extensionFiles.Add(extension);
}
}
/// <summary>
/// Adds a base64-encoded string representing a Opera extension to the list of extensions
/// to be installed in the instance of Opera.
/// </summary>
/// <param name="extension">A base64-encoded string representing the extension to add.</param>
public void AddEncodedExtension(string extension)
{
if (string.IsNullOrEmpty(extension))
{
throw new ArgumentException("extension must not be null or empty", "extension");
}
this.AddEncodedExtensions(extension);
}
/// <summary>
/// Adds a list of base64-encoded strings representing Opera extensions to the list of extensions
/// to be installed in the instance of Opera.
/// </summary>
/// <param name="extensions">An array of base64-encoded strings representing the extensions to add.</param>
public void AddEncodedExtensions(params string[] extensions)
{
this.AddEncodedExtensions(new List<string>(extensions));
}
/// <summary>
/// Adds a list of base64-encoded strings representing Opera extensions to be installed
/// in the instance of Opera.
/// </summary>
/// <param name="extensions">An <see cref="IEnumerable{T}"/> of base64-encoded strings
/// representing the extensions to add.</param>
public void AddEncodedExtensions(IEnumerable<string> extensions)
{
if (extensions == null)
{
throw new ArgumentNullException("extensions", "extensions must not be null");
}
foreach (string extension in extensions)
{
// Run the extension through the base64 converter to test that the
// string is not malformed.
try
{
Convert.FromBase64String(extension);
}
catch (FormatException ex)
{
throw new WebDriverException("Could not properly decode the base64 string", ex);
}
this.encodedExtensions.Add(extension);
}
}
/// <summary>
/// Adds a preference for the user-specific profile or "user data directory."
/// If the specified preference already exists, it will be overwritten.
/// </summary>
/// <param name="preferenceName">The name of the preference to set.</param>
/// <param name="preferenceValue">The value of the preference to set.</param>
public void AddUserProfilePreference(string preferenceName, object preferenceValue)
{
if (this.userProfilePreferences == null)
{
this.userProfilePreferences = new Dictionary<string, object>();
}
this.userProfilePreferences[preferenceName] = preferenceValue;
}
/// <summary>
/// Adds a preference for the local state file in the user's data directory for Opera.
/// If the specified preference already exists, it will be overwritten.
/// </summary>
/// <param name="preferenceName">The name of the preference to set.</param>
/// <param name="preferenceValue">The value of the preference to set.</param>
public void AddLocalStatePreference(string preferenceName, object preferenceValue)
{
if (this.localStatePreferences == null)
{
this.localStatePreferences = new Dictionary<string, object>();
}
this.localStatePreferences[preferenceName] = preferenceValue;
}
/// <summary>
/// Provides a means to add additional capabilities not yet added as type safe options
/// for the Chrome driver.
/// </summary>
/// <param name="optionName">The name of the capability to add.</param>
/// <param name="optionValue">The value of the capability to add.</param>
/// <exception cref="ArgumentException">
/// thrown when attempting to add a capability for which there is already a type safe option, or
/// when <paramref name="optionName"/> is <see langword="null"/> or the empty string.
/// </exception>
/// <remarks>Calling <see cref="AddAdditionalOperaOption(string, object)"/>
/// where <paramref name="optionName"/> has already been added will overwrite the
/// existing value with the new value in <paramref name="optionValue"/>.
/// Calling this method adds capabilities to the Chrome-specific options object passed to
/// chromedriver.exe (property name 'operaOptions').</remarks>
public void AddAdditionalOperaOption(string optionName, object optionValue)
{
this.ValidateCapabilityName(optionName);
this.additionalOperaOptions[optionName] = optionValue;
}
/// <summary>
/// Provides a means to add additional capabilities not yet added as type safe options
/// for the Opera driver.
/// </summary>
/// <param name="capabilityName">The name of the capability to add.</param>
/// <param name="capabilityValue">The value of the capability to add.</param>
/// <exception cref="ArgumentException">
/// thrown when attempting to add a capability for which there is already a type safe option, or
/// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string.
/// </exception>
/// <remarks>Calling <see cref="AddAdditionalCapability(string, object)"/>
/// where <paramref name="capabilityName"/> has already been added will overwrite the
/// existing value with the new value in <paramref name="capabilityValue"/>.
/// Also, by default, calling this method adds capabilities to the options object passed to
/// operadriver.exe.</remarks>
[Obsolete("Use the temporary AddAdditionalOption method or the AddAdditionalOperaOption method for adding additional options")]
public override void AddAdditionalCapability(string capabilityName, object capabilityValue)
{
// Add the capability to the OperaOptions object by default. This is to handle
// the 80% case where the Operadriver team adds a new option in Operadriver.exe
// and the bindings have not yet had a type safe option added.
this.AddAdditionalCapability(capabilityName, capabilityValue, false);
}
/// <summary>
/// Provides a means to add additional capabilities not yet added as type safe options
/// for the Opera driver.
/// </summary>
/// <param name="capabilityName">The name of the capability to add.</param>
/// <param name="capabilityValue">The value of the capability to add.</param>
/// <param name="isGlobalCapability">Indicates whether the capability is to be set as a global
/// capability for the driver instead of a Opera-specific option.</param>
/// <exception cref="ArgumentException">
/// thrown when attempting to add a capability for which there is already a type safe option, or
/// when <paramref name="capabilityName"/> is <see langword="null"/> or the empty string.
/// </exception>
/// <remarks>Calling <see cref="AddAdditionalCapability(string, object, bool)"/>
/// where <paramref name="capabilityName"/> has already been added will overwrite the
/// existing value with the new value in <paramref name="capabilityValue"/></remarks>
[Obsolete("Use the temporary AddAdditionalOption method or the AddAdditionalOperaOption method for adding additional options")]
public void AddAdditionalCapability(string capabilityName, object capabilityValue, bool isGlobalCapability)
{
if (isGlobalCapability)
{
this.AddAdditionalOption(capabilityName, capabilityValue);
}
else
{
this.AddAdditionalOperaOption(capabilityName, capabilityValue);
}
}
/// <summary>
/// Returns DesiredCapabilities for Opera with these options included as
/// capabilities. This does not copy the options. Further changes will be
/// reflected in the returned capabilities.
/// </summary>
/// <returns>The DesiredCapabilities for Opera with these options.</returns>
public override ICapabilities ToCapabilities()
{
Dictionary<string, object> operaOptions = this.BuildOperaOptionsDictionary();
IWritableCapabilities capabilities = this.GenerateDesiredCapabilities(false);
capabilities.SetCapability(OperaOptions.Capability, operaOptions);
// Should return capabilities.AsReadOnly(), and will in a future release.
return capabilities.AsReadOnly();
}
private Dictionary<string, object> BuildOperaOptionsDictionary()
{
Dictionary<string, object> operaOptions = new Dictionary<string, object>();
if (this.Arguments.Count > 0)
{
operaOptions[ArgumentsOperaOption] = this.Arguments;
}
if (!string.IsNullOrEmpty(this.binaryLocation))
{
operaOptions[BinaryOperaOption] = this.binaryLocation;
}
ReadOnlyCollection<string> extensions = this.Extensions;
if (extensions.Count > 0)
{
operaOptions[ExtensionsOperaOption] = extensions;
}
if (this.localStatePreferences != null && this.localStatePreferences.Count > 0)
{
operaOptions[LocalStateOperaOption] = this.localStatePreferences;
}
if (this.userProfilePreferences != null && this.userProfilePreferences.Count > 0)
{
operaOptions[PreferencesOperaOption] = this.userProfilePreferences;
}
if (this.leaveBrowserRunning)
{
operaOptions[DetachOperaOption] = this.leaveBrowserRunning;
}
if (!string.IsNullOrEmpty(this.debuggerAddress))
{
operaOptions[DebuggerAddressOperaOption] = this.debuggerAddress;
}
if (this.excludedSwitches.Count > 0)
{
operaOptions[ExcludeSwitchesOperaOption] = this.excludedSwitches;
}
if (!string.IsNullOrEmpty(this.minidumpPath))
{
operaOptions[MinidumpPathOperaOption] = this.minidumpPath;
}
foreach (KeyValuePair<string, object> pair in this.additionalOperaOptions)
{
operaOptions.Add(pair.Key, pair.Value);
}
return operaOptions;
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Util
{
/*
* 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 ByteArrayDataInput = Lucene.Net.Store.ByteArrayDataInput;
using DocIdSet = Lucene.Net.Search.DocIdSet;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using MonotonicAppendingInt64Buffer = Lucene.Net.Util.Packed.MonotonicAppendingInt64Buffer;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
/// <summary>
/// <see cref="DocIdSet"/> implementation based on word-aligned hybrid encoding on
/// words of 8 bits.
/// <para>This implementation doesn't support random-access but has a fast
/// <see cref="DocIdSetIterator"/> which can advance in logarithmic time thanks to
/// an index.</para>
/// <para>The compression scheme is simplistic and should work well with sparse and
/// very dense doc id sets while being only slightly larger than a
/// <see cref="FixedBitSet"/> for incompressible sets (overhead<2% in the worst
/// case) in spite of the index.</para>
/// <para><b>Format</b>: The format is byte-aligned. An 8-bits word is either clean,
/// meaning composed only of zeros or ones, or dirty, meaning that it contains
/// between 1 and 7 bits set. The idea is to encode sequences of clean words
/// using run-length encoding and to leave sequences of dirty words as-is.</para>
/// <list type="table">
/// <listheader><term>Token</term><term>Clean length+</term><term>Dirty length+</term><term>Dirty words</term></listheader>
/// <item><term>1 byte</term><term>0-n bytes</term><term>0-n bytes</term><term>0-n bytes</term></item>
/// </list>
/// <list type="bullet">
/// <item><term><b>Token</b></term><description> encodes whether clean means full of zeros or ones in the
/// first bit, the number of clean words minus 2 on the next 3 bits and the
/// number of dirty words on the last 4 bits. The higher-order bit is a
/// continuation bit, meaning that the number is incomplete and needs additional
/// bytes to be read.</description></item>
/// <item><term><b>Clean length+</b>:</term><description> If clean length has its higher-order bit set,
/// you need to read a vint (<see cref="Store.DataInput.ReadVInt32()"/>), shift it by 3 bits on
/// the left side and add it to the 3 bits which have been read in the token.</description></item>
/// <item><term><b>Dirty length+</b></term><description> works the same way as <b>Clean length+</b> but
/// on 4 bits and for the length of dirty words.</description></item>
/// <item><term><b>Dirty words</b></term><description>are the dirty words, there are <b>Dirty length</b>
/// of them.</description></item>
/// </list>
/// <para>This format cannot encode sequences of less than 2 clean words and 0 dirty
/// word. The reason is that if you find a single clean word, you should rather
/// encode it as a dirty word. This takes the same space as starting a new
/// sequence (since you need one byte for the token) but will be lighter to
/// decode. There is however an exception for the first sequence. Since the first
/// sequence may start directly with a dirty word, the clean length is encoded
/// directly, without subtracting 2.</para>
/// <para>There is an additional restriction on the format: the sequence of dirty
/// words is not allowed to contain two consecutive clean words. This restriction
/// exists to make sure no space is wasted and to make sure iterators can read
/// the next doc ID by reading at most 2 dirty words.</para>
/// @lucene.experimental
/// </summary>
public sealed class WAH8DocIdSet : DocIdSet
{
// Minimum index interval, intervals below this value can't guarantee anymore
// that this set implementation won't be significantly larger than a FixedBitSet
// The reason is that a single sequence saves at least one byte and an index
// entry requires at most 8 bytes (2 ints) so there shouldn't be more than one
// index entry every 8 sequences
private const int MIN_INDEX_INTERVAL = 8;
/// <summary>
/// Default index interval. </summary>
public const int DEFAULT_INDEX_INTERVAL = 24;
private static readonly MonotonicAppendingInt64Buffer SINGLE_ZERO_BUFFER = new MonotonicAppendingInt64Buffer(1, 64, PackedInt32s.COMPACT);
private static WAH8DocIdSet EMPTY = new WAH8DocIdSet(new byte[0], 0, 1, SINGLE_ZERO_BUFFER, SINGLE_ZERO_BUFFER);
static WAH8DocIdSet()
{
SINGLE_ZERO_BUFFER.Add(0L);
SINGLE_ZERO_BUFFER.Freeze();
}
private static readonly IComparer<Iterator> SERIALIZED_LENGTH_COMPARER = new ComparerAnonymousInnerClassHelper();
private class ComparerAnonymousInnerClassHelper : IComparer<Iterator>
{
public ComparerAnonymousInnerClassHelper()
{
}
public virtual int Compare(Iterator wi1, Iterator wi2)
{
return wi1.@in.Length - wi2.@in.Length;
}
}
/// <summary>
/// Same as <see cref="Intersect(ICollection{WAH8DocIdSet}, int)"/> with the default index interval. </summary>
public static WAH8DocIdSet Intersect(ICollection<WAH8DocIdSet> docIdSets)
{
return Intersect(docIdSets, DEFAULT_INDEX_INTERVAL);
}
/// <summary>
/// Compute the intersection of the provided sets. This method is much faster than
/// computing the intersection manually since it operates directly at the byte level.
/// </summary>
public static WAH8DocIdSet Intersect(ICollection<WAH8DocIdSet> docIdSets, int indexInterval)
{
switch (docIdSets.Count)
{
case 0:
throw new System.ArgumentException("There must be at least one set to intersect");
case 1:
var iter = docIdSets.GetEnumerator();
iter.MoveNext();
return iter.Current;
}
// The logic below is similar to ConjunctionScorer
int numSets = docIdSets.Count;
var iterators = new Iterator[numSets];
int i = 0;
foreach (WAH8DocIdSet set in docIdSets)
{
var it = (Iterator)set.GetIterator();
iterators[i++] = it;
}
Array.Sort(iterators, SERIALIZED_LENGTH_COMPARER);
WordBuilder builder = (WordBuilder)(new WordBuilder()).SetIndexInterval(indexInterval);
int wordNum = 0;
while (true)
{
// Advance the least costly iterator first
iterators[0].AdvanceWord(wordNum);
wordNum = iterators[0].wordNum;
if (wordNum == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
byte word = iterators[0].word;
for (i = 1; i < numSets; ++i)
{
if (iterators[i].wordNum < wordNum)
{
iterators[i].AdvanceWord(wordNum);
}
if (iterators[i].wordNum > wordNum)
{
wordNum = iterators[i].wordNum;
goto mainContinue;
}
Debug.Assert(iterators[i].wordNum == wordNum);
word &= iterators[i].word;
if (word == 0)
{
// There are common words, but they don't share any bit
++wordNum;
goto mainContinue;
}
}
// Found a common word
Debug.Assert(word != 0);
builder.AddWord(wordNum, word);
++wordNum;
mainContinue: ;
}
//mainBreak:
return builder.Build();
}
/// <summary>
/// Same as <see cref="Union(ICollection{WAH8DocIdSet}, int)"/> with the default index interval. </summary>
public static WAH8DocIdSet Union(ICollection<WAH8DocIdSet> docIdSets)
{
return Union(docIdSets, DEFAULT_INDEX_INTERVAL);
}
/// <summary>
/// Compute the union of the provided sets. This method is much faster than
/// computing the union manually since it operates directly at the byte level.
/// </summary>
public static WAH8DocIdSet Union(ICollection<WAH8DocIdSet> docIdSets, int indexInterval)
{
switch (docIdSets.Count)
{
case 0:
return EMPTY;
case 1:
var iter = docIdSets.GetEnumerator();
iter.MoveNext();
return iter.Current;
}
// The logic below is very similar to DisjunctionScorer
int numSets = docIdSets.Count;
PriorityQueue<Iterator> iterators = new PriorityQueueAnonymousInnerClassHelper(numSets);
foreach (WAH8DocIdSet set in docIdSets)
{
Iterator iterator = (Iterator)set.GetIterator();
iterator.NextWord();
iterators.Add(iterator);
}
Iterator top = iterators.Top;
if (top.wordNum == int.MaxValue)
{
return EMPTY;
}
int wordNum = top.wordNum;
byte word = top.word;
WordBuilder builder = (WordBuilder)(new WordBuilder()).SetIndexInterval(indexInterval);
while (true)
{
top.NextWord();
iterators.UpdateTop();
top = iterators.Top;
if (top.wordNum == wordNum)
{
word |= top.word;
}
else
{
builder.AddWord(wordNum, word);
if (top.wordNum == int.MaxValue)
{
break;
}
wordNum = top.wordNum;
word = top.word;
}
}
return builder.Build();
}
private class PriorityQueueAnonymousInnerClassHelper : PriorityQueue<WAH8DocIdSet.Iterator>
{
public PriorityQueueAnonymousInnerClassHelper(int numSets)
: base(numSets)
{
}
protected internal override bool LessThan(Iterator a, Iterator b)
{
return a.wordNum < b.wordNum;
}
}
internal static int WordNum(int docID)
{
Debug.Assert(docID >= 0);
return (int)((uint)docID >> 3);
}
/// <summary>
/// Word-based builder. </summary>
public class WordBuilder
{
internal readonly GrowableByteArrayDataOutput @out;
internal readonly GrowableByteArrayDataOutput dirtyWords;
internal int clean;
internal int lastWordNum;
internal int numSequences;
internal int indexInterval;
internal int cardinality;
internal bool reverse;
internal WordBuilder()
{
@out = new GrowableByteArrayDataOutput(1024);
dirtyWords = new GrowableByteArrayDataOutput(128);
clean = 0;
lastWordNum = -1;
numSequences = 0;
indexInterval = DEFAULT_INDEX_INTERVAL;
cardinality = 0;
}
/// <summary>
/// Set the index interval. Smaller index intervals improve performance of
/// <see cref="DocIdSetIterator.Advance(int)"/> but make the <see cref="DocIdSet"/>
/// larger. An index interval <c>i</c> makes the index add an overhead
/// which is at most <c>4/i</c>, but likely much less. The default index
/// interval is <c>8</c>, meaning the index has an overhead of at most
/// 50%. To disable indexing, you can pass <see cref="int.MaxValue"/> as an
/// index interval.
/// </summary>
public virtual object SetIndexInterval(int indexInterval)
{
if (indexInterval < MIN_INDEX_INTERVAL)
{
throw new System.ArgumentException("indexInterval must be >= " + MIN_INDEX_INTERVAL);
}
this.indexInterval = indexInterval;
return this;
}
internal virtual void WriteHeader(bool reverse, int cleanLength, int dirtyLength)
{
int cleanLengthMinus2 = cleanLength - 2;
Debug.Assert(cleanLengthMinus2 >= 0);
Debug.Assert(dirtyLength >= 0);
int token = ((cleanLengthMinus2 & 0x03) << 4) | (dirtyLength & 0x07);
if (reverse)
{
token |= 1 << 7;
}
if (cleanLengthMinus2 > 0x03)
{
token |= 1 << 6;
}
if (dirtyLength > 0x07)
{
token |= 1 << 3;
}
@out.WriteByte((byte)(sbyte)token);
if (cleanLengthMinus2 > 0x03)
{
@out.WriteVInt32((int)((uint)cleanLengthMinus2 >> 2));
}
if (dirtyLength > 0x07)
{
@out.WriteVInt32((int)((uint)dirtyLength >> 3));
}
}
private bool SequenceIsConsistent()
{
for (int i = 1; i < dirtyWords.Length; ++i)
{
Debug.Assert(dirtyWords.Bytes[i - 1] != 0 || dirtyWords.Bytes[i] != 0);
Debug.Assert((byte)dirtyWords.Bytes[i - 1] != 0xFF || (byte)dirtyWords.Bytes[i] != 0xFF);
}
return true;
}
internal virtual void WriteSequence()
{
Debug.Assert(SequenceIsConsistent());
try
{
WriteHeader(reverse, clean, dirtyWords.Length);
}
catch (System.IO.IOException cannotHappen)
{
throw new InvalidOperationException(cannotHappen.ToString(), cannotHappen); // LUCENENET NOTE: This was AssertionError in Lucene
}
@out.WriteBytes(dirtyWords.Bytes, 0, dirtyWords.Length);
dirtyWords.Length = 0;
++numSequences;
}
internal virtual void AddWord(int wordNum, byte word)
{
Debug.Assert(wordNum > lastWordNum);
Debug.Assert(word != 0);
if (!reverse)
{
if (lastWordNum == -1)
{
clean = 2 + wordNum; // special case for the 1st sequence
dirtyWords.WriteByte(word);
}
else
{
switch (wordNum - lastWordNum)
{
case 1:
if (word == 0xFF && (byte)dirtyWords.Bytes[dirtyWords.Length - 1] == 0xFF)
{
--dirtyWords.Length;
WriteSequence();
reverse = true;
clean = 2;
}
else
{
dirtyWords.WriteByte(word);
}
break;
case 2:
dirtyWords.WriteByte(0);
dirtyWords.WriteByte(word);
break;
default:
WriteSequence();
clean = wordNum - lastWordNum - 1;
dirtyWords.WriteByte(word);
break;
}
}
}
else
{
Debug.Assert(lastWordNum >= 0);
switch (wordNum - lastWordNum)
{
case 1:
if (word == 0xFF)
{
if (dirtyWords.Length == 0)
{
++clean;
}
else if ((byte)dirtyWords.Bytes[dirtyWords.Length - 1] == 0xFF)
{
--dirtyWords.Length;
WriteSequence();
clean = 2;
}
else
{
dirtyWords.WriteByte(word);
}
}
else
{
dirtyWords.WriteByte(word);
}
break;
case 2:
dirtyWords.WriteByte(0);
dirtyWords.WriteByte(word);
break;
default:
WriteSequence();
reverse = false;
clean = wordNum - lastWordNum - 1;
dirtyWords.WriteByte(word);
break;
}
}
lastWordNum = wordNum;
cardinality += BitUtil.BitCount(word);
}
/// <summary>
/// Build a new <see cref="WAH8DocIdSet"/>. </summary>
public virtual WAH8DocIdSet Build()
{
if (cardinality == 0)
{
Debug.Assert(lastWordNum == -1);
return EMPTY;
}
WriteSequence();
byte[] data = Arrays.CopyOf(@out.Bytes, @out.Length);
// Now build the index
int valueCount = (numSequences - 1) / indexInterval + 1;
MonotonicAppendingInt64Buffer indexPositions, indexWordNums;
if (valueCount <= 1)
{
indexPositions = indexWordNums = SINGLE_ZERO_BUFFER;
}
else
{
const int pageSize = 128;
int initialPageCount = (valueCount + pageSize - 1) / pageSize;
MonotonicAppendingInt64Buffer positions = new MonotonicAppendingInt64Buffer(initialPageCount, pageSize, PackedInt32s.COMPACT);
MonotonicAppendingInt64Buffer wordNums = new MonotonicAppendingInt64Buffer(initialPageCount, pageSize, PackedInt32s.COMPACT);
positions.Add(0L);
wordNums.Add(0L);
Iterator it = new Iterator(data, cardinality, int.MaxValue, SINGLE_ZERO_BUFFER, SINGLE_ZERO_BUFFER);
Debug.Assert(it.@in.Position == 0);
Debug.Assert(it.wordNum == -1);
for (int i = 1; i < valueCount; ++i)
{
// skip indexInterval sequences
for (int j = 0; j < indexInterval; ++j)
{
bool readSequence = it.ReadSequence();
Debug.Assert(readSequence);
it.SkipDirtyBytes();
}
int position = it.@in.Position;
int wordNum = it.wordNum;
positions.Add(position);
wordNums.Add(wordNum + 1);
}
positions.Freeze();
wordNums.Freeze();
indexPositions = positions;
indexWordNums = wordNums;
}
return new WAH8DocIdSet(data, cardinality, indexInterval, indexPositions, indexWordNums);
}
}
/// <summary>
/// A builder for <see cref="WAH8DocIdSet"/>s. </summary>
public sealed class Builder : WordBuilder
{
private int lastDocID;
private int wordNum, word;
/// <summary>
/// Sole constructor </summary>
public Builder()
: base()
{
lastDocID = -1;
wordNum = -1;
word = 0;
}
/// <summary>
/// Add a document to this builder. Documents must be added in order. </summary>
public Builder Add(int docID)
{
if (docID <= lastDocID)
{
throw new System.ArgumentException("Doc ids must be added in-order, got " + docID + " which is <= lastDocID=" + lastDocID);
}
int wordNum = WordNum(docID);
if (this.wordNum == -1)
{
this.wordNum = wordNum;
word = 1 << (docID & 0x07);
}
else if (wordNum == this.wordNum)
{
word |= 1 << (docID & 0x07);
}
else
{
AddWord(this.wordNum, (byte)word);
this.wordNum = wordNum;
word = 1 << (docID & 0x07);
}
lastDocID = docID;
return this;
}
/// <summary>
/// Add the content of the provided <see cref="DocIdSetIterator"/>. </summary>
public Builder Add(DocIdSetIterator disi)
{
for (int doc = disi.NextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = disi.NextDoc())
{
Add(doc);
}
return this;
}
public override object SetIndexInterval(int indexInterval)
{
return (Builder)base.SetIndexInterval(indexInterval);
}
public override WAH8DocIdSet Build()
{
if (this.wordNum != -1)
{
AddWord(wordNum, (byte)word);
}
return base.Build();
}
}
// where the doc IDs are stored
private readonly byte[] data;
private readonly int cardinality;
private readonly int indexInterval;
// index for advance(int)
private readonly MonotonicAppendingInt64Buffer positions, wordNums; // wordNums[i] starts at the sequence at positions[i]
internal WAH8DocIdSet(byte[] data, int cardinality, int indexInterval, MonotonicAppendingInt64Buffer positions, MonotonicAppendingInt64Buffer wordNums)
{
this.data = data;
this.cardinality = cardinality;
this.indexInterval = indexInterval;
this.positions = positions;
this.wordNums = wordNums;
}
public override bool IsCacheable
{
get
{
return true;
}
}
public override DocIdSetIterator GetIterator()
{
return new Iterator(data, cardinality, indexInterval, positions, wordNums);
}
internal static int ReadCleanLength(ByteArrayDataInput @in, int token)
{
int len = ((int)((uint)token >> 4)) & 0x07;
int startPosition = @in.Position;
if ((len & 0x04) != 0)
{
len = (len & 0x03) | (@in.ReadVInt32() << 2);
}
if (startPosition != 1)
{
len += 2;
}
return len;
}
internal static int ReadDirtyLength(ByteArrayDataInput @in, int token)
{
int len = token & 0x0F;
if ((len & 0x08) != 0)
{
len = (len & 0x07) | (@in.ReadVInt32() << 3);
}
return len;
}
internal class Iterator : DocIdSetIterator
{
/* Using the index can be costly for close targets. */
internal static int IndexThreshold(int cardinality, int indexInterval)
{
// Short sequences encode for 3 words (2 clean words and 1 dirty byte),
// don't advance if we are going to read less than 3 x indexInterval
// sequences
long indexThreshold = 3L * 3 * indexInterval;
return (int)Math.Min(int.MaxValue, indexThreshold);
}
internal readonly ByteArrayDataInput @in;
internal readonly int cardinality;
internal readonly int indexInterval;
internal readonly MonotonicAppendingInt64Buffer positions, wordNums;
internal readonly int indexThreshold;
internal int allOnesLength;
internal int dirtyLength;
internal int wordNum; // byte offset
internal byte word; // current word
internal int bitList; // list of bits set in the current word
internal int sequenceNum; // in which sequence are we?
internal int docID;
internal Iterator(byte[] data, int cardinality, int indexInterval, MonotonicAppendingInt64Buffer positions, MonotonicAppendingInt64Buffer wordNums)
{
this.@in = new ByteArrayDataInput(data);
this.cardinality = cardinality;
this.indexInterval = indexInterval;
this.positions = positions;
this.wordNums = wordNums;
wordNum = -1;
word = 0;
bitList = 0;
sequenceNum = -1;
docID = -1;
indexThreshold = IndexThreshold(cardinality, indexInterval);
}
internal virtual bool ReadSequence()
{
if (@in.Eof)
{
wordNum = int.MaxValue;
return false;
}
int token = @in.ReadByte() & 0xFF;
if ((token & (1 << 7)) == 0)
{
int cleanLength = ReadCleanLength(@in, token);
wordNum += cleanLength;
}
else
{
allOnesLength = ReadCleanLength(@in, token);
}
dirtyLength = ReadDirtyLength(@in, token);
Debug.Assert(@in.Length - @in.Position >= dirtyLength, @in.Position + " " + @in.Length + " " + dirtyLength);
++sequenceNum;
return true;
}
internal virtual void SkipDirtyBytes(int count)
{
Debug.Assert(count >= 0);
Debug.Assert(count <= allOnesLength + dirtyLength);
wordNum += count;
if (count <= allOnesLength)
{
allOnesLength -= count;
}
else
{
count -= allOnesLength;
allOnesLength = 0;
@in.SkipBytes(count);
dirtyLength -= count;
}
}
internal virtual void SkipDirtyBytes()
{
wordNum += allOnesLength + dirtyLength;
@in.SkipBytes(dirtyLength);
allOnesLength = 0;
dirtyLength = 0;
}
internal virtual void NextWord()
{
if (allOnesLength > 0)
{
word = 0xFF;
++wordNum;
--allOnesLength;
return;
}
if (dirtyLength > 0)
{
word = @in.ReadByte();
++wordNum;
--dirtyLength;
if (word != 0)
{
return;
}
if (dirtyLength > 0)
{
word = @in.ReadByte();
++wordNum;
--dirtyLength;
Debug.Assert(word != 0); // never more than one consecutive 0
return;
}
}
if (ReadSequence())
{
NextWord();
}
}
internal virtual int ForwardBinarySearch(int targetWordNum)
{
// advance forward and double the window at each step
int indexSize = (int)wordNums.Count;
int lo = sequenceNum / indexInterval, hi = lo + 1;
Debug.Assert(sequenceNum == -1 || wordNums.Get(lo) <= wordNum);
Debug.Assert(lo + 1 == wordNums.Count || wordNums.Get(lo + 1) > wordNum);
while (true)
{
if (hi >= indexSize)
{
hi = indexSize - 1;
break;
}
else if (wordNums.Get(hi) >= targetWordNum)
{
break;
}
int newLo = hi;
hi += (hi - lo) << 1;
lo = newLo;
}
// we found a window containing our target, let's binary search now
while (lo <= hi)
{
int mid = (int)((uint)(lo + hi) >> 1);
int midWordNum = (int)wordNums.Get(mid);
if (midWordNum <= targetWordNum)
{
lo = mid + 1;
}
else
{
hi = mid - 1;
}
}
Debug.Assert(wordNums.Get(hi) <= targetWordNum);
Debug.Assert(hi + 1 == wordNums.Count || wordNums.Get(hi + 1) > targetWordNum);
return hi;
}
internal virtual void AdvanceWord(int targetWordNum)
{
Debug.Assert(targetWordNum > wordNum);
int delta = targetWordNum - wordNum;
if (delta <= allOnesLength + dirtyLength + 1)
{
SkipDirtyBytes(delta - 1);
}
else
{
SkipDirtyBytes();
Debug.Assert(dirtyLength == 0);
if (delta > indexThreshold)
{
// use the index
int i = ForwardBinarySearch(targetWordNum);
int position = (int)positions.Get(i);
if (position > @in.Position) // if the binary search returned a backward offset, don't move
{
wordNum = (int)wordNums.Get(i) - 1;
@in.Position = position;
sequenceNum = i * indexInterval - 1;
}
}
while (true)
{
if (!ReadSequence())
{
return;
}
delta = targetWordNum - wordNum;
if (delta <= allOnesLength + dirtyLength + 1)
{
if (delta > 1)
{
SkipDirtyBytes(delta - 1);
}
break;
}
SkipDirtyBytes();
}
}
NextWord();
}
public override int DocID
{
get { return docID; }
}
public override int NextDoc()
{
if (bitList != 0) // there are remaining bits in the current word
{
docID = (wordNum << 3) | ((bitList & 0x0F) - 1);
bitList = (int)((uint)bitList >> 4);
return docID;
}
NextWord();
if (wordNum == int.MaxValue)
{
return docID = NO_MORE_DOCS;
}
bitList = BitUtil.BitList(word);
Debug.Assert(bitList != 0);
docID = (wordNum << 3) | ((bitList & 0x0F) - 1);
bitList = (int)((uint)bitList >> 4);
return docID;
}
public override int Advance(int target)
{
Debug.Assert(target > docID);
int targetWordNum = WordNum(target);
if (targetWordNum > this.wordNum)
{
AdvanceWord(targetWordNum);
bitList = BitUtil.BitList(word);
}
return SlowAdvance(target);
}
public override long GetCost()
{
return cardinality;
}
}
/// <summary>
/// Return the number of documents in this <see cref="DocIdSet"/> in constant time. </summary>
public int Cardinality()
{
return cardinality;
}
/// <summary>
/// Return the memory usage of this class in bytes. </summary>
public long RamBytesUsed()
{
return RamUsageEstimator.AlignObjectSize(3 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + 2 * RamUsageEstimator.NUM_BYTES_INT32)
+ RamUsageEstimator.SizeOf(data)
+ positions.RamBytesUsed()
+ wordNums.RamBytesUsed();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class CustomAttributeBuilderTests
{
public static IEnumerable<object[]> Ctor_TestData()
{
string stringValue1 = "TestString1";
string stringValue2 = "TestString2";
int intValue1 = 10;
int intValue2 = 20;
// 2 ctor, 0 properties, 1 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[0], new object[0],
new object[] { intValue2, null, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue2 },
new object[] { intValue2, null, stringValue1, intValue1 }
};
// 2 ctor, 0 properties, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[0], new object[0],
new object[] { 0, null, stringValue1, intValue1 },
new string[0], new object[0],
new object[] { 0, null, stringValue1, intValue1 }
};
// 0 ctor, 0 properties, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[0], new object[0],
new object[] { 0, null, null, 0 },
new string[0], new object[0],
new object[] { 0, null, null, 0 }
};
// 0 ctor, 0 properties, 1 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[0], new object[0],
new object[] { intValue1, null, null, 0 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue1 },
new object[] { intValue1, null, null, 0 }
};
// 0 ctor, 0 properties, 2 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[0], new object[0],
new object[] { intValue1, stringValue1, null, 0 },
new string[] { nameof(TestAttribute.TestInt), nameof(TestAttribute.TestStringField) }, new object[] { intValue1, stringValue1 },
new object[] { intValue1, stringValue1, null, 0 }
};
// 2 ctor, 0 properties, 2 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[0], new object[0],
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt), nameof(TestAttribute.TestStringField) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 0 ctor, 0 properties,1 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[0], new object[0],
new object[] { 0, stringValue1, null, 0 },
new string[] { nameof(TestAttribute.TestStringField) }, new object[] { stringValue1 },
new object[] { 0, stringValue1, null, 0 }
};
// 2 ctor, 2 properties, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new object[0], new object[0],
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 2 ctor, 1 property, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt32) }, new object[] { intValue2 },
new object[] { intValue2, null, stringValue1, intValue1 },
new object[0], new object[0],
new object[] { intValue2, null, stringValue1, intValue1 }
};
// 0 ctor, 1 property, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[] { nameof(TestAttribute.TestInt32) }, new object[] { intValue2 },
new object[] { intValue2, null, null, 0 },
new object[0], new object[0],
new object[] { intValue2, null, null, 0 }
};
// 0 ctor, 2 properties, 0 fields
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, null, 0 },
new object[0], new object[0],
new object[] { intValue2, stringValue2, null, 0 }
};
// 4 ctor, 0 fields, 2 properties
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int), typeof(string), typeof(int) }), new object[] { stringValue1, intValue1, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new string[0], new object[0],
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 2 ctor, 2 property, 2 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt), nameof(TestAttribute.TestStringField) }, new object[] { intValue2, stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 2 ctor, 1 property, 1 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestString) }, new object[] { stringValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue2 },
new object[] { intValue2, stringValue2, stringValue1, intValue1 }
};
// 0 ctor, 2 property, 1 field
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[0]), new object[0],
new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { intValue1, stringValue1 },
new object[] { intValue2, stringValue1, null, 0 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue2 },
new object[] { intValue2, stringValue1, null, 0 }
};
// 2 ctor, 1 property, 0 field
string shortString = new string('a', 128);
string longString = new string('a', 16384);
yield return new object[]
{
typeof(TestAttribute).GetConstructor(new Type[] { typeof(string), typeof(int) }), new object[] { shortString, intValue1 },
new string[] { nameof(TestAttribute.TestString) }, new object[] { longString },
new object[] { 0, longString, shortString, intValue1 },
new string[0], new object[0],
new object[] { 0, longString, shortString, intValue1 }
};
// 0 ctor, 1 property, 1 field
yield return new object[]
{
typeof(SubAttribute).GetConstructor(new Type[0]), new object[0],
new string[] { nameof(TestAttribute.TestString) }, new object[] { stringValue1 },
new object[] { intValue1, stringValue1, null, 0 },
new string[] { nameof(TestAttribute.TestInt) }, new object[] { intValue1 },
new object[] { intValue1, stringValue1, null, 0 }
};
}
[Theory]
[MemberData(nameof(Ctor_TestData))]
public static void Ctor(ConstructorInfo con, object[] constructorArgs,
string[] propertyNames, object[] propertyValues,
object[] expectedPropertyValues,
string[] fieldNames, object[] fieldValues,
object[] expectedFieldValues)
{
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), propertyNames);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), fieldNames);
Action<CustomAttributeBuilder> verify = attr =>
{
VerifyCustomAttributeBuilder(attr, TestAttribute.AllProperties, expectedPropertyValues, TestAttribute.AllFields, expectedFieldValues);
};
if (namedProperties.Length == 0)
{
if (namedFields.Length == 0)
{
// Use CustomAttributeBuilder(ConstructorInfo, object[])
CustomAttributeBuilder attribute1 = new CustomAttributeBuilder(con, constructorArgs);
verify(attribute1);
}
// Use CustomAttributeBuilder(ConstructorInfo, object[], FieldInfo[], object[])
CustomAttributeBuilder attribute2 = new CustomAttributeBuilder(con, constructorArgs, namedFields, fieldValues);
verify(attribute2);
}
if (namedFields.Length == 0)
{
// Use CustomAttributeBuilder(ConstructorInfo, object[], PropertyInfo[], object[])
CustomAttributeBuilder attribute3 = new CustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues);
verify(attribute3);
}
// Use CustomAttributeBuilder(ConstructorInfo, object[], PropertyInfo[], object[], FieldInfo[], object[])
CustomAttributeBuilder attribute4 = new CustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
verify(attribute4);
}
private static void VerifyCustomAttributeBuilder(CustomAttributeBuilder builder,
PropertyInfo[] propertyNames, object[] propertyValues,
FieldInfo[] fieldNames, object[] fieldValues)
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(builder);
object[] customAttributes = assembly.GetCustomAttributes().ToArray();
Assert.Equal(1, customAttributes.Length);
object customAttribute = customAttributes[0];
for (int i = 0; i < fieldNames.Length; ++i)
{
FieldInfo field = typeof(TestAttribute).GetField(fieldNames[i].Name);
Assert.Equal(fieldValues[i], field.GetValue(customAttribute));
}
for (int i = 0; i < propertyNames.Length; ++i)
{
PropertyInfo property = typeof(TestAttribute).GetProperty(propertyNames[i].Name);
Assert.Equal(propertyValues[i], property.GetValue(customAttribute));
}
}
[Fact]
public static void Ctor_AllPrimitives()
{
ConstructorInfo con = typeof(Primitives).GetConstructors()[0];
object[] constructorArgs = new object[]
{
(sbyte)1, (byte)2, (short)3, (ushort)4, 5, (uint)6, (long)7, (ulong)8,
(SByteEnum)9, (ByteEnum)10, (ShortEnum)11, (UShortEnum)12, (IntEnum)13, (UIntEnum)14, (LongEnum)15, (ULongEnum)16,
(char)17, true, 2.0f, 2.1,
"abc", typeof(object), new int[] { 24, 25, 26 }, null
};
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(Primitives), new string[]
{
nameof(Primitives.SByteProperty), nameof(Primitives.ByteProperty), nameof(Primitives.ShortProperty), nameof(Primitives.UShortProperty), nameof(Primitives.IntProperty), nameof(Primitives.UIntProperty), nameof(Primitives.LongProperty), nameof(Primitives.ULongProperty),
nameof(Primitives.SByteEnumProperty), nameof(Primitives.ByteEnumProperty), nameof(Primitives.ShortEnumProperty), nameof(Primitives.UShortEnumProperty), nameof(Primitives.IntEnumProperty), nameof(Primitives.UIntEnumProperty), nameof(Primitives.LongEnumProperty), nameof(Primitives.ULongEnumProperty),
nameof(Primitives.CharProperty), nameof(Primitives.BoolProperty), nameof(Primitives.FloatProperty), nameof(Primitives.DoubleProperty),
nameof(Primitives.StringProperty), nameof(Primitives.TypeProperty), nameof(Primitives.ArrayProperty), nameof(Primitives.ObjectProperty)
});
object[] propertyValues = new object[]
{
(sbyte)27, (byte)28, (short)29, (ushort)30, 31, (uint)32, (long)33, (ulong)34,
(SByteEnum)35, (ByteEnum)36, (ShortEnum)37, (UShortEnum)38, (IntEnum)39, (UIntEnum)40, (LongEnum)41, (ULongEnum)42,
(char)43, false, 4.4f, 4.5,
"def", typeof(bool), new int[] { 48, 49, 50 }, "stringAsObject"
};
FieldInfo[] namedFields = Helpers.GetFields(typeof(Primitives), new string[]
{
nameof(Primitives.SByteField), nameof(Primitives.ByteField), nameof(Primitives.ShortField), nameof(Primitives.UShortField), nameof(Primitives.IntField), nameof(Primitives.UIntField), nameof(Primitives.LongField), nameof(Primitives.ULongField),
nameof(Primitives.SByteEnumField), nameof(Primitives.ByteEnumField), nameof(Primitives.ShortEnumField), nameof(Primitives.UShortEnumField), nameof(Primitives.IntEnumField), nameof(Primitives.UIntEnumField), nameof(Primitives.LongEnumField), nameof(Primitives.ULongEnumField),
nameof(Primitives.CharField), nameof(Primitives.BoolField), nameof(Primitives.FloatField), nameof(Primitives.DoubleField),
nameof(Primitives.StringField), nameof(Primitives.TypeField), nameof(Primitives.ArrayField), nameof(Primitives.ObjectField)
});
object[] fieldValues = new object[]
{
(sbyte)51, (byte)52, (short)53, (ushort)54, 55, (uint)56, (long)57, (ulong)58,
(SByteEnum)59, (ByteEnum)60, (ShortEnum)61, (UShortEnum)62, (IntEnum)63, (UIntEnum)64, (LongEnum)65, (ULongEnum)66,
(char)67, true, 6.8f, 6.9,
null, null, null, 70
};
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attributeBuilder);
object[] customAttributes = assembly.GetCustomAttributes().ToArray();
Assert.Equal(1, customAttributes.Length);
Primitives attribute = (Primitives)customAttributes[0];
// Constructor: primitives
Assert.Equal(constructorArgs[0], attribute.SByteConstructor);
Assert.Equal(constructorArgs[1], attribute.ByteConstructor);
Assert.Equal(constructorArgs[2], attribute.ShortConstructor);
Assert.Equal(constructorArgs[3], attribute.UShortConstructor);
Assert.Equal(constructorArgs[4], attribute.IntConstructor);
Assert.Equal(constructorArgs[5], attribute.UIntConstructor);
Assert.Equal(constructorArgs[6], attribute.LongConstructor);
Assert.Equal(constructorArgs[7], attribute.ULongConstructor);
// Constructors: enums
Assert.Equal(constructorArgs[8], attribute.SByteEnumConstructor);
Assert.Equal(constructorArgs[9], attribute.ByteEnumConstructor);
Assert.Equal(constructorArgs[10], attribute.ShortEnumConstructor);
Assert.Equal(constructorArgs[11], attribute.UShortEnumConstructor);
Assert.Equal(constructorArgs[12], attribute.IntEnumConstructor);
Assert.Equal(constructorArgs[13], attribute.UIntEnumConstructor);
Assert.Equal(constructorArgs[14], attribute.LongEnumConstructor);
Assert.Equal(constructorArgs[15], attribute.ULongEnumConstructor);
// Constructors: other primitives
Assert.Equal(constructorArgs[16], attribute.CharConstructor);
Assert.Equal(constructorArgs[17], attribute.BoolConstructor);
Assert.Equal(constructorArgs[18], attribute.FloatConstructor);
Assert.Equal(constructorArgs[19], attribute.DoubleConstructor);
// Constructors: misc
Assert.Equal(constructorArgs[20], attribute.StringConstructor);
Assert.Equal(constructorArgs[21], attribute.TypeConstructor);
Assert.Equal(constructorArgs[22], attribute.ArrayConstructor);
Assert.Equal(constructorArgs[23], attribute.ObjectConstructor);
// Field: primitives
Assert.Equal(fieldValues[0], attribute.SByteField);
Assert.Equal(fieldValues[1], attribute.ByteField);
Assert.Equal(fieldValues[2], attribute.ShortField);
Assert.Equal(fieldValues[3], attribute.UShortField);
Assert.Equal(fieldValues[4], attribute.IntField);
Assert.Equal(fieldValues[5], attribute.UIntField);
Assert.Equal(fieldValues[6], attribute.LongField);
Assert.Equal(fieldValues[7], attribute.ULongField);
// Fields: enums
Assert.Equal(fieldValues[8], attribute.SByteEnumField);
Assert.Equal(fieldValues[9], attribute.ByteEnumField);
Assert.Equal(fieldValues[10], attribute.ShortEnumField);
Assert.Equal(fieldValues[11], attribute.UShortEnumField);
Assert.Equal(fieldValues[12], attribute.IntEnumField);
Assert.Equal(fieldValues[13], attribute.UIntEnumField);
Assert.Equal(fieldValues[14], attribute.LongEnumField);
Assert.Equal(fieldValues[15], attribute.ULongEnumField);
// Fields: other primitives
Assert.Equal(fieldValues[16], attribute.CharField);
Assert.Equal(fieldValues[17], attribute.BoolField);
Assert.Equal(fieldValues[18], attribute.FloatField);
Assert.Equal(fieldValues[19], attribute.DoubleField);
// Fields: misc
Assert.Equal(fieldValues[20], attribute.StringField);
Assert.Equal(fieldValues[21], attribute.TypeField);
Assert.Equal(fieldValues[22], attribute.ArrayField);
Assert.Equal(fieldValues[23], attribute.ObjectField);
// Properties: primitives
Assert.Equal(propertyValues[0], attribute.SByteProperty);
Assert.Equal(propertyValues[1], attribute.ByteProperty);
Assert.Equal(propertyValues[2], attribute.ShortProperty);
Assert.Equal(propertyValues[3], attribute.UShortProperty);
Assert.Equal(propertyValues[4], attribute.IntProperty);
Assert.Equal(propertyValues[5], attribute.UIntProperty);
Assert.Equal(propertyValues[6], attribute.LongProperty);
Assert.Equal(propertyValues[7], attribute.ULongProperty);
// Properties: enums
Assert.Equal(propertyValues[8], attribute.SByteEnumProperty);
Assert.Equal(propertyValues[9], attribute.ByteEnumProperty);
Assert.Equal(propertyValues[10], attribute.ShortEnumProperty);
Assert.Equal(propertyValues[11], attribute.UShortEnumProperty);
Assert.Equal(propertyValues[12], attribute.IntEnumProperty);
Assert.Equal(propertyValues[13], attribute.UIntEnumProperty);
Assert.Equal(propertyValues[14], attribute.LongEnumProperty);
Assert.Equal(propertyValues[15], attribute.ULongEnumProperty);
// Properties: other primitives
Assert.Equal(propertyValues[16], attribute.CharProperty);
Assert.Equal(propertyValues[17], attribute.BoolProperty);
Assert.Equal(propertyValues[18], attribute.FloatProperty);
Assert.Equal(propertyValues[19], attribute.DoubleProperty);
// Properties: misc
Assert.Equal(propertyValues[20], attribute.StringProperty);
Assert.Equal(propertyValues[21], attribute.TypeProperty);
Assert.Equal(propertyValues[22], attribute.ArrayProperty);
Assert.Equal(propertyValues[23], attribute.ObjectProperty);
}
public static IEnumerable<object[]> Ctor_RefEmitParameters_TestData()
{
AssemblyBuilder assemblyBuilder = Helpers.DynamicAssembly();
TypeBuilder typeBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule").DefineType("DynamicType", TypeAttributes.Public, typeof(Attribute));
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]);
constructorBuilder.GetILGenerator().Emit(OpCodes.Ret);
FieldBuilder fieldBuilder = typeBuilder.DefineField("Field", typeof(int), FieldAttributes.Public);
FieldBuilder fieldBuilderProperty = typeBuilder.DefineField("PropertyField", typeof(int), FieldAttributes.Public);
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty("Property", PropertyAttributes.None, typeof(int), new Type[0]);
MethodBuilder setMethod = typeBuilder.DefineMethod("set_Property", MethodAttributes.Public, typeof(void), new Type[] { typeof(int) });
ILGenerator setMethodGenerator = setMethod.GetILGenerator();
setMethodGenerator.Emit(OpCodes.Ldarg_0);
setMethodGenerator.Emit(OpCodes.Ldarg_1);
setMethodGenerator.Emit(OpCodes.Stfld, fieldBuilderProperty);
setMethodGenerator.Emit(OpCodes.Ret);
propertyBuilder.SetSetMethod(setMethod);
Type createdType = typeBuilder.CreateTypeInfo().AsType();
// ConstructorBuilder, PropertyInfo, FieldInfo
yield return new object[]
{
constructorBuilder, new object[0],
new PropertyInfo[] { createdType.GetProperty(propertyBuilder.Name) }, new object[] { 1 },
new FieldInfo[] { createdType.GetField(fieldBuilder.Name) }, new object[] { 2 }
};
// ConstructorInfo, PropertyBuilder, FieldBuilder
yield return new object[]
{
createdType.GetConstructor(new Type[0]), new object[0],
new PropertyInfo[] { propertyBuilder }, new object[] { 1 },
new FieldInfo[] { fieldBuilder }, new object[] { 2 }
};
// ConstructorBuilder, PropertyBuilder, FieldBuilder
yield return new object[]
{
constructorBuilder, new object[0],
new PropertyInfo[] { propertyBuilder }, new object[] { 1 },
new FieldInfo[] { fieldBuilder }, new object[] { 2 }
};
}
[Theory]
[MemberData(nameof(Ctor_RefEmitParameters_TestData))]
public static void Ctor_RefEmitParameters(ConstructorInfo con, object[] constructorArgs,
PropertyInfo[] namedProperties, object[] propertyValues,
FieldInfo[] namedFields, object[] fieldValues)
{
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, namedFields, fieldValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
object createdAttribute = assembly.GetCustomAttributes().First();
Assert.Equal(propertyValues[0], createdAttribute.GetType().GetField("PropertyField").GetValue(createdAttribute));
Assert.Equal(fieldValues[0], createdAttribute.GetType().GetField("Field").GetValue(createdAttribute));
}
[Theory]
[InlineData(nameof(TestAttribute.ReadonlyField))]
[InlineData(nameof(TestAttribute.StaticField))]
[InlineData(nameof(TestAttribute.StaticReadonlyField))]
public void NamedFields_ContainsReadonlyOrStaticField_Works(string name)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = new FieldInfo[] { typeof(TestAttribute).GetField(name) };
object[] fieldValues = new object[] { 5 };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
object customAttribute = assembly.GetCustomAttributes().First();
Assert.Equal(fieldValues[0], namedFields[0].GetValue(namedFields[0].IsStatic ? null : customAttribute));
}
[Fact]
public void NamedProperties_StaticProperty_Works()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = new PropertyInfo[] { typeof(TestAttribute).GetProperty(nameof(TestAttribute.StaticProperty)) };
object[] propertyValues = new object[] { 5 };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
object customAttribute = assembly.GetCustomAttributes().First();
Assert.Equal(propertyValues[0], TestAttribute.StaticProperty);
}
[Theory]
[InlineData(typeof(PrivateAttribute))]
[InlineData(typeof(NotAnAttribute))]
public static void ClassNotSupportedAsAttribute_DoesNotThrow_DoesNotSet(Type type)
{
ConstructorInfo con = type.GetConstructor(new Type[0]);
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0]);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
Assert.Empty(assembly.GetCustomAttributes());
}
[Fact]
public static void NullConstructor_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("con", () => new CustomAttributeBuilder(null, new object[0]));
Assert.Throws<ArgumentNullException>("con", () => new CustomAttributeBuilder(null, new object[0], new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentNullException>("con", () => new CustomAttributeBuilder(null, new object[0], new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentNullException>("con", () => new CustomAttributeBuilder(null, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void StaticConstructor_ThrowsArgumentException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).First();
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void PrivateConstructor_ThrowsArgumentException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First();
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Theory]
[InlineData(CallingConventions.Any)]
[InlineData(CallingConventions.VarArgs)]
public static void ConstructorHasNonStandardCallingConvention_ThrowsArgumentException(CallingConventions callingConvention)
{
TypeBuilder typeBuilder = Helpers.DynamicType(TypeAttributes.Public);
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, callingConvention, new Type[0]);
constructorBuilder.GetILGenerator().Emit(OpCodes.Ret);
ConstructorInfo con = typeBuilder.CreateTypeInfo().AsType().GetConstructor(new Type[0]);
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void NullConstructorArgs_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(int) });
Assert.Throws<ArgumentNullException>("constructorArgs", () => new CustomAttributeBuilder(con, null));
Assert.Throws<ArgumentNullException>("constructorArgs", () => new CustomAttributeBuilder(con, null, new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentNullException>("constructorArgs", () => new CustomAttributeBuilder(con, null, new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentNullException>("constructorArgs", () => new CustomAttributeBuilder(con, null, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
public static IEnumerable<object[]> NotSupportedObject_Constructor_TestData()
{
yield return new object[] { new int[0, 0] };
yield return new object[] { Enum.GetValues(CreateEnum(typeof(char), 'a')).GetValue(0) };
yield return new object[] { Enum.GetValues(CreateEnum(typeof(bool), true)).GetValue(0) };
}
public static IEnumerable<object[]> FloatEnum_DoubleEnum_TestData()
{
yield return new object[] { Enum.GetValues(CreateEnum(typeof(float), 0.0f)).GetValue(0) };
yield return new object[] { Enum.GetValues(CreateEnum(typeof(double), 0.0)).GetValue(0) };
}
public static IEnumerable<object[]> NotSupportedObject_Others_TestData()
{
yield return new object[] { new Guid() };
yield return new object[] { new int[5, 5] };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Netfx doesn't support Enum.GetEnumName for float or double enums.")]
[MemberData(nameof(FloatEnum_DoubleEnum_TestData))]
public void ConstructorArgsContainsFloatEnumOrDoubleEnum_ThrowsArgumentException(object value)
{
NotSupportedObjectInConstructorArgs_ThrowsArgumentException(value);
}
[Theory]
[MemberData(nameof(NotSupportedObject_Constructor_TestData))]
[MemberData(nameof(NotSupportedObject_Others_TestData))]
public static void NotSupportedObjectInConstructorArgs_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(object) });
object[] constructorArgs = new object[] { value };
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Theory]
[InlineData(new Type[] { typeof(int) }, new object[] { 123, false })]
[InlineData(new Type[] { typeof(int), typeof(bool) }, new object[] { false, 123 })]
[InlineData(new Type[] { typeof(string), typeof(int), typeof(string), typeof(int) }, new object[] { "TestString", 10 })]
public void ConstructorAndConstructorArgsDontMatch_ThrowsArgumentException(Type[] constructorTypes, object[] constructorArgs)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(constructorTypes);
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
public static IEnumerable<object[]> IntPtrAttributeTypes_TestData()
{
yield return new object[] { typeof(IntPtr), (IntPtr)1 };
yield return new object[] { typeof(UIntPtr), (UIntPtr)1 };
}
public static IEnumerable<object[]> InvalidAttributeTypes_TestData()
{
yield return new object[] { typeof(Guid), new Guid() };
yield return new object[] { typeof(int[,]), new int[5, 5] };
yield return new object[] { CreateEnum(typeof(char), 'a'), 'a' };
yield return new object[] { CreateEnum(typeof(bool), false), true };
yield return new object[] { CreateEnum(typeof(float), 1.0f), 1.0f };
yield return new object[] { CreateEnum(typeof(double), 1.0), 1.0 };
yield return new object[] { CreateEnum(typeof(IntPtr)), (IntPtr)1 };
yield return new object[] { CreateEnum(typeof(UIntPtr)), (UIntPtr)1 };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Coreclr fixed an issue where IntPtr/UIntPtr in constructorParameters causes a corrupt created binary.")]
[MemberData(nameof(IntPtrAttributeTypes_TestData))]
public void ConstructorParametersContainsIntPtrOrUIntPtrArgument_ThrowsArgumentException(Type type, object value)
{
ConstructorParametersNotSupportedInAttributes_ThrowsArgumentException(type, value);
}
[Theory]
[MemberData(nameof(InvalidAttributeTypes_TestData))]
public void ConstructorParametersNotSupportedInAttributes_ThrowsArgumentException(Type type, object value)
{
TypeBuilder typeBuilder = Helpers.DynamicType(TypeAttributes.Public);
ConstructorInfo con = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { type });
object[] constructorArgs = new object[] { value };
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Used to throw a NullReferenceException, see issue #11702.")]
public void NullValueForPrimitiveTypeInConstructorArgs_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(int) });
object[] constructorArgs = new object[] { null };
Assert.Throws<ArgumentNullException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs));
Assert.Throws<ArgumentNullException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentNullException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentNullException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
public static IEnumerable<object[]> NotSupportedPrimitives_TestData()
{
yield return new object[] { (IntPtr)1 };
yield return new object[] { (UIntPtr)1 };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Coreclr fixed an issue where IntPtr/UIntPtr in constructorArgs causes a corrupt created binary.")]
[MemberData(nameof(NotSupportedPrimitives_TestData))]
public static void NotSupportedPrimitiveInConstructorArgs_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(object) });
object[] constructorArgs = new object[] { value };
Assert.Throws<ArgumentException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs));
Assert.Throws<ArgumentException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new FieldInfo[0], new object[0]));
Assert.Throws<ArgumentException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0]));
Assert.Throws<ArgumentException>("constructorArgs[0]", () => new CustomAttributeBuilder(con, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void DynamicTypeInConstructorArgs_ThrowsFileNotFoundExceptionOnCreation()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
TypeBuilder type = assembly.DefineDynamicModule("DynamicModule").DefineType("DynamicType");
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[] { typeof(object) });
object[] constructorArgs = new object[] { type };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, constructorArgs);
assembly.SetCustomAttribute(attribute);
Assert.Throws<FileNotFoundException>(() => assembly.GetCustomAttributes());
}
[Fact]
public static void NullNamedFields_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
Assert.Throws<ArgumentNullException>("namedFields", () => new CustomAttributeBuilder(con, new object[0], (FieldInfo[])null, new object[0]));
Assert.Throws<ArgumentNullException>("namedFields", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], null, new object[0]));
}
[Theory]
[MemberData(nameof(InvalidAttributeTypes_TestData))]
public void NamedFields_FieldTypeNotSupportedInAttributes_ThrowsArgumentException(Type type, object value)
{
TypeBuilder typeBuilder = Helpers.DynamicType(TypeAttributes.Public);
FieldInfo field = typeBuilder.DefineField("Field", type, FieldAttributes.Public);
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = new FieldInfo[] { field };
object[] fieldValues = new object[] { value };
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, fieldValues));
}
public static IEnumerable<object[]> FieldDoesntBelongToConstructorDeclaringType_TestData()
{
// Different declaring type
yield return new object[] { typeof(TestAttribute).GetConstructor(new Type[0]), typeof(OtherTestAttribute).GetField(nameof(OtherTestAttribute.Field)) };
// Base class and sub class declaring types
yield return new object[] { typeof(TestAttribute).GetConstructor(new Type[0]), typeof(SubAttribute).GetField(nameof(SubAttribute.SubField)) };
}
[Theory]
[MemberData(nameof(FieldDoesntBelongToConstructorDeclaringType_TestData))]
public void NamedFields_FieldDoesntBelongToConstructorDeclaringType_ThrowsArgumentException(ConstructorInfo con, FieldInfo field)
{
FieldInfo[] namedFields = new FieldInfo[] { field };
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedFields, new object[] { 5 }));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, new object[] { 5 }));
}
[Fact]
public void NamedFields_ContainsConstField_ThrowsArgumentException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = new FieldInfo[] { typeof(TestAttribute).GetField(nameof(TestAttribute.ConstField)) };
object[] propertyValues = new object[] { 5 };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedFields, propertyValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
// CustomAttributeFormatException is not exposed on .NET Core
Exception ex = Assert.ThrowsAny<Exception>(() => assembly.GetCustomAttributes());
Assert.Equal("System.Reflection.CustomAttributeFormatException", ex.GetType().ToString());
}
[Fact]
public static void NullFieldValues_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
Assert.Throws<ArgumentNullException>("fieldValues", () => new CustomAttributeBuilder(con, new object[0], new FieldInfo[0], null));
Assert.Throws<ArgumentNullException>("fieldValues", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], new FieldInfo[0], null));
}
[Fact]
public static void NullObjectInNamedFields_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = new FieldInfo[] { null };
Assert.Throws<ArgumentNullException>("namedFields[0]", () => new CustomAttributeBuilder(con, new object[0], namedFields, new object[1]));
Assert.Throws<ArgumentNullException>("namedFields[0]", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, new object[1]));
}
[Fact]
public static void NullObjectInFieldValues_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.TestInt));
object[] fieldValues = new object[] { null };
Assert.Throws<ArgumentNullException>("fieldValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
Assert.Throws<ArgumentNullException>("fieldValues[0]", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, fieldValues));
}
[Theory]
[MemberData(nameof(NotSupportedObject_Others_TestData))]
public static void NotSupportedObjectInFieldValues_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.ObjectField));
object[] fieldValues = new object[] { value };
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, fieldValues));
}
[Fact]
public static void ZeroCountMultidimensionalArrayInFieldValues_ChangesToZeroCountJaggedArray()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.ObjectField));
object[] fieldValues = new object[] { new int[0, 0] };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
TestAttribute customAttribute = (TestAttribute)assembly.GetCustomAttributes().First();
Array objectField = (Array)customAttribute.ObjectField;
Assert.IsType<int[]>(objectField);
Assert.Equal(0, objectField.Length);
}
[Theory]
[MemberData(nameof(NotSupportedPrimitives_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Coreclr fixed an issue where IntPtr/UIntPtr in fieldValues causes a corrupt created binary.")]
public static void NotSupportedPrimitiveInFieldValues_ThrowsArgumentException(object value)
{
// Used to assert in CustomAttributeBuilder.EmitType(), not writing any CustomAttributeEncoding.
// This created a blob that (probably) generates a CustomAttributeFormatException. In theory, this
// could have been something more uncontrolled, so was fixed. See issue #11703.
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.ObjectField));
object[] fieldValues = new object[] { value };
Assert.Throws<ArgumentException>("fieldValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
Assert.Throws<ArgumentException>("fieldValues[0]", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new FieldInfo[0], namedFields, fieldValues));
}
[Fact]
public static void DynamicTypeInPropertyValues_ThrowsFileNotFoundExceptionOnCreation()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
TypeBuilder type = assembly.DefineDynamicModule("DynamicModule").DefineType("DynamicType");
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), nameof(TestAttribute.ObjectField));
object[] fieldValues = new object[] { type };
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues);
assembly.SetCustomAttribute(attribute);
Assert.Throws<FileNotFoundException>(() => assembly.GetCustomAttributes());
}
[Theory]
[InlineData(new string[] { nameof(TestAttribute.TestInt) }, new object[0], "namedFields, fieldValues")]
[InlineData(new string[] { nameof(TestAttribute.TestInt) }, new object[] { "TestString", 10 }, "namedFields, fieldValues")]
[InlineData(new string[] { nameof(TestAttribute.TestInt), nameof(TestAttribute.TestStringField) }, new object[] { "TestString", 10 }, null)]
[InlineData(new string[] { nameof(TestAttribute.TestStringField) }, new object[] { 10 }, null)]
public void NamedFieldAndFieldValuesDifferentLengths_ThrowsArgumentException(string[] fieldNames, object[] fieldValues, string paramName)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
FieldInfo[] namedFields = Helpers.GetFields(typeof(TestAttribute), fieldNames);
Assert.Throws<ArgumentException>(paramName, () => new CustomAttributeBuilder(con, new object[0], namedFields, fieldValues));
Assert.Throws<ArgumentException>(paramName, () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], new object[0], namedFields, fieldValues));
}
[Fact]
public static void NullNamedProperties_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
Assert.Throws<ArgumentNullException>("namedProperties", () => new CustomAttributeBuilder(con, new object[0], (PropertyInfo[])null, new object[0]));
Assert.Throws<ArgumentNullException>("namedProperties", () => new CustomAttributeBuilder(con, new object[0], null, new object[0], new FieldInfo[0], new object[0]));
}
[Fact]
public static void NullPropertyValues_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
Assert.Throws<ArgumentNullException>("propertyValues", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], null));
Assert.Throws<ArgumentNullException>("propertyValues", () => new CustomAttributeBuilder(con, new object[0], new PropertyInfo[0], null, new FieldInfo[0], new object[0]));
}
[Fact]
public static void NullObjectInNamedProperties_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = new PropertyInfo[] { null };
Assert.Throws<ArgumentNullException>("namedProperties[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, new object[1]));
Assert.Throws<ArgumentNullException>("namedProperties[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, new object[1], new FieldInfo[0], new object[0]));
}
[Fact]
public static void IndexerInNamedProperties_ThrowsCustomAttributeFormatExceptionOnCreation()
{
ConstructorInfo con = typeof(IndexerAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = new PropertyInfo[] { typeof(IndexerAttribute).GetProperty("Item") };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, new object[] { "abc" });
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
// CustomAttributeFormatException is not exposed on .NET Core
Exception ex = Assert.ThrowsAny<Exception>(() => assembly.GetCustomAttributes());
Assert.Equal("System.Reflection.CustomAttributeFormatException", ex.GetType().ToString());
}
[Theory]
[MemberData(nameof(InvalidAttributeTypes_TestData))]
[MemberData(nameof(IntPtrAttributeTypes_TestData))]
public void NamedProperties_TypeNotSupportedInAttributes_ThrowsArgumentException(Type type, object value)
{
TypeBuilder typeBuilder = Helpers.DynamicType(TypeAttributes.Public);
PropertyBuilder property = typeBuilder.DefineProperty("Property", PropertyAttributes.None, type, new Type[0]);
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = new PropertyInfo[] { property };
object[] propertyValues = new object[] { value };
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
public static IEnumerable<object[]> PropertyDoesntBelongToConstructorDeclaringType_TestData()
{
// Different declaring type
yield return new object[] { typeof(TestAttribute).GetConstructor(new Type[0]), typeof(OtherTestAttribute).GetProperty(nameof(OtherTestAttribute.Property)) };
// Base class and sub class declaring types
yield return new object[] { typeof(TestAttribute).GetConstructor(new Type[0]), typeof(SubAttribute).GetProperty(nameof(SubAttribute.SubProperty)) };
}
[Theory]
[MemberData(nameof(PropertyDoesntBelongToConstructorDeclaringType_TestData))]
public void NamedProperties_PropertyDoesntBelongToConstructorDeclaringType_ThrowsArgumentException(ConstructorInfo con, PropertyInfo property)
{
PropertyInfo[] namedProperties = new PropertyInfo[] { property };
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, new object[] { 5 }));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, new object[] { 5 }, new FieldInfo[0], new object[0]));
}
[Fact]
public static void NullObjectInPropertyValues_ThrowsArgumentNullException()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.TestInt32));
object[] propertyValues = new object[] { null };
Assert.Throws<ArgumentNullException>("propertyValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
Assert.Throws<ArgumentNullException>("propertyValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
[Theory]
[MemberData(nameof(NotSupportedObject_Others_TestData))]
public static void NotSupportedObjectInPropertyValues_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.ObjectProperty));
object[] propertyValues = new object[] { value };
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
Assert.Throws<ArgumentException>(null, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
[Fact]
public static void ZeroCountMultidimensionalArrayInPropertyValues_ChangesToZeroCountJaggedArray()
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.ObjectProperty));
object[] propertyValues = new object[] { new int[0, 0] };
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues);
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.SetCustomAttribute(attribute);
TestAttribute customAttribute = (TestAttribute)assembly.GetCustomAttributes().First();
Array objectProperty = (Array)customAttribute.ObjectProperty;
Assert.IsType<int[]>(objectProperty);
Assert.Equal(0, objectProperty.Length);
}
[Theory]
[MemberData(nameof(NotSupportedPrimitives_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Coreclr fixed an issue where IntPtr/UIntPtr in propertValues causes a corrupt created binary.")]
public static void NotSupportedPrimitiveInPropertyValues_ThrowsArgumentException(object value)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.ObjectProperty));
object[] propertyValues = new object[] { value };
Assert.Throws<ArgumentException>("propertyValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
Assert.Throws<ArgumentException>("propertyValues[0]", () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
[Fact]
public static void DynamicTypeInFieldValues_ThrowsFileNotFoundExceptionOnCreation()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
TypeBuilder type = assembly.DefineDynamicModule("DynamicModule").DefineType("DynamicType");
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), nameof(TestAttribute.ObjectProperty));
object[] propertyValues = new object[] { type };
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues);
assembly.SetCustomAttribute(attribute);
Assert.Throws<FileNotFoundException>(() => assembly.GetCustomAttributes());
}
[Theory]
[InlineData(new string[] { nameof(TestAttribute.TestInt32) }, new object[0], "namedProperties, propertyValues")]
[InlineData(new string[0], new object[] { 10 }, "namedProperties, propertyValues")]
[InlineData(new string[] { nameof(TestAttribute.TestInt32), nameof(TestAttribute.TestString) }, new object[] { "TestString", 10 }, null)]
[InlineData(new string[] { nameof(TestAttribute.GetOnlyInt32) }, new object[] { "TestString" }, null)]
[InlineData(new string[] { nameof(TestAttribute.GetOnlyString) }, new object[] { "TestString" }, null)]
[InlineData(new string[] { nameof(TestAttribute.TestInt32) }, new object[] { "TestString" }, null)]
public void NamedPropertyAndPropertyValuesDifferentLengths_ThrowsArgumentException(string[] propertyNames, object[] propertyValues, string paramName)
{
ConstructorInfo con = typeof(TestAttribute).GetConstructor(new Type[0]);
PropertyInfo[] namedProperties = Helpers.GetProperties(typeof(TestAttribute), propertyNames);
Assert.Throws<ArgumentException>(paramName, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues));
Assert.Throws<ArgumentException>(paramName, () => new CustomAttributeBuilder(con, new object[0], namedProperties, propertyValues, new FieldInfo[0], new object[0]));
}
private static Type CreateEnum(Type underlyingType, params object[] literalValues)
{
ModuleBuilder module = Helpers.DynamicModule();
EnumBuilder enumBuilder = module.DefineEnum("Name", TypeAttributes.Public, underlyingType);
for (int i = 0; i < (literalValues?.Length ?? 0); i++)
{
enumBuilder.DefineLiteral("Value" + i, literalValues[i]);
}
return enumBuilder.CreateTypeInfo().AsType();
}
}
public class OtherTestAttribute : Attribute
{
public int Property { get; set; }
public int Field;
}
class PrivateAttribute : Attribute { }
public class NotAnAttribute { }
public class Primitives : Attribute
{
public Primitives(sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul,
SByteEnum sbe, ByteEnum be, ShortEnum se, UShortEnum use, IntEnum ie, UIntEnum uie, LongEnum le, ULongEnum ule,
char c, bool bo, float f, double d,
string str, Type t, int[] arr, object obj)
{
SByteConstructor = sb;
ByteConstructor = b;
ShortConstructor = s;
UShortConstructor = us;
IntConstructor = i;
UIntConstructor = ui;
LongConstructor = l;
ULongConstructor = ul;
SByteEnumConstructor = sbe;
ByteEnumConstructor = be;
ShortEnumConstructor = se;
UShortEnumConstructor = use;
IntEnumConstructor = ie;
UIntEnumConstructor = uie;
LongEnumConstructor = le;
ULongEnumConstructor = ule;
CharConstructor = c;
BoolConstructor = bo;
FloatConstructor = f;
DoubleConstructor = d;
StringConstructor = str;
TypeConstructor = t;
ArrayConstructor = arr;
ObjectConstructor = obj;
}
public sbyte SByteConstructor;
public byte ByteConstructor;
public short ShortConstructor;
public ushort UShortConstructor;
public int IntConstructor;
public uint UIntConstructor;
public long LongConstructor;
public ulong ULongConstructor;
public SByteEnum SByteEnumConstructor;
public ByteEnum ByteEnumConstructor;
public ShortEnum ShortEnumConstructor;
public UShortEnum UShortEnumConstructor;
public IntEnum IntEnumConstructor;
public UIntEnum UIntEnumConstructor;
public LongEnum LongEnumConstructor;
public ULongEnum ULongEnumConstructor;
public char CharConstructor;
public bool BoolConstructor;
public float FloatConstructor;
public double DoubleConstructor;
public string StringConstructor;
public Type TypeConstructor;
public int[] ArrayConstructor;
public object ObjectConstructor;
public sbyte SByteProperty { get; set; }
public byte ByteProperty { get; set; }
public short ShortProperty { get; set; }
public ushort UShortProperty { get; set; }
public int IntProperty { get; set; }
public uint UIntProperty { get; set; }
public long LongProperty { get; set; }
public ulong ULongProperty { get; set; }
public SByteEnum SByteEnumProperty { get; set; }
public ByteEnum ByteEnumProperty { get; set; }
public ShortEnum ShortEnumProperty { get; set; }
public UShortEnum UShortEnumProperty { get; set; }
public IntEnum IntEnumProperty { get; set; }
public UIntEnum UIntEnumProperty { get; set; }
public LongEnum LongEnumProperty { get; set; }
public ULongEnum ULongEnumProperty { get; set; }
public char CharProperty { get; set; }
public bool BoolProperty { get; set; }
public float FloatProperty { get; set; }
public double DoubleProperty { get; set; }
public string StringProperty { get; set; }
public Type TypeProperty { get; set; }
public int[] ArrayProperty { get; set; }
public object ObjectProperty { get; set; }
public sbyte SByteField;
public byte ByteField;
public short ShortField;
public ushort UShortField;
public int IntField;
public uint UIntField;
public long LongField;
public ulong ULongField;
public SByteEnum SByteEnumField;
public ByteEnum ByteEnumField;
public ShortEnum ShortEnumField;
public UShortEnum UShortEnumField;
public IntEnum IntEnumField;
public UIntEnum UIntEnumField;
public LongEnum LongEnumField;
public ULongEnum ULongEnumField;
public char CharField;
public bool BoolField;
public float FloatField;
public double DoubleField;
public string StringField;
public Type TypeField;
public int[] ArrayField;
public object ObjectField;
}
public class IndexerAttribute : Attribute
{
public IndexerAttribute() { }
public string this[string s]
{
get { return s; }
set { }
}
}
public enum SByteEnum : sbyte { }
public enum ByteEnum : byte { }
public enum ShortEnum : short { }
public enum UShortEnum : ushort { }
public enum IntEnum : int { }
public enum UIntEnum : uint { }
public enum LongEnum : long { }
public enum ULongEnum : ulong { }
}
| |
using System;
using System.Collections;
using Tutor.Structure;
using Tutor.Patterns;
using Tutor.PatternMatching;
namespace Tutor.Theory
{
/// <summary>
/// Summary description for Polynomial.
/// </summary>
public class PolynomialTerm
{
public long Degree;
public Equation Coef;
}
public class PolynomialTermCompare : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
PolynomialTerm a = (PolynomialTerm)x;
PolynomialTerm b = (PolynomialTerm)y;
if(a.Degree < b.Degree) return 1;
if(a.Degree == b.Degree) return 0;
return -1;
}
#endregion
}
public class Polynomial
{
public Equation X;
public ArrayList _Elements;
public long MaxDegree;
public long MinDegree;
public Polynomial()
{
_Elements = new ArrayList();
MaxDegree = 0;
MinDegree = -1;
}
public void canon()
{
_Elements.Sort(new PolynomialTermCompare());
}
}
public class PolynomialTester
{
public static PolynomialTerm GetTerm(Equation E, EquationPattern [] Bank, Equation X)
{
PolynomialTerm PD = new PolynomialTerm();
PD.Degree = -1;
PD.Coef = null;
MatchEnvironment Gamma = new MatchEnvironment();
Gamma.BindTree(X, "X");
int Which = -1;
for(int k = 0; k < Bank.Length; k++)
{
for(int cy = 0; cy < E.order(); cy++)
{
try
{
Gamma = PatternMatcher.Match(E, Bank[k], Gamma);
Which = k;
k = Bank.Length + 1;
cy = E.order() + 1;
}
catch(NoMatch NM)
{
Object o = NM; o = o;
}
E.cycle();
}
}
if(Which==0)
{
PD.Degree = 0;
PD.Coef = Gamma.FindConstant(1);
}
if(Which==1)
{
PD.Degree = 1;
PD.Coef = Gamma.FindConstant(2);
}
if(Which==2)
{
PD.Degree = 1;
PD.Coef = new EquConstant(1);
}
if(Which==3)
{
PD.Degree = Gamma.FindConstant(1).Value;
PD.Coef = new EquConstant(1);
}
if(Which==4)
{
PD.Degree = Gamma.FindConstant(1).Value;
PD.Coef = Gamma.FindConstant(2);
}
if(Which==5)
{
PD.Degree = Gamma.FindConstant(1).Value;
PD.Coef = new EquDivide(Gamma.FindConstant(2),Gamma.FindConstant(3));
}
if(Which==6)
{
PD.Degree = Gamma.FindConstant(1).Value;
PD.Coef = new EquDivide(Gamma.FindConstant(2),Gamma.FindConstant(3));
}
if(Which==-1)
throw new NoMatch();
return PD;
}
public static Equation FloatGCD(Equation E)
{
if(E is EquAddition)
{
EquAddition Add = (EquAddition) E;
EquAddition Next = new EquAddition();
foreach(Equation T in Add._Terms)
{
Equation R = (new FloatGCD()).TestAndApply(T, null);
if(R == null)
Next._Terms.Add(T);
else
Next._Terms.Add(R);
}
return Next;
}
else
{
Equation R = (new FloatGCD()).TestAndApply(E, null);
if(R != null)
return R;
return E;
}
}
public static ArrayList FindCandidates(Equation E)
{
ArrayList Arr = new ArrayList();
EquationPattern [] _Patterns = new EquationPattern[7];
_Patterns[0] = PatternParser.Parse("(c 1)");
_Patterns[1] = PatternParser.Parse("(* (c 2) X )");
_Patterns[2] = PatternParser.Parse("X ");
_Patterns[3] = PatternParser.Parse("(^ X (c 1))");
_Patterns[4] = PatternParser.Parse("(* (c 2) (^ X (c 1)))");
_Patterns[5] = PatternParser.Parse("(* (/ (c 2) (c 3)) (^ X (c 1)))");
_Patterns[6] = PatternParser.Parse("(/ (* (c 2) (^ X (c 1))) (c 3))");
foreach(Equation T in ((EquAddition) E)._Terms)
{
for(int k = 0; k < _Patterns.Length; k++)
{
try
{
MatchEnvironment Gamma = PatternMatcher.Match(T, _Patterns[k]);
Arr.Add( Gamma.FindTree("X") );
}
catch(NoMatch NM)
{
Object o = NM; o = o;
}
}
}
return Arr;
}
public static Polynomial Test(Equation E)
{
Equation Fixed = FloatGCD(E);
ArrayList Candidates = FindCandidates(Fixed);
foreach(Equation X in Candidates)
{
try
{
Polynomial P = PolynomialTester.Test(Fixed, X);
return P;
}
catch (Tutor.PatternMatching.NoMatch NM)
{
}
}
throw new Tutor.PatternMatching.NoMatch();
}
// public static
public static Polynomial Test(Equation E, Equation X)
{
EquationPattern [] _Patterns = new EquationPattern[7];
_Patterns[0] = PatternParser.Parse("(c 1)");
_Patterns[1] = PatternParser.Parse("(* (c 2) X )");
_Patterns[2] = PatternParser.Parse("X ");
_Patterns[3] = PatternParser.Parse("(^ X (c 1))");
_Patterns[4] = PatternParser.Parse("(* (c 2) (^ X (c 1)))");
_Patterns[5] = PatternParser.Parse("(* (/ (c 2) (c 3)) (^ X (c 1)))");
_Patterns[6] = PatternParser.Parse("(/ (* (c 2) (^ X (c 1))) (c 3))");
Polynomial Polynom = new Polynomial();
Polynom.X = X;
foreach(Equation T in ((EquAddition) E)._Terms)
{
PolynomialTerm PD = GetTerm(T, _Patterns, X);
Polynom._Elements.Add(PD);
if(Polynom.MinDegree<0) Polynom.MinDegree = PD.Degree;
Polynom.MinDegree = PD.Degree < Polynom.MinDegree ? PD.Degree : Polynom.MinDegree;
Polynom.MaxDegree = PD.Degree > Polynom.MaxDegree ? PD.Degree : Polynom.MaxDegree;
}
Polynom.canon();
foreach(PolynomialTerm PT in Polynom._Elements)
{
Console.WriteLine(PT.Coef.str() + "*" + Polynom.X.str() + "^" + PT.Degree);
}
Console.WriteLine("" + Polynom.MinDegree + ":" + Polynom.MaxDegree);
return Polynom;
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, 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.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Collections.Generic;
using System.Diagnostics;
using Xunit;
public class AsyncTargetWrapperTests : NLogTestBase
{
[Fact]
public void AsyncTargetWrapperInitTest()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow);
Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction);
Assert.Equal(300, targetWrapper.QueueLimit);
Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
Assert.Equal(100, targetWrapper.BatchSize);
}
[Fact]
public void AsyncTargetWrapperInitTest2()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper()
{
WrappedTarget = myTarget,
};
Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction);
Assert.Equal(10000, targetWrapper.QueueLimit);
Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
Assert.Equal(100, targetWrapper.BatchSize);
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/1069
/// </summary>
[Fact]
public void AsyncTargetWrapperInitTest_WhenTimeToSleepBetweenBatchesIsEqualToZero_ShouldThrowNLogConfigurationException() {
LogManager.ThrowConfigExceptions = true;
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper() {
WrappedTarget = myTarget,
TimeToSleepBetweenBatches = 0,
};
Assert.Throws<NLogConfigurationException>(() => targetWrapper.Initialize(null));
}
[Fact]
public void AsyncTargetWrapperSyncTest1()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper
{
WrappedTarget = myTarget,
Name = "AsyncTargetWrapperSyncTest1_Wrapper",
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
ManualResetEvent continuationHit = new ManualResetEvent(false);
Thread continuationThread = null;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationThread = Thread.CurrentThread;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
// continuation was not hit
Assert.True(continuationHit.WaitOne(2000));
Assert.NotSame(continuationThread, Thread.CurrentThread);
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotSame(continuationThread, Thread.CurrentThread);
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperAsyncTest1()
{
var myTarget = new MyAsyncTarget();
var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" };
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit.WaitOne());
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperAsyncWithExceptionTest1()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var targetWrapper = new AsyncTargetWrapper(myTarget) {Name = "AsyncTargetWrapperAsyncWithExceptionTest1_Wrapper"};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit.WaitOne());
Assert.NotNull(lastException);
Assert.IsType(typeof(InvalidOperationException), lastException);
// no flush on exception
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
lastException = null;
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType(typeof(InvalidOperationException), lastException);
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperSingleTest()
{
InternalLogger.LogToConsole = true;
InternalLogger.IncludeTimestamp = true;
InternalLogger.LogLevel = LogLevel.Trace;
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
Name = "AsyncTargetWrapperFlushTest_Wrapper",
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 3
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
List<Exception> exceptions = new List<Exception>();
long missingEvents = 1;
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(
ex =>
{
try
{
lock (exceptions)
{
exceptions.Add(ex);
}
Interlocked.Decrement(ref missingEvents);
}
catch (Exception e)
{
InternalLogger.Trace("Error in callback", e);
}
}));
Exception lastException = null;
ManualResetEvent mre = new ManualResetEvent(false);
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.Flush(
cont =>
{
try
{
DateTime start = DateTime.Now;
// We have to spin until all events are done being written by the above code, otherwise on
// slow computers the flush will be called before all events has been pushed to the event queue.
// causing the below assertions to fail.
if (missingEvents > 0)
{
InternalLogger.Trace("Still missing {0} events, exceptions captured:{1}", missingEvents, exceptions.Count);
}
while (missingEvents > 0)
{
InternalLogger.Trace("Still missing {0} events, exceptions captured:{1}", missingEvents, exceptions.Count);
Thread.Sleep(50);
if (DateTime.Now - start > TimeSpan.FromSeconds(2000))
{
Assert.False(true, string.Format("threads did not manage to enqueue their messages within time limit, still missing:{0}events, exceptions captured:{1}", missingEvents, exceptions.Count));
}
}
// by this time all continuations should be completed
Assert.Equal(1, exceptions.Count);
// We have to use interlocked, otherwise there are no guarantee that we get the correct value
// with just 1 flush of the target
int flushCount = Interlocked.CompareExchange(ref myTarget.FlushCount, 0, 1);
Assert.Equal(1, flushCount);
int writeCount = Interlocked.CompareExchange(ref myTarget.WriteCount, 0, 1);
// and all writes should be accounted for
Assert.Equal(1, writeCount);
}
catch (Exception ex)
{
lastException = ex;
}
finally
{
mre.Set();
}
});
Assert.True(mre.WaitOne());
},
LogLevel.Trace);
if (lastException != null)
{
Assert.True(false, lastException.ToString() + "\r\n" + internalLog);
}
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperFlushTest()
{
InternalLogger.LogToConsole = true;
InternalLogger.IncludeTimestamp = true;
InternalLogger.LogLevel = LogLevel.Trace;
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
Name = "AsyncTargetWrapperFlushTest_Wrapper",
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 3
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
List<Exception> exceptions = new List<Exception>();
#if !SILVERLIGHT
int eventCount = Environment.Is64BitProcess ? 5000 : 500;
long missingEvents = Environment.Is64BitProcess ? 5000 : 500;
#else
int eventCount = 500;
long missingEvents = 500;
#endif
for (int i = 0; i < eventCount; ++i)
{
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(
ex =>
{
try
{
lock (exceptions)
{
exceptions.Add(ex);
}
Interlocked.Decrement(ref missingEvents);
}
catch (Exception e)
{
InternalLogger.Trace("Error in callback",e);
}
}));
}
Exception lastException = null;
ManualResetEvent mre = new ManualResetEvent(false);
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.Flush(
cont =>
{
try
{
DateTime start = DateTime.Now;
// We have to spin until all events are done being written by the above code, otherwise on
// slow computers the flush will be called before all events has been pushed to the event queue.
// causing the below assertions to fail.
if (missingEvents > 0)
{
InternalLogger.Trace("Still missing {0} events, exceptions captured:{1}", missingEvents, exceptions.Count);
}
while (missingEvents > 0)
{
InternalLogger.Trace("Still missing {0} events, exceptions captured:{1}", missingEvents, exceptions.Count);
Thread.Sleep(50);
if (DateTime.Now - start > TimeSpan.FromSeconds(20))
{
Assert.False( true,string.Format("threads did not manage to enqueue their messages within time limit, still missing:{0}events, exceptions captured:{1}", missingEvents, exceptions.Count));
}
}
// by this time all continuations should be completed
Assert.Equal(eventCount, exceptions.Count);
// We have to use interlocked, otherwise there are no guarantee that we get the correct value
// with just 1 flush of the target
int flushCount = Interlocked.CompareExchange(ref myTarget.FlushCount, 0, 1);
Assert.Equal(1, flushCount);
int writeCount = Interlocked.CompareExchange(ref myTarget.WriteCount, 0, eventCount);
// and all writes should be accounted for
Assert.Equal(eventCount, writeCount);
}
catch (Exception ex)
{
lastException = ex;
}
finally
{
mre.Set();
}
});
Assert.True(mre.WaitOne());
},
LogLevel.Trace);
if (lastException != null)
{
Assert.True(false, lastException.ToString() + "\r\n" + internalLog);
}
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperCloseTest()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 1000,
Name = "AsyncTargetWrapperCloseTest_Wrapper",
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
// quickly close the target before the timer elapses
targetWrapper.Close();
}
[Fact]
public void AsyncTargetWrapperExceptionTest()
{
var targetWrapper = new AsyncTargetWrapper
{
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 500,
WrappedTarget = new DebugTarget(),
Name = "AsyncTargetWrapperExceptionTest_Wrapper"
};
LogManager.ThrowExceptions = false;
targetWrapper.Initialize(null);
// null out wrapped target - will cause exception on the timer thread
targetWrapper.WrappedTarget = null;
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
targetWrapper.Close();
},
LogLevel.Trace);
Assert.True(internalLog.Contains("AsyncWrapper 'AsyncTargetWrapperExceptionTest_Wrapper': WrappedTarget is NULL"), internalLog);
}
[Fact]
public void FlushingMultipleTimesSimultaneous()
{
var asyncTarget = new AsyncTargetWrapper
{
TimeToSleepBetweenBatches = 2000,
WrappedTarget = new DebugTarget(),
Name = "FlushingMultipleTimesSimultaneous_Wrapper"
};
asyncTarget.Initialize(null);
try
{
asyncTarget.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
var firstContinuationCalled = false;
var secondContinuationCalled = false;
var firstContinuationResetEvent = new ManualResetEvent(false);
var secondContinuationResetEvent = new ManualResetEvent(false);
asyncTarget.Flush(ex =>
{
firstContinuationCalled = true;
firstContinuationResetEvent.Set();
});
asyncTarget.Flush(ex =>
{
secondContinuationCalled = true;
secondContinuationResetEvent.Set();
});
firstContinuationResetEvent.WaitOne();
secondContinuationResetEvent.WaitOne();
Assert.True(firstContinuationCalled);
Assert.True(secondContinuationCalled);
}
finally
{
asyncTarget.Close();
}
}
class MyAsyncTarget : Target
{
public int FlushCount;
public int WriteCount;
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
// This assertion is flawed.
// If threads run slow, then AsyncTargetWrapper will flush multiple times.
// We cannot expect FlushCount to be lower than WriteCount, since Flush run on a timer thread, whereas
// Write run on a threadpool thread.
//Assert.True(this.FlushCount <= this.WriteCount);
Interlocked.Increment(ref this.WriteCount);
if (this.WriteCount % 100 == 0)
{
InternalLogger.Trace("{0} - Writen 100", DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss.ffff"));
}
ThreadPool.QueueUserWorkItem(
s =>
{
try
{
if (this.ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
}
catch (Exception e)
{
InternalLogger.Trace("Unexopected Exception", e);
logEvent.Continuation(e);
}
});
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
Interlocked.Increment(ref this.FlushCount);
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
class MyTarget : Target
{
public int FlushCount { get; set; }
public int WriteCount { get; set; }
protected override void Write(LogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
this.WriteCount++;
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
asyncContinuation(null);
}
}
}
}
| |
using GLTF;
using GLTF.Schema;
using GLTF.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace GLTF
{
// Static class for construction GLB objects. These API's only work with the .NET 4.6 runtime and above.
public static class GLBBuilder
{
/// <summary>
/// Turns a glTF file w/ structure into a GLB. Does not currently copy binary data
/// </summary>
/// <param name="root">The glTF root to turn into a GLBObject</param>
/// <param name="glbOutStream">Output stream to write the GLB to</param>
/// <param name="loader">Loader for loading external components from GLTFRoot. The loader will receive uris and return the stream to the resource</param>
/// <returns>A constructed GLBObject</returns>
private static GLBObject ConstructFromGLTF(GLTFRoot root, Stream glbOutStream, Func<string, Stream> loader)
{
if (root == null) throw new ArgumentNullException(nameof(root));
if (glbOutStream == null) throw new ArgumentNullException(nameof(glbOutStream));
MemoryStream gltfJsonStream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(gltfJsonStream))
{
root.Serialize(sw, true);
sw.Flush();
long proposedLength = gltfJsonStream.Length + GLTFParser.HEADER_SIZE + GLTFParser.CHUNK_HEADER_SIZE;
if (gltfJsonStream.Length > uint.MaxValue)
{
throw new ArgumentException("Serialized root cannot exceed uint.maxvalue", nameof(root));
}
uint proposedLengthAsUint = (uint)proposedLength;
glbOutStream.SetLength(proposedLengthAsUint);
GLBObject glbObject = new GLBObject
{
Header = new GLBHeader
{
FileLength = proposedLengthAsUint,
Version = 2
},
Root = root,
Stream = glbOutStream,
JsonChunkInfo = new ChunkInfo
{
Length = (uint)gltfJsonStream.Length,
StartPosition = GLTFParser.HEADER_SIZE,
Type = ChunkFormat.JSON
}
};
// write header
WriteHeader(glbOutStream, glbObject.Header, glbObject.StreamStartPosition);
// write chunk header
WriteChunkHeader(glbOutStream, glbObject.JsonChunkInfo);
gltfJsonStream.Position = 0;
gltfJsonStream.CopyTo(glbOutStream);
// todo: implement getting binary data for loader
return glbObject;
}
}
/// <summary>
/// Turns the GLB data contained in a stream into a GLBObject. Will copy to the outStream if specified
/// </summary>
/// <param name="root">The glTF root to turn into a GLBObject</param>
/// <param name="inputGLBStream">The stream the glb came in</param>
/// <param name="outStream">If outstream is specified, the glb gets copied to it</param>
/// <param name="inputGLBStreamStartPosition">Offset into the buffer that the GLB starts</param>
/// <returns>A constructed GLBObject</returns>
public static GLBObject ConstructFromGLB(GLTFRoot root, Stream inputGLBStream, Stream outStream = null,
long inputGLBStreamStartPosition = 0)
{
if (outStream != null)
{
inputGLBStream.Position = inputGLBStreamStartPosition;
inputGLBStream.CopyTo(outStream);
}
else
{
outStream = inputGLBStream;
}
// header information is 4 bytes in, past the magic number
inputGLBStream.Position = 4 + inputGLBStreamStartPosition;
GLBHeader header = GLTFParser.ParseGLBHeader(inputGLBStream);
inputGLBStream.Position = GLTFParser.HEADER_SIZE + inputGLBStreamStartPosition;
List<ChunkInfo> allChunks = GLTFParser.FindChunks(inputGLBStream);
ChunkInfo jsonChunkInfo = new ChunkInfo
{
Type = ChunkFormat.JSON
};
ChunkInfo binaryChunkInfo = new ChunkInfo
{
Type = ChunkFormat.BIN
};
foreach (ChunkInfo chunkInfo in allChunks)
{
switch (chunkInfo.Type)
{
case ChunkFormat.JSON:
jsonChunkInfo = chunkInfo;
break;
case ChunkFormat.BIN:
binaryChunkInfo = chunkInfo;
break;
}
}
if (jsonChunkInfo.Length == 0)
{
throw new ArgumentException("JSON chunk must exists for valid GLB", nameof(inputGLBStream));
}
// todo: compute the initial bufferview list
return new GLBObject
{
Root = root,
Stream = outStream,
StreamStartPosition = inputGLBStreamStartPosition,
Header = header,
JsonChunkInfo = jsonChunkInfo,
BinaryChunkInfo = binaryChunkInfo
};
}
/// <summary>
/// Turns a stream that contains glTF or a GLB data into a GLBObject. glTF is not yet supported
/// </summary>
/// <param name="inStream">The stream to turn into a GLB</param>
/// <param name="glbOutStream">If specified, output stream to write the GLB to</param>
/// <param name="loader">Loader for loading external components from GLTFRoot. Loader is required if loading from glTF</param>
/// <returns>A constructed GLBObject</returns>
public static GLBObject ConstructFromStream(Stream inStream, Stream glbOutStream = null, Func<string, Stream> loader = null,
long streamStartPosition = 0, bool removeUndefinedReferences = true)
{
if (inStream == null) throw new ArgumentNullException(nameof(inStream));
if (inStream.Length > 0)
{
inStream.Position = streamStartPosition;
GLTFRoot root;
GLTFParser.ParseJson(inStream, out root, streamStartPosition);
if (removeUndefinedReferences)
{
GLTFHelpers.RemoveUndefinedReferences(root);
}
if (!root.IsGLB)
{
return ConstructFromGLTF(root, glbOutStream, loader);
}
return ConstructFromGLB(root, inStream, glbOutStream, streamStartPosition);
}
return _ConstructFromEmptyStream(inStream, streamStartPosition);
}
private static GLBObject _ConstructFromEmptyStream(Stream inStream, long streamStartPosition)
{
GLBObject glbObject = new GLBObject
{
Stream = inStream,
JsonChunkInfo = new ChunkInfo
{
Length = 0,
StartPosition = GLTFParser.HEADER_SIZE,
Type = ChunkFormat.JSON
},
BinaryChunkInfo = new ChunkInfo
{
Length = 0,
StartPosition = GLTFParser.HEADER_SIZE + GLTFParser.CHUNK_HEADER_SIZE,
Type = ChunkFormat.BIN
},
Header = new GLBHeader
{
FileLength = GLTFParser.HEADER_SIZE,
Version = 2
},
StreamStartPosition = streamStartPosition
};
return glbObject;
}
/// <summary>
/// Saves out the GLBObject to its own stream
/// The GLBObject stream will be updated to be the output stream. Callers are reponsible for handling Stream lifetime
/// </summary>
/// <param name="glb">The GLB to flush to the output stream and update</param>
/// <param name="newRoot">Optional root to replace the one in the glb</param>
/// <returns>A GLBObject that is based upon outStream</returns>
public static void UpdateStream(GLBObject glb)
{
if (glb.Root == null) throw new ArgumentException("glb Root and newRoot cannot be null", nameof(glb.Root));
if (glb.Stream == null) throw new ArgumentException("glb GLBStream property cannot be null", nameof(glb.Stream));
MemoryStream gltfJsonStream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(gltfJsonStream))
{
glb.Root.Serialize(sw, true); // todo: this could out of memory exception
sw.Flush();
if (gltfJsonStream.Length > int.MaxValue)
{
// todo: make this a non generic exception
throw new Exception("JSON chunk of GLB has exceeded maximum allowed size (4 GB)");
}
// realloc of out of space
if (glb.JsonChunkInfo.Length < gltfJsonStream.Length)
{
uint proposedJsonChunkLength = (uint)System.Math.Min((long)gltfJsonStream.Length * 2, uint.MaxValue); // allocate double what is required
proposedJsonChunkLength = CalculateAlignment(proposedJsonChunkLength, 4);
// chunks must be 4 byte aligned
uint amountToAddToFile = proposedJsonChunkLength - glb.JsonChunkInfo.Length;
// we have not yet initialized a json chunk before
if (glb.JsonChunkInfo.Length == 0)
{
amountToAddToFile += GLTFParser.CHUNK_HEADER_SIZE;
glb.SetJsonChunkStartPosition(GLTFParser.HEADER_SIZE);
}
// new proposed length = propsoedJsonBufferSize - currentJsonBufferSize + totalFileLength
long proposedLength = amountToAddToFile + glb.Header.FileLength;
if (proposedLength > uint.MaxValue)
{
throw new Exception("GLB has exceeded max allowed size (4 GB)");
}
uint proposedLengthAsUint = (uint)proposedLength;
try
{
glb.Stream.SetLength(proposedLength);
}
catch (IOException e)
{
#if WINDOWS_UWP
Debug.WriteLine(e);
#else
Console.WriteLine(e);
#endif
throw;
}
long newBinaryChunkStartPosition =
GLTFParser.HEADER_SIZE + GLTFParser.CHUNK_HEADER_SIZE + proposedJsonChunkLength;
glb.Stream.Position = glb.BinaryChunkInfo.StartPosition;
glb.SetBinaryChunkStartPosition(newBinaryChunkStartPosition);
if (glb.BinaryChunkInfo.Length > 0)
{
uint lengthToCopy = glb.BinaryChunkInfo.Length + GLTFParser.CHUNK_HEADER_SIZE;
// todo: we need to be able to copy while doing it with smaller buffers. Also int is smaller than uint, so this is not standards compliant.
glb.Stream.CopyToSelf((int)newBinaryChunkStartPosition,
lengthToCopy);
}
// write out new GLB length
glb.SetFileLength(proposedLengthAsUint);
WriteHeader(glb.Stream, glb.Header, glb.StreamStartPosition);
// write out new JSON header
glb.SetJsonChunkLength(proposedJsonChunkLength);
WriteChunkHeader(glb.Stream, glb.JsonChunkInfo);
}
// clear the buffer
glb.Stream.Position = glb.JsonChunkInfo.StartPosition + GLTFParser.CHUNK_HEADER_SIZE;
uint amountToCopy = glb.JsonChunkInfo.Length;
while (amountToCopy != 0)
{
int currAmountToCopy = (int)System.Math.Min(amountToCopy, int.MaxValue);
byte[] filler =
Encoding.ASCII.GetBytes(new string(' ', currAmountToCopy));
glb.Stream.Write(filler, 0, filler.Length);
amountToCopy -= (uint)currAmountToCopy;
}
// write new JSON data
gltfJsonStream.Position = 0;
glb.Stream.Position = glb.JsonChunkInfo.StartPosition + GLTFParser.CHUNK_HEADER_SIZE;
gltfJsonStream.CopyTo(glb.Stream);
glb.Stream.Flush();
}
}
/// <summary>
/// Adds binary data to the GLB
/// </summary>
/// <param name="glb">The glb to update</param>
/// <param name="binaryData">The binary data to append</param>
/// <param name="createBufferView">Whether a buffer view should be created, added to the GLTFRoot, and id returned</param>
/// <param name="streamStartPosition">Start position of stream</param>
/// <param name="bufferViewName">Root to replace the current one with</param>
/// <returns>The location of the added buffer view</returns>
public static BufferViewId AddBinaryData(GLBObject glb, Stream binaryData, bool createBufferView = true, long streamStartPosition = 0, string bufferViewName = null)
{
if (glb == null) throw new ArgumentNullException(nameof(glb));
if(glb.Root == null && bufferViewName == null) throw new ArgumentException("glb Root and new root cannot be null", nameof(glb));
if(glb.Stream == null) throw new ArgumentException("glb Stream cannot be null", nameof(glb));
if(binaryData == null) throw new ArgumentNullException(nameof(binaryData));
if(binaryData.Length > uint.MaxValue) throw new ArgumentException("Stream cannot be larger than uint.MaxValue", nameof(binaryData));
return _AddBinaryData(glb, binaryData, createBufferView, streamStartPosition, bufferViewName);
}
private static BufferViewId _AddBinaryData(GLBObject glb, Stream binaryData, bool createBufferView, long streamStartPosition, string bufferViewName = null)
{
binaryData.Position = streamStartPosition;
// Append new binary chunk to end
uint blobLengthAsUInt = CalculateAlignment((uint)(binaryData.Length - streamStartPosition), 4);
uint newBinaryBufferSize = glb.BinaryChunkInfo.Length + blobLengthAsUInt;
uint newGLBSize = glb.Header.FileLength + blobLengthAsUInt;
uint blobWritePosition = glb.Header.FileLength;
// there was an existing file that had no binary chunk info previously
if (glb.BinaryChunkInfo.Length == 0)
{
newGLBSize += GLTFParser.CHUNK_HEADER_SIZE;
blobWritePosition += GLTFParser.CHUNK_HEADER_SIZE;
glb.SetBinaryChunkStartPosition(glb.Header.FileLength); // if 0, then appends chunk info at the end
}
glb.Stream.SetLength(glb.Header.FileLength + blobLengthAsUInt);
glb.Stream.Position = blobWritePosition; // assuming the end of the file is the end of the binary chunk
binaryData.CopyTo(glb.Stream); // make sure this doesn't supersize it
glb.SetFileLength(newGLBSize);
glb.SetBinaryChunkLength(newBinaryBufferSize);
// write glb header past magic number
WriteHeader(glb.Stream, glb.Header, glb.StreamStartPosition);
WriteChunkHeader(glb.Stream, glb.BinaryChunkInfo);
if (createBufferView)
{
// Add a new BufferView to the GLTFRoot
BufferView bufferView = new BufferView
{
Buffer = new BufferId
{
Id = 0,
Root = glb.Root
},
ByteLength = blobLengthAsUInt, // figure out whether glb size is wrong or if documentation is unclear
ByteOffset = glb.BinaryChunkInfo.Length - blobLengthAsUInt,
Name = bufferViewName
};
if (glb.Root.BufferViews == null)
{
glb.Root.BufferViews = new List<BufferView>();
}
glb.Root.BufferViews.Add(bufferView);
return new BufferViewId
{
Id = glb.Root.BufferViews.Count - 1,
Root = glb.Root
};
}
return null;
}
/// <summary>
/// Merges two glb files together
/// </summary>
/// <param name="mergeTo">The glb to update</param>
/// <param name="mergeFrom">The glb to merge from</param>
public static void MergeGLBs(GLBObject mergeTo, GLBObject mergeFrom)
{
if (mergeTo == null) throw new ArgumentNullException(nameof(mergeTo));
if (mergeFrom == null) throw new ArgumentNullException(nameof(mergeFrom));
// 1) merge json
// 2) copy mergefrom binary data to mergeto binary data
// 3) Fix up bufferviews to be the new offset
int previousBufferViewsCount = mergeTo.Root.BufferViews?.Count ?? 0;
uint previousBufferSize = mergeTo.BinaryChunkInfo.Length;
GLTFHelpers.MergeGLTF(mergeTo.Root, mergeFrom.Root);
_AddBinaryData(mergeTo, mergeFrom.Stream, false, mergeFrom.BinaryChunkInfo.StartPosition + GLTFParser.CHUNK_HEADER_SIZE);
uint bufferSizeDiff =
mergeTo.BinaryChunkInfo.Length -
previousBufferSize; // calculate buffer size change to update the byte offsets of the appended buffer views
if (mergeTo.Root.BufferViews != null)
{
for (int i = previousBufferViewsCount; i < mergeTo.Root.BufferViews.Count; ++i)
{
mergeTo.Root.BufferViews[i].ByteOffset += bufferSizeDiff;
}
}
}
/// <summary>
/// Removes a blob from the GLB at the given BufferView
/// Updates accessors and images to have correct new bufferview index
/// This function can invalidate BufferViewId's returned by previous function
/// </summary>
/// <param name="glb">The glb to remove from</param>
/// <param name="bufferViewId">The buffer to remove</param>
public static void RemoveBinaryData(GLBObject glb, BufferViewId bufferViewId)
{
if (glb == null) throw new ArgumentNullException(nameof(glb));
if (bufferViewId == null) throw new ArgumentNullException(nameof(bufferViewId));
BufferView bufferViewToRemove = bufferViewId.Value;
int id = bufferViewId.Id;
if (bufferViewToRemove.ByteOffset + bufferViewToRemove.ByteLength == glb.BinaryChunkInfo.Length)
{
uint bufferViewLengthAsUint = bufferViewToRemove.ByteLength;
glb.SetFileLength(glb.Header.FileLength - bufferViewLengthAsUint);
glb.SetBinaryChunkLength(glb.BinaryChunkInfo.Length - bufferViewLengthAsUint);
if (glb.BinaryChunkInfo.Length == 0)
{
glb.Root.Buffers.RemoveAt(0);
foreach (BufferView bufferView in glb.Root.BufferViews) // other buffers may still exist, and their index has now changed
{
--bufferView.Buffer.Id;
}
glb.SetFileLength(glb.Header.FileLength - GLTFParser.CHUNK_HEADER_SIZE);
}
else
{
glb.Root.Buffers[0].ByteLength = glb.BinaryChunkInfo.Length;
// write binary chunk header
WriteChunkHeader(glb.Stream, glb.BinaryChunkInfo);
}
// trim the end
glb.Stream.SetLength(glb.Header.FileLength);
// write glb header
WriteHeader(glb.Stream, glb.Header, glb.StreamStartPosition);
}
glb.Root.BufferViews.RemoveAt(id);
if (glb.Root.Accessors != null)
{
foreach (Accessor accessor in glb.Root.Accessors) // shift over all accessors
{
if (accessor.BufferView != null && accessor.BufferView.Id >= id)
{
--accessor.BufferView.Id;
}
if (accessor.Sparse != null)
{
if (accessor.Sparse.Indices?.BufferView.Id >= id)
{
--accessor.Sparse.Indices.BufferView.Id;
}
if (accessor.Sparse.Values?.BufferView.Id >= id)
{
--accessor.Sparse.Values.BufferView.Id;
}
}
}
}
if (glb.Root.Images != null)
{
foreach (GLTFImage image in glb.Root.Images)
{
if (image.BufferView != null && image.BufferView.Id >= id)
{
--image.BufferView.Id;
}
}
}
}
/// <summary>
/// Added function to set the root
/// </summary>
/// <param name="glb">GLB to add</param>
/// <param name="newRoot">The new root to update it with</param>
public static void SetRoot(GLBObject glb, GLTFRoot newRoot)
{
if (newRoot != null)
{
glb.Root = newRoot;
}
}
private static void WriteHeader(Stream stream, GLBHeader header, long streamStartPosition)
{
stream.Position = streamStartPosition;
byte[] magicNumber = BitConverter.GetBytes(GLTFParser.MAGIC_NUMBER);
byte[] version = BitConverter.GetBytes(header.Version);
byte[] length = BitConverter.GetBytes(header.FileLength);
stream.Write(magicNumber, 0, magicNumber.Length);
stream.Write(version, 0, version.Length);
stream.Write(length, 0, length.Length);
}
private static void WriteChunkHeader(Stream stream, ChunkInfo chunkInfo)
{
stream.Position = chunkInfo.StartPosition;
byte[] lengthBytes = BitConverter.GetBytes(chunkInfo.Length);
byte[] typeBytes = BitConverter.GetBytes((uint)chunkInfo.Type);
stream.Write(lengthBytes, 0, lengthBytes.Length);
stream.Write(typeBytes, 0, lengthBytes.Length);
}
public static uint CalculateAlignment(uint currentSize, uint byteAlignment)
{
return (currentSize + byteAlignment - 1) / byteAlignment * byteAlignment;
}
}
}
| |
// 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;
using System.Reactive;
using System.Reactive.Subjects;
using Moq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Layout;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class WindowBaseTests
{
[Fact]
public void Impl_ClientSize_Should_Be_Set_After_Layout_Pass()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = Mock.Of<IWindowBaseImpl>(x => x.Scaling == 1);
Mock.Get(impl).Setup(x => x.Resize(It.IsAny<Size>())).Callback(() => { });
var target = new TestWindowBase(impl)
{
Template = CreateTemplate(),
Content = new TextBlock
{
Width = 321,
Height = 432,
},
IsVisible = true,
};
target.LayoutManager.ExecuteInitialLayoutPass(target);
Mock.Get(impl).Verify(x => x.Resize(new Size(321, 432)));
}
}
[Fact]
public void Activate_Should_Call_Impl_Activate()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<IWindowBaseImpl>();
var target = new TestWindowBase(impl.Object);
target.Activate();
impl.Verify(x => x.Activate());
}
}
[Fact]
public void Impl_Activate_Should_Call_Raise_Activated_Event()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<IWindowBaseImpl>();
impl.SetupAllProperties();
bool raised = false;
var target = new TestWindowBase(impl.Object);
target.Activated += (s, e) => raised = true;
impl.Object.Activated();
Assert.True(raised);
}
}
[Fact]
public void Impl_Deactivate_Should_Call_Raise_Deativated_Event()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var impl = new Mock<IWindowBaseImpl>();
impl.SetupAllProperties();
bool raised = false;
var target = new TestWindowBase(impl.Object);
target.Deactivated += (s, e) => raised = true;
impl.Object.Deactivated();
Assert.True(raised);
}
}
[Fact]
public void IsVisible_Should_Initially_Be_False()
{
using (UnitTestApplication.Start(TestServices.MockWindowingPlatform))
{
var target = new TestWindowBase();
Assert.False(target.IsVisible);
}
}
[Fact]
public void IsVisible_Should_Be_True_After_Show()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var target = new TestWindowBase();
target.Show();
Assert.True(target.IsVisible);
}
}
[Fact]
public void IsVisible_Should_Be_False_Atfer_Hide()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var target = new TestWindowBase();
target.Show();
target.Hide();
Assert.False(target.IsVisible);
}
}
[Fact]
public void IsVisible_Should_Be_False_Atfer_Impl_Signals_Close()
{
var windowImpl = new Mock<IPopupImpl>();
windowImpl.Setup(x => x.Scaling).Returns(1);
windowImpl.SetupProperty(x => x.Closed);
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var target = new TestWindowBase(windowImpl.Object);
target.Show();
windowImpl.Object.Closed();
Assert.False(target.IsVisible);
}
}
[Fact]
public void Setting_IsVisible_True_Shows_Window()
{
var windowImpl = new Mock<IPopupImpl>();
windowImpl.Setup(x => x.Scaling).Returns(1);
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var target = new TestWindowBase(windowImpl.Object);
target.IsVisible = true;
windowImpl.Verify(x => x.Show());
}
}
[Fact]
public void Setting_IsVisible_False_Hides_Window()
{
var windowImpl = new Mock<IPopupImpl>();
windowImpl.Setup(x => x.Scaling).Returns(1);
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var target = new TestWindowBase(windowImpl.Object);
target.Show();
target.IsVisible = false;
windowImpl.Verify(x => x.Hide());
}
}
[Fact]
public void Showing_Should_Start_Renderer()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var renderer = new Mock<IRenderer>();
var target = new TestWindowBase(renderer.Object);
target.Show();
renderer.Verify(x => x.Start(), Times.Once);
}
}
[Fact]
public void Hiding_Should_Stop_Renderer()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var renderer = new Mock<IRenderer>();
var target = new TestWindowBase(renderer.Object);
target.Show();
target.Hide();
renderer.Verify(x => x.Stop(), Times.Once);
}
}
[Fact]
public void Renderer_Should_Be_Disposed_When_Impl_Signals_Close()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var renderer = new Mock<IRenderer>();
var windowImpl = new Mock<IPopupImpl>();
windowImpl.Setup(x => x.Scaling).Returns(1);
windowImpl.SetupProperty(x => x.Closed);
windowImpl.Setup(x => x.CreateRenderer(It.IsAny<IRenderRoot>())).Returns(renderer.Object);
var target = new TestWindowBase(windowImpl.Object);
target.Show();
windowImpl.Object.Closed();
renderer.Verify(x => x.Dispose(), Times.Once);
}
}
private FuncControlTemplate<TestWindowBase> CreateTemplate()
{
return new FuncControlTemplate<TestWindowBase>(x =>
new ContentPresenter
{
Name = "PART_ContentPresenter",
[!ContentPresenter.ContentProperty] = x[!ContentControl.ContentProperty],
});
}
private class TestWindowBase : WindowBase
{
public bool IsClosed { get; private set; }
public TestWindowBase(IRenderer renderer = null)
: base(Mock.Of<IWindowBaseImpl>(x =>
x.Scaling == 1 &&
x.CreateRenderer(It.IsAny<IRenderRoot>()) == renderer))
{
}
public TestWindowBase(IWindowBaseImpl impl)
: base(impl)
{
}
protected override void HandleApplicationExiting()
{
base.HandleApplicationExiting();
IsClosed = true;
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
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 UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
/// <summary>
/// Add OVROverlay script to an object with an optional mesh primitive
/// rendered as a TimeWarp overlay instead by drawing it into the eye buffer.
/// This will take full advantage of the display resolution and avoid double
/// resampling of the texture.
///
/// We support 3 types of Overlay shapes right now
/// 1. Quad : This is most common overlay type , you render a quad in Timewarp space.
/// 2. Cylinder: [Mobile Only][Experimental], Display overlay as partial surface of a cylinder
/// * The cylinder's center will be your game object's center
/// * We encoded the cylinder's parameters in transform.scale,
/// **[scale.z] is the radius of the cylinder
/// **[scale.y] is the height of the cylinder
/// **[scale.x] is the length of the arc of cylinder
/// * Limitations
/// **Only the half of the cylinder can be displayed, which means the arc angle has to be smaller than 180 degree, [scale.x] / [scale.z] <= PI
/// **Your camera has to be inside of the inscribed sphere of the cylinder, the overlay will be faded out automatically when the camera is close to the inscribed sphere's surface.
/// **Translation only works correctly with vrDriver 1.04 or above
/// 3. Cubemap: Display overlay as a cube map
/// 4. OffcenterCubemap: [Mobile Only] Display overlay as a cube map with a texture coordinate offset
/// * The actually sampling will looks like [color = texture(cubeLayerSampler, normalize(direction) + offset)] instead of [color = texture( cubeLayerSampler, direction )]
/// * The extra center offset can be feed from transform.position
/// * Note: if transform.position's magnitude is greater than 1, which will cause some cube map pixel always invisible
/// Which is usually not what people wanted, we don't kill the ability for developer to do so here, but will warn out.
/// 5. Equirect: Display overlay as a 360-degree equirectangular skybox.
/// </summary>
public class OVROverlay : MonoBehaviour
{
#region Interface
/// <summary>
/// Determines the on-screen appearance of a layer.
/// </summary>
public enum OverlayShape
{
Quad = OVRPlugin.OverlayShape.Quad,
Cylinder = OVRPlugin.OverlayShape.Cylinder,
Cubemap = OVRPlugin.OverlayShape.Cubemap,
OffcenterCubemap = OVRPlugin.OverlayShape.OffcenterCubemap,
Equirect = OVRPlugin.OverlayShape.Equirect,
}
/// <summary>
/// Whether the layer appears behind or infront of other content in the scene.
/// </summary>
public enum OverlayType
{
None,
Underlay,
Overlay,
};
/// <summary>
/// Specify overlay's type
/// </summary>
[Tooltip("Specify overlay's type")]
public OverlayType currentOverlayType = OverlayType.Overlay;
/// <summary>
/// If true, the texture's content is copied to the compositor each frame.
/// </summary>
[Tooltip("If true, the texture's content is copied to the compositor each frame.")]
public bool isDynamic = false;
/// <summary>
/// If true, the layer would be used to present protected content (e.g. HDCP). The flag is effective only on PC.
/// </summary>
[Tooltip("If true, the layer would be used to present protected content (e.g. HDCP). The flag is effective only on PC.")]
public bool isProtectedContent = false;
/// <summary>
/// If true, the layer will be created as an external surface. externalSurfaceObject contains the Surface object. It's effective only on Android.
/// </summary>
[Tooltip("If true, the layer will be created as an external surface. externalSurfaceObject contains the Surface object. It's effective only on Android.")]
public bool isExternalSurface = false;
/// <summary>
/// The width which will be used to create the external surface. It's effective only on Android.
/// </summary>
[Tooltip("The width which will be used to create the external surface. It's effective only on Android.")]
public int externalSurfaceWidth = 0;
/// <summary>
/// The height which will be used to create the external surface. It's effective only on Android.
/// </summary>
[Tooltip("The height which will be used to create the external surface. It's effective only on Android.")]
public int externalSurfaceHeight = 0;
/// <summary>
/// The compositionDepth defines the order of the OVROverlays in composition. The overlay/underlay with smaller compositionDepth would be composited in the front of the overlay/underlay with larger compositionDepth.
/// </summary>
[Tooltip("The compositionDepth defines the order of the OVROverlays in composition. The overlay/underlay with smaller compositionDepth would be composited in the front of the overlay/underlay with larger compositionDepth.")]
public int compositionDepth = 0;
/// <summary>
/// Specify overlay's shape
/// </summary>
[Tooltip("Specify overlay's shape")]
public OverlayShape currentOverlayShape = OverlayShape.Quad;
private OverlayShape prevOverlayShape = OverlayShape.Quad;
/// <summary>
/// The left- and right-eye Textures to show in the layer.
/// \note If you need to change the texture on a per-frame basis, please use OverrideOverlayTextureInfo(..) to avoid caching issues.
/// </summary>
[Tooltip("The left- and right-eye Textures to show in the layer.")]
public Texture[] textures = new Texture[] { null, null };
protected IntPtr[] texturePtrs = new IntPtr[] { IntPtr.Zero, IntPtr.Zero };
/// <summary>
/// The Surface object (Android only).
/// </summary>
public System.IntPtr externalSurfaceObject;
public delegate void ExternalSurfaceObjectCreated();
/// <summary>
/// Will be triggered after externalSurfaceTextueObject get created.
/// </summary>
public ExternalSurfaceObjectCreated externalSurfaceObjectCreated;
/// <summary>
/// Use this function to set texture and texNativePtr when app is running
/// GetNativeTexturePtr is a slow behavior, the value should be pre-cached
/// </summary>
#if UNITY_2017_2_OR_NEWER
public void OverrideOverlayTextureInfo(Texture srcTexture, IntPtr nativePtr, UnityEngine.XR.XRNode node)
#else
public void OverrideOverlayTextureInfo(Texture srcTexture, IntPtr nativePtr, UnityEngine.VR.VRNode node)
#endif
{
#if UNITY_2017_2_OR_NEWER
int index = (node == UnityEngine.XR.XRNode.RightEye) ? 1 : 0;
#else
int index = (node == UnityEngine.VR.VRNode.RightEye) ? 1 : 0;
#endif
if (textures.Length <= index)
return;
textures[index] = srcTexture;
texturePtrs[index] = nativePtr;
isOverridePending = true;
}
protected bool isOverridePending;
internal const int maxInstances = 15;
internal static OVROverlay[] instances = new OVROverlay[maxInstances];
#endregion
private static Material tex2DMaterial;
private static Material cubeMaterial;
private OVRPlugin.LayerLayout layout {
get {
#if UNITY_ANDROID && !UNITY_EDITOR
if (textures.Length == 2 && textures[1] != null)
return OVRPlugin.LayerLayout.Stereo;
#endif
return OVRPlugin.LayerLayout.Mono;
}
}
private struct LayerTexture {
public Texture appTexture;
public IntPtr appTexturePtr;
public Texture[] swapChain;
public IntPtr[] swapChainPtr;
};
private LayerTexture[] layerTextures;
private OVRPlugin.LayerDesc layerDesc;
private int stageCount = -1;
private int layerIndex = -1; // Controls the composition order based on wake-up time.
private int layerId = 0; // The layer's internal handle in the compositor.
private GCHandle layerIdHandle;
private IntPtr layerIdPtr = IntPtr.Zero;
private int frameIndex = 0;
private int prevFrameIndex = -1;
private Renderer rend;
private int texturesPerStage { get { return (layout == OVRPlugin.LayerLayout.Stereo) ? 2 : 1; } }
private bool CreateLayer(int mipLevels, int sampleCount, OVRPlugin.EyeTextureFormat etFormat, int flags, OVRPlugin.Sizei size, OVRPlugin.OverlayShape shape)
{
if (!layerIdHandle.IsAllocated || layerIdPtr == IntPtr.Zero)
{
layerIdHandle = GCHandle.Alloc(layerId, GCHandleType.Pinned);
layerIdPtr = layerIdHandle.AddrOfPinnedObject();
}
if (layerIndex == -1)
{
for (int i = 0; i < maxInstances; ++i)
{
if (instances[i] == null || instances[i] == this)
{
layerIndex = i;
instances[i] = this;
break;
}
}
}
bool needsSetup = (
isOverridePending ||
layerDesc.MipLevels != mipLevels ||
layerDesc.SampleCount != sampleCount ||
layerDesc.Format != etFormat ||
layerDesc.Layout != layout ||
layerDesc.LayerFlags != flags ||
!layerDesc.TextureSize.Equals(size) ||
layerDesc.Shape != shape);
if (!needsSetup)
return false;
OVRPlugin.LayerDesc desc = OVRPlugin.CalculateLayerDesc(shape, layout, size, mipLevels, sampleCount, etFormat, flags);
OVRPlugin.EnqueueSetupLayer(desc, compositionDepth, layerIdPtr);
layerId = (int)layerIdHandle.Target;
if (layerId > 0)
{
layerDesc = desc;
if (isExternalSurface)
{
stageCount = 1;
}
else
{
stageCount = OVRPlugin.GetLayerTextureStageCount(layerId);
}
}
isOverridePending = false;
return true;
}
private bool CreateLayerTextures(bool useMipmaps, OVRPlugin.Sizei size, bool isHdr)
{
if (isExternalSurface)
{
if (externalSurfaceObject == System.IntPtr.Zero)
{
externalSurfaceObject = OVRPlugin.GetLayerAndroidSurfaceObject(layerId);
if (externalSurfaceObject != System.IntPtr.Zero)
{
Debug.LogFormat("GetLayerAndroidSurfaceObject returns {0}", externalSurfaceObject);
if (externalSurfaceObjectCreated != null)
{
externalSurfaceObjectCreated();
}
}
}
return false;
}
bool needsCopy = false;
if (stageCount <= 0)
return false;
// For newer SDKs, blit directly to the surface that will be used in compositing.
if (layerTextures == null)
layerTextures = new LayerTexture[texturesPerStage];
for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
{
if (layerTextures[eyeId].swapChain == null)
layerTextures[eyeId].swapChain = new Texture[stageCount];
if (layerTextures[eyeId].swapChainPtr == null)
layerTextures[eyeId].swapChainPtr = new IntPtr[stageCount];
for (int stage = 0; stage < stageCount; ++stage)
{
Texture sc = layerTextures[eyeId].swapChain[stage];
IntPtr scPtr = layerTextures[eyeId].swapChainPtr[stage];
if (sc != null && scPtr != IntPtr.Zero)
continue;
if (scPtr == IntPtr.Zero)
scPtr = OVRPlugin.GetLayerTexture(layerId, stage, (OVRPlugin.Eye)eyeId);
if (scPtr == IntPtr.Zero)
continue;
var txFormat = (isHdr) ? TextureFormat.RGBAHalf : TextureFormat.RGBA32;
if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
sc = Texture2D.CreateExternalTexture(size.w, size.h, txFormat, useMipmaps, true, scPtr);
#if UNITY_2017_1_OR_NEWER
else
sc = Cubemap.CreateExternalTexture(size.w, txFormat, useMipmaps, scPtr);
#endif
layerTextures[eyeId].swapChain[stage] = sc;
layerTextures[eyeId].swapChainPtr[stage] = scPtr;
needsCopy = true;
}
}
return needsCopy;
}
private void DestroyLayerTextures()
{
if (isExternalSurface)
{
return;
}
for (int eyeId = 0; layerTextures != null && eyeId < texturesPerStage; ++eyeId)
{
if (layerTextures[eyeId].swapChain != null)
{
for (int stage = 0; stage < stageCount; ++stage)
DestroyImmediate(layerTextures[eyeId].swapChain[stage]);
}
}
layerTextures = null;
}
private void DestroyLayer()
{
if (layerIndex != -1)
{
// Turn off the overlay if it was on.
OVRPlugin.EnqueueSubmitLayer(true, false, IntPtr.Zero, IntPtr.Zero, -1, 0, OVRPose.identity.ToPosef(), Vector3.one.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)prevOverlayShape);
instances[layerIndex] = null;
layerIndex = -1;
}
if (layerIdPtr != IntPtr.Zero)
{
OVRPlugin.EnqueueDestroyLayer(layerIdPtr);
layerIdPtr = IntPtr.Zero;
layerIdHandle.Free();
layerId = 0;
}
layerDesc = new OVRPlugin.LayerDesc();
frameIndex = 0;
prevFrameIndex = -1;
}
private bool LatchLayerTextures()
{
if (isExternalSurface)
{
return true;
}
for (int i = 0; i < texturesPerStage; ++i)
{
if (textures[i] != layerTextures[i].appTexture || layerTextures[i].appTexturePtr == IntPtr.Zero)
{
if (textures[i] != null)
{
#if UNITY_EDITOR
var assetPath = UnityEditor.AssetDatabase.GetAssetPath(textures[i]);
var importer = (UnityEditor.TextureImporter)UnityEditor.TextureImporter.GetAtPath(assetPath);
if (importer && importer.textureType != UnityEditor.TextureImporterType.Default)
{
Debug.LogError("Need Default Texture Type for overlay");
return false;
}
#endif
var rt = textures[i] as RenderTexture;
if (rt && !rt.IsCreated())
rt.Create();
layerTextures[i].appTexturePtr = (texturePtrs[i] != IntPtr.Zero) ? texturePtrs[i] : textures[i].GetNativeTexturePtr();
if (layerTextures[i].appTexturePtr != IntPtr.Zero)
layerTextures[i].appTexture = textures[i];
}
}
if (currentOverlayShape == OverlayShape.Cubemap)
{
if (textures[i] as Cubemap == null)
{
Debug.LogError("Need Cubemap texture for cube map overlay");
return false;
}
}
}
#if !UNITY_ANDROID || UNITY_EDITOR
if (currentOverlayShape == OverlayShape.OffcenterCubemap)
{
Debug.LogWarning("Overlay shape " + currentOverlayShape + " is not supported on current platform");
return false;
}
#endif
if (layerTextures[0].appTexture == null || layerTextures[0].appTexturePtr == IntPtr.Zero)
return false;
return true;
}
private OVRPlugin.LayerDesc GetCurrentLayerDesc()
{
OVRPlugin.Sizei textureSize = new OVRPlugin.Sizei() { w = 0, h = 0 };
if (isExternalSurface)
{
textureSize.w = externalSurfaceWidth;
textureSize.h = externalSurfaceHeight;
}
else
{
if (textures[0] == null)
{
Debug.LogWarning("textures[0] hasn't been set");
}
textureSize.w = textures[0] ? textures[0].width : 0;
textureSize.h = textures[0] ? textures[0].height : 0;
}
OVRPlugin.LayerDesc newDesc = new OVRPlugin.LayerDesc() {
Format = OVRPlugin.EyeTextureFormat.R8G8B8A8_sRGB,
LayerFlags = isExternalSurface ? 0 : (int)OVRPlugin.LayerFlags.TextureOriginAtBottomLeft,
Layout = layout,
MipLevels = 1,
SampleCount = 1,
Shape = (OVRPlugin.OverlayShape)currentOverlayShape,
TextureSize = textureSize
};
var tex2D = textures[0] as Texture2D;
if (tex2D != null)
{
if (tex2D.format == TextureFormat.RGBAHalf || tex2D.format == TextureFormat.RGBAFloat)
newDesc.Format = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
newDesc.MipLevels = tex2D.mipmapCount;
}
var texCube = textures[0] as Cubemap;
if (texCube != null)
{
if (texCube.format == TextureFormat.RGBAHalf || texCube.format == TextureFormat.RGBAFloat)
newDesc.Format = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
newDesc.MipLevels = texCube.mipmapCount;
}
var rt = textures[0] as RenderTexture;
if (rt != null)
{
newDesc.SampleCount = rt.antiAliasing;
if (rt.format == RenderTextureFormat.ARGBHalf || rt.format == RenderTextureFormat.ARGBFloat || rt.format == RenderTextureFormat.RGB111110Float)
newDesc.Format = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
}
if (isProtectedContent)
{
newDesc.LayerFlags |= (int)OVRPlugin.LayerFlags.ProtectedContent;
}
if (isExternalSurface)
{
newDesc.LayerFlags |= (int)OVRPlugin.LayerFlags.AndroidSurfaceSwapChain;
}
return newDesc;
}
private bool PopulateLayer(int mipLevels, bool isHdr, OVRPlugin.Sizei size, int sampleCount, int stage)
{
if (isExternalSurface)
{
return true;
}
bool ret = false;
RenderTextureFormat rtFormat = (isHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
{
Texture et = layerTextures[eyeId].swapChain[stage];
if (et == null)
continue;
for (int mip = 0; mip < mipLevels; ++mip)
{
int width = size.w >> mip;
if (width < 1) width = 1;
int height = size.h >> mip;
if (height < 1) height = 1;
#if UNITY_2017_1_1 || UNITY_2017_2_OR_NEWER
RenderTextureDescriptor descriptor = new RenderTextureDescriptor(width, height, rtFormat, 0);
descriptor.msaaSamples = sampleCount;
descriptor.useMipMap = true;
descriptor.autoGenerateMips = false;
descriptor.sRGB = false;
var tempRTDst = RenderTexture.GetTemporary(descriptor);
#else
var tempRTDst = RenderTexture.GetTemporary(width, height, 0, rtFormat, RenderTextureReadWrite.Linear, sampleCount);
#endif
if (!tempRTDst.IsCreated())
tempRTDst.Create();
tempRTDst.DiscardContents();
bool dataIsLinear = isHdr || (QualitySettings.activeColorSpace == ColorSpace.Linear);
#if !UNITY_2017_1_OR_NEWER
var rt = textures[eyeId] as RenderTexture;
dataIsLinear |= rt != null && rt.sRGB; //HACK: Unity 5.6 and earlier convert to linear on read from sRGB RenderTexture.
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
dataIsLinear = true; //HACK: Graphics.CopyTexture causes linear->srgb conversion on target write with D3D but not GLES.
#endif
if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
{
tex2DMaterial.SetInt("_linearToSrgb", (!isHdr && dataIsLinear) ? 1 : 0);
//Resolve, decompress, swizzle, etc not handled by simple CopyTexture.
#if !UNITY_ANDROID || UNITY_EDITOR
// The PC compositor uses premultiplied alpha, so multiply it here.
tex2DMaterial.SetInt("_premultiply", 1);
#endif
Graphics.Blit(textures[eyeId], tempRTDst, tex2DMaterial);
Graphics.CopyTexture(tempRTDst, 0, 0, et, 0, mip);
}
#if UNITY_2017_1_OR_NEWER
else // Cubemap
{
for (int face = 0; face < 6; ++face)
{
cubeMaterial.SetInt("_linearToSrgb", (!isHdr && dataIsLinear) ? 1 : 0);
#if !UNITY_ANDROID || UNITY_EDITOR
// The PC compositor uses premultiplied alpha, so multiply it here.
cubeMaterial.SetInt("_premultiply", 1);
#endif
cubeMaterial.SetInt("_face", face);
//Resolve, decompress, swizzle, etc not handled by simple CopyTexture.
Graphics.Blit(textures[eyeId], tempRTDst, cubeMaterial);
Graphics.CopyTexture(tempRTDst, 0, 0, et, face, mip);
}
}
#endif
RenderTexture.ReleaseTemporary(tempRTDst);
ret = true;
}
}
return ret;
}
private bool SubmitLayer(bool overlay, bool headLocked, OVRPose pose, Vector3 scale, int frameIndex)
{
int rightEyeIndex = (texturesPerStage >= 2) ? 1 : 0;
bool isOverlayVisible = OVRPlugin.EnqueueSubmitLayer(overlay, headLocked,
isExternalSurface ? System.IntPtr.Zero : layerTextures[0].appTexturePtr,
isExternalSurface ? System.IntPtr.Zero : layerTextures[rightEyeIndex].appTexturePtr,
layerId, frameIndex, pose.flipZ().ToPosef(), scale.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)currentOverlayShape);
prevOverlayShape = currentOverlayShape;
return isOverlayVisible;
}
#region Unity Messages
void Awake()
{
Debug.Log("Overlay Awake");
if (tex2DMaterial == null)
tex2DMaterial = new Material(Shader.Find("Oculus/Texture2D Blit"));
if (cubeMaterial == null)
cubeMaterial = new Material(Shader.Find("Oculus/Cubemap Blit"));
rend = GetComponent<Renderer>();
if (textures.Length == 0)
textures = new Texture[] { null };
// Backward compatibility
if (rend != null && textures[0] == null)
textures[0] = rend.material.mainTexture;
}
void OnEnable()
{
if (!OVRManager.isHmdPresent)
{
enabled = false;
return;
}
}
void OnDisable()
{
if ((gameObject.hideFlags & HideFlags.DontSaveInBuild) != 0)
return;
DestroyLayerTextures();
DestroyLayer();
}
void OnDestroy()
{
DestroyLayerTextures();
DestroyLayer();
}
bool ComputeSubmit(ref OVRPose pose, ref Vector3 scale, ref bool overlay, ref bool headLocked)
{
Camera headCamera = Camera.main;
overlay = (currentOverlayType == OverlayType.Overlay);
headLocked = false;
for (var t = transform; t != null && !headLocked; t = t.parent)
headLocked |= (t == headCamera.transform);
pose = (headLocked) ? transform.ToHeadSpacePose(headCamera) : transform.ToTrackingSpacePose(headCamera);
scale = transform.lossyScale;
for (int i = 0; i < 3; ++i)
scale[i] /= headCamera.transform.lossyScale[i];
if (currentOverlayShape == OverlayShape.Cubemap)
{
#if UNITY_ANDROID && !UNITY_EDITOR
//HACK: VRAPI cubemaps assume are yawed 180 degrees relative to LibOVR.
pose.orientation = pose.orientation * Quaternion.AngleAxis(180, Vector3.up);
#endif
pose.position = headCamera.transform.position;
}
// Pack the offsetCenter directly into pose.position for offcenterCubemap
if (currentOverlayShape == OverlayShape.OffcenterCubemap)
{
pose.position = transform.position;
if (pose.position.magnitude > 1.0f)
{
Debug.LogWarning("Your cube map center offset's magnitude is greater than 1, which will cause some cube map pixel always invisible .");
return false;
}
}
// Cylinder overlay sanity checking
if (currentOverlayShape == OverlayShape.Cylinder)
{
float arcAngle = scale.x / scale.z / (float)Math.PI * 180.0f;
if (arcAngle > 180.0f)
{
Debug.LogWarning("Cylinder overlay's arc angle has to be below 180 degree, current arc angle is " + arcAngle + " degree." );
return false;
}
}
return true;
}
void LateUpdate()
{
// The overlay must be specified every eye frame, because it is positioned relative to the
// current head location. If frames are dropped, it will be time warped appropriately,
// just like the eye buffers.
if (currentOverlayType == OverlayType.None || ((textures.Length < texturesPerStage || textures[0] == null) && !isExternalSurface))
return;
OVRPose pose = OVRPose.identity;
Vector3 scale = Vector3.one;
bool overlay = false;
bool headLocked = false;
if (!ComputeSubmit(ref pose, ref scale, ref overlay, ref headLocked))
return;
OVRPlugin.LayerDesc newDesc = GetCurrentLayerDesc();
bool isHdr = (newDesc.Format == OVRPlugin.EyeTextureFormat.R16G16B16A16_FP);
bool createdLayer = CreateLayer(newDesc.MipLevels, newDesc.SampleCount, newDesc.Format, newDesc.LayerFlags, newDesc.TextureSize, newDesc.Shape);
if (layerIndex == -1 || layerId <= 0)
return;
bool useMipmaps = (newDesc.MipLevels > 1);
createdLayer |= CreateLayerTextures(useMipmaps, newDesc.TextureSize, isHdr);
if (!isExternalSurface && (layerTextures[0].appTexture as RenderTexture != null))
isDynamic = true;
if (!LatchLayerTextures())
return;
// Don't populate the same frame image twice.
if (frameIndex > prevFrameIndex)
{
int stage = frameIndex % stageCount;
if (!PopulateLayer (newDesc.MipLevels, isHdr, newDesc.TextureSize, newDesc.SampleCount, stage))
return;
}
bool isOverlayVisible = SubmitLayer(overlay, headLocked, pose, scale, frameIndex);
prevFrameIndex = frameIndex;
if (isDynamic)
++frameIndex;
// Backward compatibility: show regular renderer if overlay isn't visible.
if (rend)
rend.enabled = !isOverlayVisible;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CppSharp.AST;
using CppSharp.Generators;
using CppSharp.Parser;
using CppSharp.Passes;
using CppAbi = CppSharp.Parser.AST.CppAbi;
namespace CppSharp
{
/// <summary>
/// Generates C# and C++/CLI bindings for the CppSharp.CppParser project.
/// </summary>
class ParserGen : ILibrary
{
internal readonly GeneratorKind Kind;
internal readonly string Triple;
internal readonly CppAbi Abi;
internal readonly bool IsGnuCpp11Abi;
public ParserGen(GeneratorKind kind, string triple, CppAbi abi,
bool isGnuCpp11Abi = false)
{
Kind = kind;
Triple = triple;
Abi = abi;
IsGnuCpp11Abi = isGnuCpp11Abi;
}
static string GetSourceDirectory(string dir)
{
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (directory != null)
{
var path = Path.Combine(directory.FullName, dir);
if (Directory.Exists(path) &&
Directory.Exists(Path.Combine(directory.FullName, "deps")))
return path;
directory = directory.Parent;
}
throw new Exception("Could not find build directory: " + dir);
}
public void Setup(Driver driver)
{
var parserOptions = driver.ParserOptions;
parserOptions.TargetTriple = Triple;
parserOptions.Abi = Abi;
var options = driver.Options;
options.GeneratorKind = Kind;
options.CommentKind = CommentKind.BCPLSlash;
var parserModule = options.AddModule("CppSharp.CppParser");
parserModule.Headers.AddRange(new[]
{
"AST.h",
"Sources.h",
"CppParser.h"
});
parserModule.Libraries.Add("CppSharp.CppParser.lib");
parserModule.OutputNamespace = string.Empty;
if (Abi == CppAbi.Microsoft)
parserOptions.MicrosoftMode = true;
if (Triple.Contains("apple"))
SetupMacOptions(parserOptions);
if (Triple.Contains("linux"))
SetupLinuxOptions(parserOptions);
var basePath = Path.Combine(GetSourceDirectory("src"), "CppParser");
parserOptions.AddIncludeDirs(basePath);
parserOptions.AddLibraryDirs(".");
options.OutputDir = Path.Combine(GetSourceDirectory("src"), "CppParser",
"Bindings", Kind.ToString());
var extraTriple = IsGnuCpp11Abi ? "-cxx11abi" : string.Empty;
if (Kind == GeneratorKind.CSharp)
options.OutputDir = Path.Combine(options.OutputDir, parserOptions.TargetTriple + extraTriple);
options.CheckSymbols = false;
//options.Verbose = true;
options.UnityBuild = true;
}
private void SetupLinuxOptions(ParserOptions options)
{
options.MicrosoftMode = false;
options.NoBuiltinIncludes = true;
var headersPath = Platform.IsLinux ? string.Empty :
Path.Combine(GetSourceDirectory("build"), "headers", "x86_64-linux-gnu");
// Search for the available GCC versions on the provided headers.
var versions = Directory.EnumerateDirectories(Path.Combine(headersPath,
"usr/include/c++"));
if (versions.Count() == 0)
throw new Exception("No valid GCC version found on system include paths");
string gccVersionPath = versions.First();
string gccVersion = gccVersionPath.Substring(
gccVersionPath.LastIndexOf(Path.DirectorySeparatorChar) + 1);
string[] systemIncludeDirs = {
Path.Combine("usr", "include", "c++", gccVersion),
Path.Combine("usr", "include", "x86_64-linux-gnu", "c++", gccVersion),
Path.Combine("usr", "include", "c++", gccVersion, "backward"),
Path.Combine("usr", "lib", "gcc", "x86_64-linux-gnu", gccVersion, "include"),
Path.Combine("usr", "include", "x86_64-linux-gnu"),
Path.Combine("usr", "include")
};
foreach (var dir in systemIncludeDirs)
options.AddSystemIncludeDirs(Path.Combine(headersPath, dir));
options.AddDefines("_GLIBCXX_USE_CXX11_ABI=" + (IsGnuCpp11Abi ? "1" : "0"));
}
private static void SetupMacOptions(ParserOptions options)
{
options.MicrosoftMode = false;
options.NoBuiltinIncludes = true;
if (Platform.IsMacOS)
{
var headersPaths = new List<string> {
Path.Combine(GetSourceDirectory("deps"), "llvm/tools/clang/lib/Headers"),
Path.Combine(GetSourceDirectory("deps"), "libcxx", "include"),
"/usr/include",
};
foreach (var header in headersPaths)
Console.WriteLine(header);
foreach (var header in headersPaths)
options.AddSystemIncludeDirs(header);
}
var headersPath = Path.Combine(GetSourceDirectory("build"), "headers",
"osx");
options.AddSystemIncludeDirs(Path.Combine(headersPath, "include"));
options.AddSystemIncludeDirs(Path.Combine(headersPath, "clang", "4.2", "include"));
options.AddSystemIncludeDirs(Path.Combine(headersPath, "libcxx", "include"));
options.AddArguments("-stdlib=libc++");
}
public void SetupPasses(Driver driver)
{
}
public void Preprocess(Driver driver, ASTContext ctx)
{
ctx.RenameNamespace("CppSharp::CppParser", "Parser");
if (driver.Options.IsCSharpGenerator)
{
driver.Generator.OnUnitGenerated += o =>
{
Block firstBlock = o.Outputs[0].RootBlock.Blocks[1];
if (o.TranslationUnit.Module == driver.Options.SystemModule)
{
firstBlock.NewLine();
firstBlock.WriteLine("[assembly:InternalsVisibleTo(\"CppSharp.Parser.CSharp\")]");
}
else
{
firstBlock.WriteLine("using System.Runtime.CompilerServices;");
firstBlock.NewLine();
firstBlock.WriteLine("[assembly:InternalsVisibleTo(\"CppSharp.Parser\")]");
}
};
}
}
public void Postprocess(Driver driver, ASTContext ctx)
{
}
public static void Main(string[] args)
{
if (Platform.IsWindows)
{
Console.WriteLine("Generating the C++/CLI parser bindings for Windows...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CLI, "i686-pc-win32-msvc",
CppAbi.Microsoft));
Console.WriteLine();
Console.WriteLine("Generating the C# parser bindings for Windows...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "i686-pc-win32-msvc",
CppAbi.Microsoft));
Console.WriteLine();
Console.WriteLine("Generating the C# 64-bit parser bindings for Windows...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "x86_64-pc-win32-msvc",
CppAbi.Microsoft));
Console.WriteLine();
}
var osxHeadersPath = Path.Combine(GetSourceDirectory("build"), @"headers\osx");
if (Directory.Exists(osxHeadersPath) || Platform.IsMacOS)
{
Console.WriteLine("Generating the C# parser bindings for OSX...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "i686-apple-darwin12.4.0",
CppAbi.Itanium));
Console.WriteLine();
Console.WriteLine("Generating the C# parser bindings for OSX...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "x86_64-apple-darwin12.4.0",
CppAbi.Itanium));
Console.WriteLine();
}
var linuxHeadersPath = Path.Combine(GetSourceDirectory("build"), @"headers\x86_64-linux-gnu");
if (Directory.Exists(linuxHeadersPath) || Platform.IsLinux)
{
Console.WriteLine("Generating the C# parser bindings for Linux...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "x86_64-linux-gnu",
CppAbi.Itanium));
Console.WriteLine();
Console.WriteLine("Generating the C# parser bindings for Linux (GCC C++11 ABI)...");
ConsoleDriver.Run(new ParserGen(GeneratorKind.CSharp, "x86_64-linux-gnu",
CppAbi.Itanium, isGnuCpp11Abi: true));
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using System.Globalization;
using MICore;
using System.Threading.Tasks;
using System.Linq;
namespace Microsoft.MIDebugEngine
{
public static class EngineUtils
{
internal static string AsAddr(ulong addr, bool is64bit)
{
string addrFormat = is64bit ? "x16" : "x8";
return "0x" + addr.ToString(addrFormat, CultureInfo.InvariantCulture);
}
internal static string GetAddressDescription(DebuggedProcess proc, ulong ip)
{
string description = null;
proc.WorkerThread.RunOperation(async () =>
{
description = await EngineUtils.GetAddressDescriptionAsync(proc, ip);
}
);
return description;
}
internal static async Task<string> GetAddressDescriptionAsync(DebuggedProcess proc, ulong ip)
{
string location = null;
IEnumerable<DisasmInstruction> instructions = await proc.Disassembly.FetchInstructions(ip, 1);
if (instructions != null)
{
foreach (DisasmInstruction instruction in instructions)
{
if (location == null && !String.IsNullOrEmpty(instruction.Symbol))
{
location = instruction.Symbol;
break;
}
}
}
if (location == null)
{
string addrFormat = proc.Is64BitArch ? "x16" : "x8";
location = ip.ToString(addrFormat, CultureInfo.InvariantCulture);
}
return location;
}
public static void CheckOk(int hr)
{
if (hr != 0)
{
throw new MIException(hr);
}
}
public static void RequireOk(int hr)
{
if (hr != 0)
{
throw new InvalidOperationException();
}
}
public static AD_PROCESS_ID GetProcessId(IDebugProcess2 process)
{
AD_PROCESS_ID[] pid = new AD_PROCESS_ID[1];
EngineUtils.RequireOk(process.GetPhysicalProcessId(pid));
return pid[0];
}
public static AD_PROCESS_ID GetProcessId(IDebugProgram2 program)
{
IDebugProcess2 process;
RequireOk(program.GetProcess(out process));
return GetProcessId(process);
}
public static int UnexpectedException(Exception e)
{
Debug.Fail("Unexpected exception during Attach");
return Constants.RPC_E_SERVERFAULT;
}
internal static bool IsFlagSet(uint value, int flagValue)
{
return (value & flagValue) != 0;
}
internal static bool ProcIdEquals(AD_PROCESS_ID pid1, AD_PROCESS_ID pid2)
{
if (pid1.ProcessIdType != pid2.ProcessIdType)
{
return false;
}
else if (pid1.ProcessIdType == (int)enum_AD_PROCESS_ID.AD_PROCESS_ID_SYSTEM)
{
return pid1.dwProcessId == pid2.dwProcessId;
}
else
{
return pid1.guidProcessId == pid2.guidProcessId;
}
}
//
// The RegisterNameMap maps register names to logical group names. The architecture of
// the platform is described with all its varients. Any particular target may only contains a subset
// of the available registers.
public class RegisterNameMap
{
private Entry[] _map;
private struct Entry
{
public readonly string Name;
public readonly bool IsRegex;
public readonly string Group;
public Entry(string name, bool isRegex, string group)
{
Name = name;
IsRegex = isRegex;
Group = group;
}
};
private static readonly Entry[] s_arm32Registers = new Entry[]
{
new Entry( "sp", false, "CPU"),
new Entry( "lr", false, "CPU"),
new Entry( "pc", false, "CPU"),
new Entry( "cpsr", false, "CPU"),
new Entry( "r[0-9]+", true, "CPU"),
new Entry( "fpscr", false, "FPU"),
new Entry( "f[0-9]+", true, "FPU"),
new Entry( "s[0-9]+", true, "IEEE Single"),
new Entry( "d[0-9]+", true, "IEEE Double"),
new Entry( "q[0-9]+", true, "Vector"),
};
private static readonly Entry[] s_X86Registers = new Entry[]
{
new Entry( "eax", false, "CPU" ),
new Entry( "ecx", false, "CPU" ),
new Entry( "edx", false, "CPU" ),
new Entry( "ebx", false, "CPU" ),
new Entry( "esp", false, "CPU" ),
new Entry( "ebp", false, "CPU" ),
new Entry( "esi", false, "CPU" ),
new Entry( "edi", false, "CPU" ),
new Entry( "eip", false, "CPU" ),
new Entry( "eflags", false, "CPU" ),
new Entry( "cs", false, "CPU" ),
new Entry( "ss", false, "CPU" ),
new Entry( "ds", false, "CPU" ),
new Entry( "es", false, "CPU" ),
new Entry( "fs", false, "CPU" ),
new Entry( "gs", false, "CPU" ),
new Entry( "st", true, "CPU" ),
new Entry( "fctrl", false, "CPU" ),
new Entry( "fstat", false, "CPU" ),
new Entry( "ftag", false, "CPU" ),
new Entry( "fiseg", false, "CPU" ),
new Entry( "fioff", false, "CPU" ),
new Entry( "foseg", false, "CPU" ),
new Entry( "fooff", false, "CPU" ),
new Entry( "fop", false, "CPU" ),
new Entry( "mxcsr", false, "CPU" ),
new Entry( "orig_eax", false, "CPU" ),
new Entry( "al", false, "CPU" ),
new Entry( "cl", false, "CPU" ),
new Entry( "dl", false, "CPU" ),
new Entry( "bl", false, "CPU" ),
new Entry( "ah", false, "CPU" ),
new Entry( "ch", false, "CPU" ),
new Entry( "dh", false, "CPU" ),
new Entry( "bh", false, "CPU" ),
new Entry( "ax", false, "CPU" ),
new Entry( "cx", false, "CPU" ),
new Entry( "dx", false, "CPU" ),
new Entry( "bx", false, "CPU" ),
new Entry( "bp", false, "CPU" ),
new Entry( "si", false, "CPU" ),
new Entry( "di", false, "CPU" ),
new Entry( "mm[0-7]", true, "MMX" ),
new Entry( "xmm[0-7]ih", true, "SSE2" ),
new Entry( "xmm[0-7]il", true, "SSE2" ),
new Entry( "xmm[0-7]dh", true, "SSE2" ),
new Entry( "xmm[0-7]dl", true, "SSE2" ),
new Entry( "xmm[0-7][0-7]", true, "SSE" ),
new Entry( "ymm.+", true, "AVX" ),
new Entry( "mm[0-7][0-7]", true, "AMD3DNow" ),
};
private static readonly Entry[] s_allRegisters = new Entry[]
{
new Entry( ".+", true, "CPU"),
};
public static RegisterNameMap Create(string[] registerNames)
{
// TODO: more robust mechanism for determining processor architecture
RegisterNameMap map = new RegisterNameMap();
if (registerNames[0][0] == 'r') // registers are prefixed with 'r', assume ARM and initialize its register sets
{
map._map = s_arm32Registers;
}
else if (registerNames[0][0] == 'e') // x86 register set
{
map._map = s_X86Registers;
}
else
{
// report one global register set
map._map = s_allRegisters;
}
return map;
}
public string GetGroupName(string regName)
{
foreach (var e in _map)
{
if (e.IsRegex)
{
if (System.Text.RegularExpressions.Regex.IsMatch(regName, e.Name))
{
return e.Group;
}
}
else if (e.Name == regName)
{
return e.Group;
}
}
return "Other Registers";
}
};
internal static string GetExceptionDescription(Exception exception)
{
if (!IsCorruptingException(exception))
{
return exception.Message;
}
else
{
return string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_CorruptingException, exception.GetType().FullName, exception.StackTrace);
}
}
private static bool IsCorruptingException(Exception exception)
{
if (exception is NullReferenceException)
return true;
if (exception is ArgumentNullException)
return true;
if (exception is ArithmeticException)
return true;
if (exception is ArrayTypeMismatchException)
return true;
if (exception is DivideByZeroException)
return true;
if (exception is IndexOutOfRangeException)
return true;
if (exception is InvalidCastException)
return true;
if (exception is System.Runtime.InteropServices.SEHException)
return true;
return false;
}
internal class SignalMap : Dictionary<string, uint>
{
private static SignalMap s_instance;
private SignalMap()
{
this["SIGHUP"] = 1;
this["SIGINT"] = 2;
this["SIGQUIT"] = 3;
this["SIGILL"] = 4;
this["SIGTRAP"] = 5;
this["SIGABRT"] = 6;
this["SIGIOT"] = 6;
this["SIGBUS"] = 7;
this["SIGFPE"] = 8;
this["SIGKILL"] = 9;
this["SIGUSR1"] = 10;
this["SIGSEGV"] = 11;
this["SIGUSR2"] = 12;
this["SIGPIPE"] = 13;
this["SIGALRM"] = 14;
this["SIGTERM"] = 15;
this["SIGSTKFLT"] = 16;
this["SIGCHLD"] = 17;
this["SIGCONT"] = 18;
this["SIGSTOP"] = 19;
this["SIGTSTP"] = 20;
this["SIGTTIN"] = 21;
this["SIGTTOU"] = 22;
this["SIGURG"] = 23;
this["SIGXCPU"] = 24;
this["SIGXFSZ"] = 25;
this["SIGVTALRM"] = 26;
this["SIGPROF"] = 27;
this["SIGWINCH"] = 28;
this["SIGIO"] = 29;
this["SIGPOLL"] = 29;
this["SIGPWR"] = 30;
this["SIGSYS"] = 31;
this["SIGUNUSED"] = 31;
}
public static SignalMap Instance
{
get
{
if (s_instance == null)
{
s_instance = new SignalMap();
}
return s_instance;
}
}
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using DotSpatial.Data;
using DotSpatial.NTSExtension;
using DotSpatial.NTSExtension.Voronoi;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
namespace DotSpatial.Analysis
{
/// <summary>
/// This class provides an application programming interface to access the Voronoi calculations that are wrapped by a tool.
/// </summary>
public static class Voronoi
{
#region Methods
/// <summary>
/// The Voronoi Graph calculation creates a delaunay tesselation where
/// each point is effectively converted into triangles.
/// </summary>
/// <param name="points">The points to use for creating the tesselation.</param>
/// <returns>The generated line featureset.</returns>
public static IFeatureSet DelaunayLines(IFeatureSet points)
{
double[] vertices = points.Vertex;
VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices);
FeatureSet result = new FeatureSet();
foreach (VoronoiEdge edge in gp.Edges)
{
Coordinate c1 = edge.RightData.ToCoordinate();
Coordinate c2 = edge.LeftData.ToCoordinate();
LineString ls = new LineString(new[] { c1, c2 });
result.AddFeature(ls);
}
return result;
}
/// <summary>
/// The Voronoi Graph calculation creates the lines that form a voronoi diagram.
/// </summary>
/// <param name="points">The points to use for creating the tesselation.</param>
/// <returns>An IFeatureSet that is the resulting set of lines in the diagram.</returns>
public static IFeatureSet VoronoiLines(IFeatureSet points)
{
double[] vertices = points.Vertex;
VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices);
HandleBoundaries(gp, points.Extent.ToEnvelope());
FeatureSet result = new FeatureSet();
foreach (VoronoiEdge edge in gp.Edges)
{
Coordinate c1 = edge.VVertexA.ToCoordinate();
Coordinate c2 = edge.VVertexB.ToCoordinate();
LineString ls = new LineString(new[] { c1, c2 });
result.AddFeature(ls);
}
return result;
}
/// <summary>
/// The Voronoi Graph calculation creates the lines that form a voronoi diagram.
/// </summary>
/// <param name="points">The points to use for creating the tesselation.</param>
/// <param name="cropToExtent">The normal polygons have sharp angles that extend like stars.
/// Cropping will ensure that the original featureset extent plus a small extra buffer amount
/// is the outer extent of the polygons. Errors seem to occur if the exact extent is used.</param>
/// <returns>The IFeatureSet containing the lines that were formed in the diagram.</returns>
public static IFeatureSet VoronoiPolygons(IFeatureSet points, bool cropToExtent)
{
IFeatureSet fs = new FeatureSet();
VoronoiPolygons(points, fs, cropToExtent);
return fs;
}
/// <summary>
/// The Voronoi Graph calculation creates the lines that form a voronoi diagram.
/// </summary>
/// <param name="points">The points to use for creating the tesselation.</param>
/// <param name="result">The output featureset.</param>
/// <param name="cropToExtent">The normal polygons have sharp angles that extend like stars.
/// Cropping will ensure that the original featureset extent plus a small extra buffer amount
/// is the outer extent of the polygons. Errors seem to occur if the exact extent is used.</param>
public static void VoronoiPolygons(IFeatureSet points, IFeatureSet result, bool cropToExtent)
{
double[] vertices = points.Vertex;
VoronoiGraph gp = Fortune.ComputeVoronoiGraph(vertices);
Extent ext = points.Extent;
ext.ExpandBy(ext.Width / 100, ext.Height / 100);
Envelope env = ext.ToEnvelope();
IPolygon bounds = env.ToPolygon();
// Convert undefined coordinates to a defined coordinate.
HandleBoundaries(gp, env);
for (int i = 0; i < vertices.Length / 2; i++)
{
List<VoronoiEdge> myEdges = new List<VoronoiEdge>();
Vector2 v = new Vector2(vertices, i * 2);
foreach (VoronoiEdge edge in gp.Edges)
{
if (!v.Equals(edge.RightData) && !v.Equals(edge.LeftData))
{
continue;
}
myEdges.Add(edge);
}
List<Coordinate> coords = new List<Coordinate>();
VoronoiEdge firstEdge = myEdges[0];
coords.Add(firstEdge.VVertexA.ToCoordinate());
coords.Add(firstEdge.VVertexB.ToCoordinate());
Vector2 previous = firstEdge.VVertexB;
myEdges.Remove(myEdges[0]);
Vector2 start = firstEdge.VVertexA;
while (myEdges.Count > 0)
{
for (int j = 0; j < myEdges.Count; j++)
{
VoronoiEdge edge = myEdges[j];
if (edge.VVertexA.Equals(previous))
{
previous = edge.VVertexB;
Coordinate c = previous.ToCoordinate();
coords.Add(c);
myEdges.Remove(edge);
break;
}
// couldn't match by adding to the end, so try adding to the beginning
if (edge.VVertexB.Equals(start))
{
start = edge.VVertexA;
coords.Insert(0, start.ToCoordinate());
myEdges.Remove(edge);
break;
}
// I don't like the reverse situation, but it seems necessary.
if (edge.VVertexB.Equals(previous))
{
previous = edge.VVertexA;
Coordinate c = previous.ToCoordinate();
coords.Add(c);
myEdges.Remove(edge);
break;
}
if (edge.VVertexA.Equals(start))
{
start = edge.VVertexB;
coords.Insert(0, start.ToCoordinate());
myEdges.Remove(edge);
break;
}
}
}
for (int j = 0; j < coords.Count; j++)
{
Coordinate cA = coords[j];
// Remove NAN values
if (double.IsNaN(cA.X) || double.IsNaN(cA.Y))
{
coords.Remove(cA);
}
// Remove duplicate coordinates
for (int k = j + 1; k < coords.Count; k++)
{
Coordinate cB = coords[k];
if (cA.Equals2D(cB))
{
coords.Remove(cB);
}
}
}
foreach (Coordinate coord in coords)
{
if (double.IsNaN(coord.X) || double.IsNaN(coord.Y))
{
coords.Remove(coord);
}
}
if (coords.Count <= 2)
{
continue;
}
Polygon pg = new Polygon(new LinearRing(coords.ToArray()));
if (cropToExtent)
{
try
{
IGeometry g = pg.Intersection(bounds);
IPolygon p = g as IPolygon;
if (p != null)
{
Feature f = new Feature(p, result);
f.CopyAttributes(points.Features[i]);
}
}
catch (Exception)
{
Feature f = new Feature(pg, result);
f.CopyAttributes(points.Features[i]);
}
}
else
{
Feature f = new Feature(pg, result);
f.CopyAttributes(points.Features[i]);
}
}
}
/// <summary>
/// The original algorithm simply allows edges that have one defined point and
/// another "NAN" point. Simply excluding the not a number coordinates fails
/// to preserve the known direction of the ray. We only need to extend this
/// long enough to encounter the bounding box, not infinity.
/// </summary>
/// <param name="graph">The VoronoiGraph with the edge list.</param>
/// <param name="bounds">The polygon bounding the datapoints.</param>
private static void HandleBoundaries(VoronoiGraph graph, Envelope bounds)
{
List<ILineString> boundSegments = new List<ILineString>();
List<VoronoiEdge> unboundEdges = new List<VoronoiEdge>();
// Identify bound edges for intersection testing
foreach (VoronoiEdge edge in graph.Edges)
{
if (edge.VVertexA.ContainsNan() || edge.VVertexB.ContainsNan())
{
unboundEdges.Add(edge);
continue;
}
boundSegments.Add(new LineString(new[] { edge.VVertexA.ToCoordinate(), edge.VVertexB.ToCoordinate() }));
}
// calculate a length to extend a ray to look for intersections
Envelope env = bounds;
double h = env.Height;
double w = env.Width;
double len = Math.Sqrt((w * w) + (h * h));
// len is now long enough to pass entirely through the dataset no matter where it starts
foreach (VoronoiEdge edge in unboundEdges)
{
// the unbound line passes thorugh start
Coordinate start = edge.VVertexB.ContainsNan() ? edge.VVertexA.ToCoordinate() : edge.VVertexB.ToCoordinate();
// the unbound line should have a direction normal to the line joining the left and right source points
double dx = edge.LeftData.X - edge.RightData.X;
double dy = edge.LeftData.Y - edge.RightData.Y;
double l = Math.Sqrt((dx * dx) + (dy * dy));
// the slope of the bisector between left and right
double sx = -dy / l;
double sy = dx / l;
Coordinate center = bounds.Center();
if ((start.X > center.X && start.Y > center.Y) || (start.X < center.X && start.Y < center.Y))
{
sx = dy / l;
sy = -dx / l;
}
Coordinate end1 = new Coordinate(start.X + (len * sx), start.Y + (len * sy));
Coordinate end2 = new Coordinate(start.X - (sx * len), start.Y - (sy * len));
Coordinate end = (end1.Distance(center) < end2.Distance(center)) ? end2 : end1;
if (bounds.Contains(end))
{
end = new Coordinate(start.X - (sx * len), start.Y - (sy * len));
}
if (edge.VVertexA.ContainsNan())
{
edge.VVertexA = new Vector2(end.X, end.Y);
}
else
{
edge.VVertexB = new Vector2(end.X, end.Y);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.IpV6;
using PcapDotNet.TestUtils;
namespace PcapDotNet.Core.Test
{
internal class WiresharkDatagramComparerIpV6 : WiresharkDatagramComparerSimple
{
public WiresharkDatagramComparerIpV6()
{
}
protected override string PropertyName
{
get { return "IpV6"; }
}
protected override bool CompareField(XElement field, Datagram datagram)
{
IpV6Datagram ipV6Datagram = (IpV6Datagram)datagram;
SkipAuthenticationHeaders(ipV6Datagram);
int optionsIndex = 0;
switch (field.Name())
{
case "ipv6.version":
// TODO: Remove this when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10706 is fixed.
if (field.Show() != ipV6Datagram.Version.ToString())
return false;
field.AssertShowDecimal(ipV6Datagram.Version);
foreach (XElement subfield in field.Fields())
{
switch (subfield.Name())
{
case "ip.version":
subfield.AssertShowDecimal(ipV6Datagram.Version);
break;
default:
throw new InvalidOperationException(string.Format("Invalid ipv6 version subfield {0}", subfield.Name()));
}
}
break;
case "ipv6.class":
field.AssertShowDecimal(ipV6Datagram.TrafficClass);
break;
case "ipv6.flow":
field.AssertShowDecimal(ipV6Datagram.FlowLabel);
field.AssertNoFields();
break;
case "ipv6.plen":
field.AssertShowDecimal(ipV6Datagram.PayloadLength);
field.AssertNoFields();
break;
case "ipv6.nxt":
field.AssertShowDecimal((byte)ipV6Datagram.NextHeader);
field.AssertNoFields();
break;
case "ipv6.hlim":
field.AssertShowDecimal(ipV6Datagram.HopLimit);
field.AssertNoFields();
break;
case "ipv6.src":
case "ipv6.src_host":
field.AssertShow(ipV6Datagram.Source.GetWiresharkString());
field.AssertNoFields();
break;
case "ipv6.src_6to4_gw_ipv4":
case "ipv6.src_6to4_sla_id":
case "ipv6.6to4_gw_ipv4":
case "ipv6.6to4_sla_id":
field.AssertNoFields();
break;
case "ipv6.dst":
case "ipv6.dst_host":
field.AssertShow(ipV6Datagram.CurrentDestination.GetWiresharkString());
field.AssertNoFields();
break;
case "ipv6.addr":
case "ipv6.host":
Assert.IsTrue(field.Show() == ipV6Datagram.Source.GetWiresharkString() ||
field.Show() == ipV6Datagram.CurrentDestination.GetWiresharkString());
field.AssertNoFields();
break;
case "ipv6.hop_opt":
if (_currentExtensionHeaderIndex >= ipV6Datagram.ExtensionHeaders.Headers.Count)
{
Assert.IsFalse(ipV6Datagram.ExtensionHeaders.IsValid);
int maxLength = ipV6Datagram.Length - IpV6Datagram.HeaderLength - ipV6Datagram.ExtensionHeaders.BytesLength;
if (field.Fields().Any(subfield => subfield.Name() == "ipv6.opt.length"))
{
int length = int.Parse(field.Fields().First(subfield => subfield.Name() == "ipv6.opt.length").Show());
MoreAssert.IsBigger(maxLength, length);
}
else
{
Assert.AreEqual(6, maxLength);
}
}
else
{
IpV6ExtensionHeaderHopByHopOptions hopByHopOptions =
(IpV6ExtensionHeaderHopByHopOptions)ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex];
IncrementCurrentExtensionHeaderIndex(ipV6Datagram);
CompareOptions(field, ref optionsIndex, ipV6Datagram, hopByHopOptions);
}
break;
case "ipv6.routing_hdr":
if (!ipV6Datagram.IsValid)
return false;
IpV6ExtensionHeaderRouting routing = (IpV6ExtensionHeaderRouting)ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex];
IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks routingProtocolLowPowerAndLossyNetworks =
routing as IpV6ExtensionHeaderRoutingProtocolLowPowerAndLossyNetworks;
int routingProtocolLowPowerAndLossyNetworksAddressIndex = 0;
IncrementCurrentExtensionHeaderIndex(ipV6Datagram);
int sourceRouteAddressIndex = 0;
foreach (var headerField in field.Fields())
{
switch (headerField.Name())
{
case "":
headerField.AssertNoFields();
ValidateExtensionHeaderUnnamedField(routing, headerField);
break;
case "ipv6.routing_hdr.type":
headerField.AssertNoFields();
headerField.AssertShowDecimal((byte)routing.RoutingType);
break;
case "ipv6.routing_hdr.left":
headerField.AssertNoFields();
headerField.AssertShowDecimal(routing.SegmentsLeft);
break;
case "ipv6.mipv6_home_address":
headerField.AssertNoFields();
IpV6ExtensionHeaderRoutingHomeAddress routingHomeAddress = (IpV6ExtensionHeaderRoutingHomeAddress)routing;
headerField.AssertShow(routingHomeAddress.HomeAddress.ToString("x"));
break;
case "ipv6.routing_hdr.addr":
headerField.AssertNoFields();
IpV6ExtensionHeaderRoutingSourceRoute routingSourceRoute = (IpV6ExtensionHeaderRoutingSourceRoute)routing;
headerField.AssertShow(routingSourceRoute.Addresses[sourceRouteAddressIndex++].ToString("x"));
break;
case "ipv6.routing_hdr.rpl.cmprI":
headerField.AssertNoFields();
headerField.AssertShowDecimal(routingProtocolLowPowerAndLossyNetworks.CommonPrefixLengthForNonLastAddresses);
break;
case "ipv6.routing_hdr.rpl.cmprE":
headerField.AssertNoFields();
headerField.AssertShowDecimal(routingProtocolLowPowerAndLossyNetworks.CommonPrefixLengthForLastAddress);
break;
case "ipv6.routing_hdr.rpl.pad":
headerField.AssertNoFields();
headerField.AssertShowDecimal(routingProtocolLowPowerAndLossyNetworks.PadSize);
break;
case "ipv6.routing_hdr.rpl.reserved":
headerField.AssertNoFields();
headerField.AssertShowDecimal(0);
break;
case "ipv6.routing_hdr.rpl.segments":
if (headerField.Fields().Any())
{
headerField.AssertNumFields(1);
headerField.Fields().First().AssertName("_ws.expert");
}
// TODO: Uncomment when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10560 is fixed.
// headerField.AssertShowDecimal(routingProtocolLowPowerAndLossyNetworks.Addresses.Count);
break;
case "ipv6.routing_hdr.rpl.address":
headerField.AssertNoFields();
// TODO: Implement when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10560 is fixed.
break;
case "ipv6.routing_hdr.rpl.full_address":
headerField.AssertNoFields();
// TODO: Implement when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10673 is fixed.
++routingProtocolLowPowerAndLossyNetworksAddressIndex;
break;
default:
throw new InvalidOperationException("Invalid IPv6 routing source route field " + headerField.Name());
}
}
break;
case "ipv6.dst_opt":
if (_currentExtensionHeaderIndex >= ipV6Datagram.ExtensionHeaders.Headers.Count)
{
int expectedExtensionHeaderLength = (int.Parse(field.Fields().Skip(1).First().Value(), NumberStyles.HexNumber) + 1) * 8;
int actualMaxPossibleLength = ipV6Datagram.RealPayloadLength -
ipV6Datagram.ExtensionHeaders.Take(_currentExtensionHeaderIndex).Sum(
extensionHeader => extensionHeader.Length);
MoreAssert.IsSmaller(expectedExtensionHeaderLength, actualMaxPossibleLength);
return false;
}
IpV6ExtensionHeaderDestinationOptions destinationOptions = (IpV6ExtensionHeaderDestinationOptions)ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex];
IncrementCurrentExtensionHeaderIndex(ipV6Datagram);
CompareOptions(field, ref optionsIndex, ipV6Datagram, destinationOptions);
break;
case "ipv6.shim6":
// TODO: Implement Shim6.
IpV4Protocol nextHeader = _currentExtensionHeaderIndex > 0
? ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex - 1].NextHeader.Value
: ipV6Datagram.NextHeader;
Assert.IsTrue(nextHeader == IpV4Protocol.Shim6);
break;
case "ipv6.unknown_hdr":
Assert.AreEqual(ipV6Datagram.ExtensionHeaders.Count(), _currentExtensionHeaderIndex);
// TODO: Fix according to https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=9996
return false;
case "ipv6.src_sa_mac":
case "ipv6.dst_sa_mac":
case "ipv6.sa_mac":
case "ipv6.dst_6to4_gw_ipv4":
case "ipv6.dst_6to4_sla_id":
// TODO: Understand how these are calculated.
break;
case "":
switch (field.Show())
{
case "Fragmentation Header":
if (_currentExtensionHeaderIndex >= ipV6Datagram.ExtensionHeaders.Headers.Count && !ipV6Datagram.IsValid)
return false;
IpV6ExtensionHeaderFragmentData fragmentData =
(IpV6ExtensionHeaderFragmentData)ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex];
IncrementCurrentExtensionHeaderIndex(ipV6Datagram);
foreach (var headerField in field.Fields())
{
switch (headerField.Name())
{
case "ipv6.fragment.nxt":
headerField.AssertValue((byte)fragmentData.NextHeader.Value);
break;
case "ipv6.fragment.offset":
headerField.AssertShowDecimal(fragmentData.FragmentOffset);
break;
case "ipv6.fragment.more":
headerField.AssertShowDecimal(fragmentData.MoreFragments);
break;
case "ipv6.fragment.id":
headerField.AssertShowDecimal(fragmentData.Identification);
break;
case "ipv6.fragment.reserved_octet":
case "ipv6.fragment.reserved_bits":
headerField.AssertShowDecimal(0);
break;
default:
throw new InvalidOperationException("Invalid ipv6 fragmentation field " + headerField.Name());
}
}
break;
default:
throw new InvalidOperationException(string.Format("Invalid ipv6 field {0}", field.Show()));
}
break;
default:
throw new InvalidOperationException(string.Format("Invalid ipv6 field {0}", field.Name()));
}
return true;
}
private void CompareOptions(XElement field, ref int optionsIndex, IpV6Datagram ipV6Datagram, IpV6ExtensionHeaderOptions header)
{
foreach (var headerField in field.Fields())
{
switch (headerField.Name())
{
case "ipv6.nxt":
headerField.AssertNoFields();
headerField.AssertShowDecimal((byte)header.NextHeader);
break;
case "ipv6.opt.length":
headerField.AssertNoFields();
headerField.AssertShowDecimal((header.Length - 8) / 8);
break;
case "ipv6.opt":
foreach (XElement headerSubfield in headerField.Fields())
{
IpV6Option option = header.Options[optionsIndex];
var optionCalipso = option as IpV6OptionCalipso;
var optionQuickStart = option as IpV6OptionQuickStart;
switch (headerSubfield.Name())
{
case "ipv6.opt.type":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal((byte)option.OptionType);
break;
case "ipv6.opt.length":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(option.Length - 2);
break;
case "ipv6.opt.tel":
headerSubfield.AssertNoFields();
IpV6OptionTunnelEncapsulationLimit optionTunnelEncapsulationLimit = (IpV6OptionTunnelEncapsulationLimit)option;
headerSubfield.AssertShowDecimal(optionTunnelEncapsulationLimit.TunnelEncapsulationLimit);
++optionsIndex;
break;
case "ipv6.opt.rpl.flag":
IpV6OptionRoutingProtocolLowPowerAndLossyNetworks optionRoutingProtocolLowPowerAndLossyNetworks =
(IpV6OptionRoutingProtocolLowPowerAndLossyNetworks)option;
foreach (XElement optionSubfield in headerSubfield.Fields())
{
optionSubfield.AssertNoFields();
switch (optionSubfield.Name())
{
case "ipv6.opt.rpl.flag.o":
optionSubfield.AssertShowDecimal(optionRoutingProtocolLowPowerAndLossyNetworks.Down);
break;
case "ipv6.opt.rpl.flag.r":
optionSubfield.AssertShowDecimal(optionRoutingProtocolLowPowerAndLossyNetworks.RankError);
break;
case "ipv6.opt.rpl.flag.f":
optionSubfield.AssertShowDecimal(optionRoutingProtocolLowPowerAndLossyNetworks.ForwardingError);
break;
case "ipv6.opt.rpl.flag.rsv":
optionSubfield.AssertShowDecimal(0);
break;
case "ipv6.opt.rpl.instance_id":
optionSubfield.AssertShowDecimal(
optionRoutingProtocolLowPowerAndLossyNetworks.RoutingProtocolLowPowerAndLossyNetworksInstanceId);
break;
case "ipv6.opt.rpl.sender_rank":
optionSubfield.AssertShowDecimal(optionRoutingProtocolLowPowerAndLossyNetworks.SenderRank);
break;
default:
throw new InvalidOperationException("Invalid ipv6 option subfield " + optionSubfield.Name());
}
}
++optionsIndex;
// TODO: change to break; after https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10559 is fixed.
return;
case "ipv6.opt.calipso.doi":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal((uint)optionCalipso.DomainOfInterpretation);
break;
case "ipv6.opt.calipso.cmpt.length":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(optionCalipso.CompartmentLength);
break;
case "ipv6.opt.calipso.sens_level":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(optionCalipso.SensitivityLevel);
break;
case "ipv6.opt.calipso.checksum":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(optionCalipso.Checksum);
break;
case "ipv6.opt.calipso.cmpt_bitmap":
headerSubfield.AssertNoFields();
headerSubfield.AssertValue(optionCalipso.CompartmentBitmap);
++optionsIndex;
break;
case "ipv6.opt.router_alert":
headerSubfield.AssertNoFields();
var optionRouterAlert = (IpV6OptionRouterAlert)option;
headerSubfield.AssertShowDecimal((ushort)optionRouterAlert.RouterAlertType);
++optionsIndex;
break;
case "ipv6.opt.padn":
headerSubfield.AssertNoFields();
var optionPadN = (IpV6OptionPadN)option;
headerSubfield.AssertValue(new byte[optionPadN.PaddingDataLength]);
++optionsIndex;
break;
case "ipv6.opt.qs_func":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal((byte)optionQuickStart.QuickStartFunction);
break;
case "ipv6.opt.qs_rate":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(optionQuickStart.Rate);
break;
case "ipv6.opt.qs_ttl":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(optionQuickStart.Ttl);
break;
case "ipv6.opt.qs_ttl_diff":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal((256 + ipV6Datagram.HopLimit - optionQuickStart.Ttl) % 256);
break;
case "ipv6.opt.qs_unused":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(optionQuickStart.Ttl);
break;
case "ipv6.opt.qs_nonce":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(optionQuickStart.Nonce);
break;
case "ipv6.opt.qs_reserved":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(0);
++optionsIndex;
break;
case "ipv6.opt.pad1":
headerSubfield.AssertNoFields();
headerSubfield.AssertShow("");
Assert.IsTrue(option is IpV6OptionPad1);
++optionsIndex;
break;
case "ipv6.opt.jumbo":
headerSubfield.AssertNoFields();
headerSubfield.AssertShowDecimal(((IpV6OptionJumboPayload)option).JumboPayloadLength);
++optionsIndex;
break;
case "ipv6.mipv6_home_address":
headerSubfield.AssertNoFields();
headerSubfield.AssertShow(((IpV6OptionHomeAddress)option).HomeAddress.GetWiresharkString());
++optionsIndex;
break;
case "ipv6.opt.unknown":
headerSubfield.AssertNoFields();
Assert.IsTrue(new[]
{
IpV6OptionType.LineIdentification,
IpV6OptionType.IdentifierLocatorNetworkProtocolNonce,
IpV6OptionType.SimplifiedMulticastForwardingDuplicatePacketDetection,
IpV6OptionType.EndpointIdentification,
}.Contains(option.OptionType),
option.OptionType.ToString());
++optionsIndex;
break;
default:
throw new InvalidOperationException("Invalid ipv6 header subfield " + headerSubfield.Name());
}
}
break;
default:
throw new InvalidOperationException("Invalid ipv6 options field " + headerField.Name());
}
}
}
private void IncrementCurrentExtensionHeaderIndex(IpV6Datagram ipV6Datagram)
{
++_currentExtensionHeaderIndex;
SkipAuthenticationHeaders(ipV6Datagram);
}
private void SkipAuthenticationHeaders(IpV6Datagram ipV6Datagram)
{
while (_currentExtensionHeaderIndex < ipV6Datagram.ExtensionHeaders.Headers.Count &&
ipV6Datagram.ExtensionHeaders[_currentExtensionHeaderIndex].Protocol == IpV4Protocol.AuthenticationHeader)
{
++_currentExtensionHeaderIndex;
}
}
private void ValidateExtensionHeaderUnnamedField(IpV6ExtensionHeader header, XElement headerField)
{
int optionIndex = -1;
ValidateExtensionHeaderUnnamedField(header, headerField, ref optionIndex);
}
private void ValidateExtensionHeaderUnnamedField(IpV6ExtensionHeader header, XElement headerField, ref int optionsIndex)
{
IpV6ExtensionHeaderOptions headerOptions = header as IpV6ExtensionHeaderOptions;
string[] headerFieldShowParts = headerField.Show().Split(':');
string headerFieldShowName = headerFieldShowParts[0];
string headerFieldShowValue = headerFieldShowParts[1];
switch (headerFieldShowName)
{
case "Next header":
headerField.AssertValue((byte)header.NextHeader.Value);
break;
case "Length":
if (header.IsValid)
Assert.IsTrue(headerFieldShowValue.EndsWith(" (" + header.Length + " bytes)"));
break;
case "Router alert":
IpV6OptionRouterAlert routerAlert = (IpV6OptionRouterAlert)headerOptions.Options[optionsIndex++];
switch (headerFieldShowValue)
{
case " MLD (4 bytes)":
Assert.AreEqual(IpV6RouterAlertType.MulticastListenerDiscovery, routerAlert.RouterAlertType);
break;
case " RSVP (4 bytes)":
Assert.AreEqual(IpV6RouterAlertType.Rsvp, routerAlert.RouterAlertType);
break;
case " Unknown (4 bytes)":
MoreAssert.IsInRange((ushort)IpV6RouterAlertType.ActiveNetwork, (ushort)IpV6RouterAlertType.NextStepsInSignalingNatFirewallLayerProtocol, (ushort)routerAlert.RouterAlertType);
headerField.AssertValueInRange(0x05020002, 0x05020044);
break;
default:
throw new InvalidOperationException("Invalid ipv6 header route Router alert value " + headerFieldShowValue);
}
break;
case "Jumbo payload":
IpV6OptionJumboPayload jumboPayload = (IpV6OptionJumboPayload)headerOptions.Options[optionsIndex++];
Assert.AreEqual(" " + jumboPayload.JumboPayloadLength + " (6 bytes)", headerFieldShowValue);
break;
default:
throw new InvalidOperationException("Invalid ipv6 header unnamed field show name " + headerFieldShowName);
}
}
private int _currentExtensionHeaderIndex;
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, 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.Internal
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using MessageTemplates;
/// <summary>
/// Dictionary that combines the standard <see cref="LogEventInfo.Properties" /> with the
/// MessageTemplate-properties extracted from the <see cref="LogEventInfo.Message" />.
///
/// The <see cref="MessageProperties" /> are returned as the first items
/// in the collection, and in positional order.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
internal sealed class PropertiesDictionary : IDictionary<object, object>, IEnumerable<MessageTemplateParameter>
{
private struct PropertyValue
{
/// <summary>
/// Value of the property
/// </summary>
public readonly object Value;
/// <summary>
/// Is this a property of the message?
/// </summary>
public readonly bool IsMessageProperty;
/// <summary>
///
/// </summary>
/// <param name="value">Value of the property</param>
/// <param name="isMessageProperty">Is this a property of the message?</param>
public PropertyValue(object value, bool isMessageProperty)
{
Value = value;
IsMessageProperty = isMessageProperty;
}
}
/// <summary>
/// The properties of the logEvent
/// </summary>
private Dictionary<object, PropertyValue> _eventProperties;
/// <summary>
/// The properties extracted from the message
/// </summary>
private IList<MessageTemplateParameter> _messageProperties;
private DictionaryCollection _keyCollection;
private DictionaryCollection _valueCollection;
private IDictionary _eventContextAdapter;
/// <summary>
/// Injects the list of message-template-parameter into the IDictionary-interface
/// </summary>
/// <param name="parameterList">Message-template-parameters</param>
public PropertiesDictionary(IList<MessageTemplateParameter> parameterList = null)
{
if (parameterList?.Count > 0)
{
MessageProperties = parameterList;
}
}
private bool IsEmpty => (_eventProperties == null || _eventProperties.Count == 0) && (_messageProperties == null || _messageProperties.Count == 0);
public IDictionary EventContext => _eventContextAdapter ?? (_eventContextAdapter = new DictionaryAdapter<object, object>(this));
private Dictionary<object, PropertyValue> EventProperties
{
get
{
if (_eventProperties == null)
{
if (_messageProperties != null && _messageProperties.Count > 0)
{
_eventProperties = new Dictionary<object, PropertyValue>(_messageProperties.Count);
if (!InsertMessagePropertiesIntoEmptyDictionary(_messageProperties, _eventProperties))
{
_messageProperties = CreateUniqueMessagePropertiesListSlow(_messageProperties, _eventProperties);
}
}
else
{
_eventProperties = new Dictionary<object, PropertyValue>();
}
}
return _eventProperties;
}
}
public IList<MessageTemplateParameter> MessageProperties
{
get => _messageProperties ?? ArrayHelper.Empty<MessageTemplateParameter>();
internal set => _messageProperties = SetMessageProperties(value, _messageProperties);
}
private IList<MessageTemplateParameter> SetMessageProperties(IList<MessageTemplateParameter> newMessageProperties, IList<MessageTemplateParameter> oldMessageProperties)
{
if (_eventProperties == null && VerifyUniqueMessageTemplateParametersFast(newMessageProperties))
{
return newMessageProperties;
}
else
{
if (_eventProperties == null)
{
_eventProperties = new Dictionary<object, PropertyValue>(newMessageProperties.Count);
}
if (oldMessageProperties != null && _eventProperties.Count > 0)
{
RemoveOldMessageProperties(oldMessageProperties);
}
if (newMessageProperties != null && (_eventProperties.Count > 0 || !InsertMessagePropertiesIntoEmptyDictionary(newMessageProperties, _eventProperties)))
{
return CreateUniqueMessagePropertiesListSlow(newMessageProperties, _eventProperties);
}
else
{
return newMessageProperties;
}
}
}
private void RemoveOldMessageProperties(IList<MessageTemplateParameter> oldMessageProperties)
{
for (int i = 0; i < oldMessageProperties.Count; ++i)
{
if (_eventProperties.TryGetValue(oldMessageProperties[i].Name, out var propertyValue) && propertyValue.IsMessageProperty)
{
_eventProperties.Remove(oldMessageProperties[i].Name);
}
}
}
/// <inheritDoc/>
public object this[object key]
{
get
{
if (!IsEmpty && EventProperties.TryGetValue(key, out var valueItem))
{
return valueItem.Value;
}
throw new KeyNotFoundException();
}
set => EventProperties[key] = new PropertyValue(value, false);
}
/// <inheritDoc/>
public ICollection<object> Keys => KeyCollection;
/// <inheritDoc/>
public ICollection<object> Values => ValueCollection;
private DictionaryCollection KeyCollection
{
get
{
if (_keyCollection != null)
return _keyCollection;
if (IsEmpty)
return EmptyKeyCollection;
return _keyCollection ?? (_keyCollection = new DictionaryCollection(this, true));
}
}
private DictionaryCollection ValueCollection
{
get
{
if (_valueCollection != null)
return _valueCollection;
if (IsEmpty)
return EmptyValueCollection;
return _valueCollection ?? (_valueCollection = new DictionaryCollection(this, false));
}
}
private static readonly DictionaryCollection EmptyKeyCollection = new DictionaryCollection(new PropertiesDictionary(), true);
private static readonly DictionaryCollection EmptyValueCollection = new DictionaryCollection(new PropertiesDictionary(), false);
/// <inheritDoc/>
public int Count => (_eventProperties?.Count) ?? (_messageProperties?.Count) ?? 0;
/// <inheritDoc/>
public bool IsReadOnly => false;
/// <inheritDoc/>
public void Add(object key, object value)
{
EventProperties.Add(key, new PropertyValue(value, false));
}
/// <inheritDoc/>
public void Add(KeyValuePair<object, object> item)
{
Add(item.Key, item.Value);
}
/// <inheritDoc/>
public void Clear()
{
_eventProperties?.Clear();
if (_messageProperties != null)
_messageProperties = ArrayHelper.Empty<MessageTemplateParameter>();
}
/// <inheritDoc/>
public bool Contains(KeyValuePair<object, object> item)
{
if (!IsEmpty)
{
if (((IDictionary<object, PropertyValue>)EventProperties).Contains(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, false))))
return true;
if (((IDictionary<object, PropertyValue>)EventProperties).Contains(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, true))))
return true;
}
return false;
}
/// <inheritDoc/>
public bool ContainsKey(object key)
{
if (!IsEmpty)
{
return EventProperties.ContainsKey(key);
}
return false;
}
/// <inheritDoc/>
public void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (!IsEmpty)
{
foreach (var propertyItem in this)
{
array[arrayIndex++] = propertyItem;
}
}
}
/// <inheritDoc/>
public IEnumerator<KeyValuePair<object, object>> GetEnumerator()
{
if (IsEmpty)
return System.Linq.Enumerable.Empty<KeyValuePair<object, object>>().GetEnumerator();
return new DictionaryEnumerator(this);
}
/// <inheritDoc/>
IEnumerator IEnumerable.GetEnumerator()
{
if (IsEmpty)
return ArrayHelper.Empty<KeyValuePair<object, object>>().GetEnumerator();
return new DictionaryEnumerator(this);
}
/// <inheritDoc/>
public bool Remove(object key)
{
if (!IsEmpty)
{
return EventProperties.Remove(key);
}
return false;
}
/// <inheritDoc/>
public bool Remove(KeyValuePair<object, object> item)
{
if (!IsEmpty)
{
if (((IDictionary<object, PropertyValue>)EventProperties).Remove(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, false))))
return true;
if (((IDictionary<object, PropertyValue>)EventProperties).Remove(new KeyValuePair<object, PropertyValue>(item.Key, new PropertyValue(item.Value, true))))
return true;
}
return false;
}
/// <inheritDoc/>
public bool TryGetValue(object key, out object value)
{
if (!IsEmpty && EventProperties.TryGetValue(key, out var valueItem))
{
value = valueItem.Value;
return true;
}
value = null;
return false;
}
/// <summary>
/// Check if the message-template-parameters can be used directly without allocating a dictionary
/// </summary>
/// <param name="parameterList">Message-template-parameters</param>
/// <returns>Are all parameter names unique (true / false)</returns>
private static bool VerifyUniqueMessageTemplateParametersFast(IList<MessageTemplateParameter> parameterList)
{
if (parameterList == null || parameterList.Count == 0)
return true;
if (parameterList.Count > 10)
return false;
for (int i = 0; i < parameterList.Count - 1; ++i)
{
for (int j = i + 1; j < parameterList.Count; ++j)
{
if (parameterList[i].Name == parameterList[j].Name)
return false;
}
}
return true;
}
/// <summary>
/// Attempt to insert the message-template-parameters into an empty dictionary
/// </summary>
/// <param name="messageProperties">Message-template-parameters</param>
/// <param name="eventProperties">The initially empty dictionary</param>
/// <returns>Message-template-parameters was inserted into dictionary without trouble (true/false)</returns>
private static bool InsertMessagePropertiesIntoEmptyDictionary(IList<MessageTemplateParameter> messageProperties, Dictionary<object, PropertyValue> eventProperties)
{
try
{
for (int i = 0; i < messageProperties.Count; ++i)
{
eventProperties.Add(messageProperties[i].Name, new PropertyValue(messageProperties[i].Value, true));
}
return true; // We are done
}
catch (ArgumentException)
{
// Duplicate keys found, lets try again
for (int i = 0; i < messageProperties.Count; ++i)
{
//remove the duplicates
eventProperties.Remove(messageProperties[i].Name);
}
return false;
}
}
/// <summary>
/// Attempt to override the existing dictionary values using the message-template-parameters
/// </summary>
/// <param name="messageProperties">Message-template-parameters</param>
/// <param name="eventProperties">The already filled dictionary</param>
/// <returns>List of unique message-template-parameters</returns>
private static IList<MessageTemplateParameter> CreateUniqueMessagePropertiesListSlow(IList<MessageTemplateParameter> messageProperties, Dictionary<object, PropertyValue> eventProperties)
{
List<MessageTemplateParameter> messagePropertiesUnique = null;
for (int i = 0; i < messageProperties.Count; ++i)
{
if (eventProperties.TryGetValue(messageProperties[i].Name, out var valueItem) && valueItem.IsMessageProperty)
{
if (messagePropertiesUnique == null)
{
messagePropertiesUnique = new List<MessageTemplateParameter>(messageProperties.Count);
for (int j = 0; j < i; ++j)
{
messagePropertiesUnique.Add(messageProperties[j]);
}
}
continue; // Skip already exists
}
eventProperties[messageProperties[i].Name] = new PropertyValue(messageProperties[i].Value, true);
messagePropertiesUnique?.Add(messageProperties[i]);
}
return messagePropertiesUnique ?? messageProperties;
}
IEnumerator<MessageTemplateParameter> IEnumerable<MessageTemplateParameter>.GetEnumerator()
{
return new ParameterEnumerator(this);
}
private abstract class DictionaryEnumeratorBase : IDisposable
{
private readonly PropertiesDictionary _dictionary;
private int? _messagePropertiesEnumerator;
private bool _eventEnumeratorCreated;
private Dictionary<object, PropertyValue>.Enumerator _eventEnumerator;
protected DictionaryEnumeratorBase(PropertiesDictionary dictionary)
{
_dictionary = dictionary;
}
protected KeyValuePair<object, object> CurrentProperty
{
get
{
if (_messagePropertiesEnumerator.HasValue)
{
var property = _dictionary._messageProperties[_messagePropertiesEnumerator.Value];
return new KeyValuePair<object, object>(property.Name, property.Value);
}
if (_eventEnumeratorCreated)
return new KeyValuePair<object, object>(_eventEnumerator.Current.Key, _eventEnumerator.Current.Value.Value);
throw new InvalidOperationException();
}
}
protected MessageTemplateParameter CurrentParameter
{
get
{
if (_messagePropertiesEnumerator.HasValue)
{
return _dictionary._messageProperties[_messagePropertiesEnumerator.Value];
}
if (_eventEnumeratorCreated)
{
string parameterName = XmlHelper.XmlConvertToString(_eventEnumerator.Current.Key ?? string.Empty) ?? string.Empty;
return new MessageTemplateParameter(parameterName, _eventEnumerator.Current.Value.Value, null, CaptureType.Unknown);
}
throw new InvalidOperationException();
}
}
public bool MoveNext()
{
if (_messagePropertiesEnumerator.HasValue)
{
if (_messagePropertiesEnumerator.Value + 1 < _dictionary._messageProperties.Count)
{
// Move forward to a key that is not overriden
_messagePropertiesEnumerator = FindNextValidMessagePropertyIndex(_messagePropertiesEnumerator.Value + 1);
if (_messagePropertiesEnumerator.HasValue)
return true;
_messagePropertiesEnumerator = _dictionary._eventProperties.Count - 1;
}
if (HasEventProperties(_dictionary))
{
_messagePropertiesEnumerator = null;
_eventEnumerator = _dictionary._eventProperties.GetEnumerator();
_eventEnumeratorCreated = true;
return MoveNextValidEventProperty();
}
return false;
}
if (_eventEnumeratorCreated)
{
return MoveNextValidEventProperty();
}
if (HasMessageProperties(_dictionary))
{
// Move forward to a key that is not overriden
_messagePropertiesEnumerator = FindNextValidMessagePropertyIndex(0);
if (_messagePropertiesEnumerator.HasValue)
{
return true;
}
}
if (HasEventProperties(_dictionary))
{
_eventEnumerator = _dictionary._eventProperties.GetEnumerator();
_eventEnumeratorCreated = true;
return MoveNextValidEventProperty();
}
return false;
}
private static bool HasMessageProperties(PropertiesDictionary propertiesDictionary)
{
return propertiesDictionary._messageProperties != null && propertiesDictionary._messageProperties.Count > 0;
}
private static bool HasEventProperties(PropertiesDictionary propertiesDictionary)
{
return propertiesDictionary._eventProperties != null && propertiesDictionary._eventProperties.Count > 0;
}
private bool MoveNextValidEventProperty()
{
while (_eventEnumerator.MoveNext())
{
if (!_eventEnumerator.Current.Value.IsMessageProperty)
return true;
}
return false;
}
private int? FindNextValidMessagePropertyIndex(int startIndex)
{
if (_dictionary._eventProperties == null)
return startIndex;
for (int i = startIndex; i < _dictionary._messageProperties.Count; ++i)
{
if (_dictionary._eventProperties.TryGetValue(_dictionary._messageProperties[i].Name, out var valueItem) && valueItem.IsMessageProperty)
{
return i;
}
}
return null;
}
public void Dispose()
{
// Nothing to do
}
public void Reset()
{
_messagePropertiesEnumerator = null;
_eventEnumeratorCreated = false;
_eventEnumerator = default(Dictionary<object, PropertyValue>.Enumerator);
}
}
private class ParameterEnumerator : DictionaryEnumeratorBase, IEnumerator<MessageTemplateParameter>
{
/// <inheritDoc/>
public MessageTemplateParameter Current => CurrentParameter;
/// <inheritDoc/>
object IEnumerator.Current => CurrentParameter;
public ParameterEnumerator(PropertiesDictionary dictionary)
: base(dictionary)
{
}
}
private class DictionaryEnumerator : DictionaryEnumeratorBase, IEnumerator<KeyValuePair<object, object>>
{
/// <inheritDoc/>
public KeyValuePair<object, object> Current => CurrentProperty;
/// <inheritDoc/>
object IEnumerator.Current => CurrentProperty;
public DictionaryEnumerator(PropertiesDictionary dictionary)
: base(dictionary)
{
}
}
[DebuggerDisplay("Count = {Count}")]
private class DictionaryCollection : ICollection<object>
{
private readonly PropertiesDictionary _dictionary;
private readonly bool _keyCollection;
public DictionaryCollection(PropertiesDictionary dictionary, bool keyCollection)
{
_dictionary = dictionary;
_keyCollection = keyCollection;
}
/// <inheritDoc/>
public int Count => _dictionary.Count;
/// <inheritDoc/>
public bool IsReadOnly => true;
/// <summary>Will always throw, as collection is readonly</summary>
public void Add(object item) { throw new NotSupportedException(); }
/// <summary>Will always throw, as collection is readonly</summary>
public void Clear() { throw new NotSupportedException(); }
/// <summary>Will always throw, as collection is readonly</summary>
public bool Remove(object item) { throw new NotSupportedException(); }
/// <inheritDoc/>
public bool Contains(object item)
{
if (_keyCollection)
{
return _dictionary.ContainsKey(item);
}
if (!_dictionary.IsEmpty)
{
if (_dictionary.EventProperties.ContainsValue(new PropertyValue(item, false)))
return true;
if (_dictionary.EventProperties.ContainsValue(new PropertyValue(item, true)))
return true;
}
return false;
}
/// <inheritDoc/>
public void CopyTo(object[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (!_dictionary.IsEmpty)
{
foreach (var propertyItem in _dictionary)
{
array[arrayIndex++] = _keyCollection ? propertyItem.Key : propertyItem.Value;
}
}
}
/// <inheritDoc/>
public IEnumerator<object> GetEnumerator()
{
return new DictionaryCollectionEnumerator(_dictionary, _keyCollection);
}
/// <inheritDoc/>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class DictionaryCollectionEnumerator : DictionaryEnumeratorBase, IEnumerator<object>
{
private readonly bool _keyCollection;
public DictionaryCollectionEnumerator(PropertiesDictionary dictionary, bool keyCollection)
: base(dictionary)
{
_keyCollection = keyCollection;
}
/// <inheritDoc/>
public object Current => _keyCollection ? CurrentProperty.Key : CurrentProperty.Value;
}
}
}
}
| |
namespace Ioke.Lang {
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Ioke.Lang.Util;
public class FileSystem {
public static IList<string> Glob(Runtime runtime, string text) {
return runtime.globber.PushGlob(runtime.CurrentWorkingDirectory, text, 0);
}
public class IokeFile : IokeIO {
// private FileInfo file;
public IokeFile(FileInfo file) : base(null, null) {
// this.file = file;
try {
if(file != null) {
this.writer = new StreamWriter(file.OpenWrite());
}
} catch(IOException) {
}
}
public override void Init(IokeObject obj) {
Runtime runtime = obj.runtime;
obj.Kind = "FileSystem File";
obj.RegisterMethod(runtime.NewNativeMethod("Closes any open stream to this file",
new TypeCheckingNativeMethod.WithNoArguments("close", obj,
(method, on, args, keywords, context, message) => {
try {
TextWriter writer = IokeIO.GetWriter(on);
if(writer != null) {
writer.Close();
}
} catch(IOException) {
}
return context.runtime.nil;
})));
}
}
public static void Init(IokeObject obj) {
Runtime runtime = obj.runtime;
obj.Kind = "FileSystem";
IokeObject file = new IokeObject(runtime, "represents a file in the file system", new IokeFile(null));
file.MimicsWithoutCheck(runtime.Io);
file.Init();
obj.RegisterCell("File", file);
obj.RegisterMethod(runtime.NewNativeMethod("Tries to interpret the given arguments as strings describing file globs, and returns an array containing the result of applying these globs.",
new NativeMethod("[]", DefaultArgumentsDefinition.builder()
.WithRest("globTexts")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
var dirs = FileSystem.Glob(context.runtime, IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0])));
var result = new SaneArrayList();
foreach(string s in dirs) {
result.Add(context.runtime.NewText(s));
}
return context.runtime.NewList(result);
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes one string argument and returns true if it's the relative or absolute name of a directory, and false otherwise.",
new NativeMethod("directory?", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("directoryName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0]));
DirectoryInfo f = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
f = new DirectoryInfo(name);
} else {
f = new DirectoryInfo(Path.Combine(context.runtime.CurrentWorkingDirectory, name));
}
return f.Exists ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes one string argument that should be a file name, and returns a text of the contents of this file.",
new NativeMethod("readFully", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("fileName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0]));
FileInfo f = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
f = new FileInfo(name);
} else {
f = new FileInfo(Path.Combine(context.runtime.CurrentWorkingDirectory, name));
}
return context.runtime.NewText(File.ReadAllText(f.FullName));
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes one string argument and returns true if it's the relative or absolute name of a file, and false otherwise.",
new NativeMethod("file?", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("fileName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0]));
FileInfo f = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
f = new FileInfo(name);
} else {
f = new FileInfo(Path.Combine(context.runtime.CurrentWorkingDirectory, name));
}
return f.Exists ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes one string argument and returns true if it's the relative or absolute name of something that exists.",
new NativeMethod("exists?", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("entryName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0]));
string nx = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
nx = name;
} else {
nx = Path.Combine(context.runtime.CurrentWorkingDirectory, name);
}
return (new FileInfo(nx).Exists || new DirectoryInfo(nx).Exists) ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes one string argument that should be the path of a file or directory, and returns the parent of it - or nil if there is no parent.",
new NativeMethod("parentOf", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("entryName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = Text.GetText(args[0]);
string nx;
if(IokeSystem.IsAbsoluteFileName(name)) {
nx = name;
} else {
nx = Path.Combine(context.runtime.CurrentWorkingDirectory, name);
}
string parent = Path.GetDirectoryName(nx);
if(parent == null) {
return context.runtime.nil;
}
string cwd = context.runtime.CurrentWorkingDirectory;
if(!IokeSystem.IsAbsoluteFileName(name) && parent.Equals(cwd)) {
return context.runtime.nil;
}
if(parent.StartsWith(cwd)) {
parent = parent.Substring(cwd.Length+1);
}
return context.runtime.NewText(parent);
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes a file name and a lexical block - opens the file, ensures that it exists and then yields the file to the block. Finally it closes the file after the block has finished executing, and then returns the result of the block.",
new NativeMethod("withOpenFile", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("fileName")
.WithRequiredPositional("code")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0]));
FileInfo f = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
f = new FileInfo(name);
} else {
f = new FileInfo(Path.Combine(context.runtime.CurrentWorkingDirectory, name));
}
try {
if(!f.Exists) {
using(FileStream fs = File.Create(f.FullName)) {
}
}
} catch(IOException) {
}
IokeObject ff = context.runtime.NewFile(context, f);
object result = context.runtime.nil;
try {
result = Interpreter.Send(context.runtime.callMessage, context, args[1], ff);
} finally {
Interpreter.Send(context.runtime.closeMessage, context, ff);
}
return result;
})));
obj.RegisterMethod(runtime.NewNativeMethod("Copies a file. Takes two text arguments, where the first is the name of the file to copy and the second is the name of the destination. If the destination is a directory, the file will be copied with the same name, and if it's a filename, the file will get a new name",
new NativeMethod("copyFile", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("fileName")
.WithRequiredPositional("destination")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = Text.GetText(args[0]);
FileInfo f = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
f = new FileInfo(name);
} else {
f = new FileInfo(Path.Combine(context.runtime.CurrentWorkingDirectory, name));
}
string name2 = Text.GetText(args[1]);
string nx = null;
if(IokeSystem.IsAbsoluteFileName(name2)) {
nx = name2;
} else {
nx = Path.Combine(context.runtime.CurrentWorkingDirectory, name2);
}
if(new DirectoryInfo(nx).Exists) {
nx = Path.Combine(nx, f.Name);
}
try {
File.Copy(f.FullName, nx, true);
} catch (IOException) {
}
return context.runtime.nil;
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes one string argument and creates a directory with that name. It also takes an optional second argument. If it's true, will try to create all necessary directories inbetween. Default is false. Will signal a condition if the directory already exists, or if there's a file with that name.",
new NativeMethod("createDirectory!", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("directoryName")
.WithOptionalPositional("createPath", "false")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0]));
DirectoryInfo f = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
f = new DirectoryInfo(name);
} else {
f = new DirectoryInfo(Path.Combine(context.runtime.CurrentWorkingDirectory, name));
}
if(f.Exists || new FileInfo(f.FullName).Exists) {
string msg = null;
if(f.Exists) {
msg = "Can't create directory '" + name + "' since there already exists a directory with that name";
} else {
msg = "Can't create directory '" + name + "' since there already exists a file with that name";
}
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"IO"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("text", runtime.NewText(msg));
runtime.WithReturningRestart("ignore", context, ()=>{runtime.ErrorCondition(condition);});
}
Directory.CreateDirectory(f.FullName);
return context.runtime.nil;
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes one string argument and removes a directory with that name. Will signal a condition if the directory doesn't exist, or if there's a file with that name.",
new NativeMethod("removeDirectory!", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("directoryName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0]));
string nf = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
nf = name;
} else {
nf = Path.Combine(context.runtime.CurrentWorkingDirectory, name);
}
if(!(new DirectoryInfo(nf).Exists) || new FileInfo(nf).Exists) {
string msg = null;
if(!(new DirectoryInfo(nf).Exists)) {
msg = "Can't remove directory '" + name + "' since it doesn't exist";
} else {
msg = "Can't remove directory '" + name + "' since it is a file";
}
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"IO"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("text", runtime.NewText(msg));
runtime.WithReturningRestart("ignore", context, ()=>{runtime.ErrorCondition(condition);});
}
Directory.Delete(nf);
return context.runtime.nil;
})));
obj.RegisterMethod(runtime.NewNativeMethod("Takes one string argument and removes a file with that name. Will signal a condition if the file doesn't exist, or if there's a directory with that name.",
new NativeMethod("removeFile!", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("fileName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = IokeSystem.WithReplacedHomeDirectory(Text.GetText(args[0]));
string nf = null;
if(IokeSystem.IsAbsoluteFileName(name)) {
nf = name;
} else {
nf = Path.Combine(context.runtime.CurrentWorkingDirectory, name);
}
if(!(new FileInfo(nf).Exists) || new DirectoryInfo(nf).Exists) {
string msg = null;
if(!(new FileInfo(nf).Exists)) {
msg = "Can't remove file '" + name + "' since it doesn't exist";
} else {
msg = "Can't remove file '" + name + "' since it is a directory";
}
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
message,
context,
"Error",
"IO"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("text", runtime.NewText(msg));
runtime.WithReturningRestart("ignore", context, ()=>{runtime.ErrorCondition(condition);});
}
File.Delete(nf);
return context.runtime.nil;
})));
}
}
}
| |
namespace EntityData.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ContinuousFutures",
c => new
{
ID = c.Int(nullable: false, identity: true),
InstrumentID = c.Int(nullable: false),
UnderlyingSymbolID = c.Int(nullable: false),
Month = c.Int(nullable: false),
RolloverType = c.Int(nullable: false),
RolloverDays = c.Int(nullable: false),
AdjustmentMode = c.Int(nullable: false),
UseJan = c.Boolean(nullable: false),
UseFeb = c.Boolean(nullable: false),
UseMar = c.Boolean(nullable: false),
UseApr = c.Boolean(nullable: false),
UseMay = c.Boolean(nullable: false),
UseJun = c.Boolean(nullable: false),
UseJul = c.Boolean(nullable: false),
UseAug = c.Boolean(nullable: false),
UseSep = c.Boolean(nullable: false),
UseOct = c.Boolean(nullable: false),
UseNov = c.Boolean(nullable: false),
UseDec = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Instruments", t => t.InstrumentID, cascadeDelete: true)
.ForeignKey("dbo.UnderlyingSymbols", t => t.UnderlyingSymbolID, cascadeDelete: true)
.Index(t => t.InstrumentID)
.Index(t => t.UnderlyingSymbolID);
CreateTable(
"dbo.Instruments",
c => new
{
ID = c.Int(nullable: false, identity: true),
Symbol = c.String(maxLength: 100, unicode: false, storeType: "nvarchar"),
UnderlyingSymbol = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
Name = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
PrimaryExchangeID = c.Int(),
ExchangeID = c.Int(),
Type = c.Int(nullable: false),
Multiplier = c.Int(),
Expiration = c.DateTime(precision: 0),
OptionType = c.Int(),
Strike = c.Decimal(precision: 16, scale: 8),
Currency = c.String(maxLength: 25, unicode: false, storeType: "nvarchar"),
MinTick = c.Decimal(precision: 16, scale: 8),
Industry = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
Category = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
Subcategory = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
IsContinuousFuture = c.Boolean(nullable: false),
ValidExchanges = c.String(unicode: false),
DatasourceID = c.Int(nullable: false),
ContinuousFutureID = c.Int(),
SessionsSource = c.Int(nullable: false),
SessionTemplateID = c.Int(),
DatasourceSymbol = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.ContinuousFutures", t => t.ContinuousFutureID)
.ForeignKey("dbo.Datasources", t => t.DatasourceID, cascadeDelete: true)
.ForeignKey("dbo.Exchanges", t => t.ExchangeID)
.ForeignKey("dbo.Exchanges", t => t.PrimaryExchangeID)
.Index(t => t.ContinuousFutureID)
.Index(t => t.DatasourceID)
.Index(t => t.ExchangeID)
.Index(t => t.PrimaryExchangeID);
CreateIndex(
"dbo.Instruments",
new string[5] { "Symbol", "DatasourceID", "ExchangeID", "Expiration", "Strike" },
unique: true);
CreateTable(
"dbo.Datasources",
c => new
{
ID = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 100, unicode: false, storeType: "nvarchar"),
})
.PrimaryKey(t => t.ID);
CreateIndex(
"dbo.Datasources",
"Name",
unique: true);
CreateTable(
"dbo.Exchanges",
c => new
{
ID = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 100, unicode: false, storeType: "nvarchar"),
Timezone = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
LongName = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
})
.PrimaryKey(t => t.ID);
CreateIndex(
"dbo.Exchanges",
"Name",
unique: true);
CreateTable(
"dbo.exchangesessions",
c => new
{
ID = c.Int(nullable: false, identity: true),
OpeningTime = c.Time(nullable: false, precision: 3),
ClosingTime = c.Time(nullable: false, precision: 3),
ExchangeID = c.Int(nullable: false),
IsSessionEnd = c.Boolean(nullable: false),
OpeningDay = c.Int(nullable: false),
ClosingDay = c.Int(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Exchanges", t => t.ExchangeID, cascadeDelete: true)
.Index(t => t.ExchangeID);
CreateTable(
"dbo.instrumentsessions",
c => new
{
ID = c.Int(nullable: false, identity: true),
OpeningTime = c.Time(nullable: false, precision: 3),
ClosingTime = c.Time(nullable: false, precision: 3),
InstrumentID = c.Int(nullable: false),
IsSessionEnd = c.Boolean(nullable: false),
OpeningDay = c.Int(nullable: false),
ClosingDay = c.Int(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Instruments", t => t.InstrumentID, cascadeDelete: true)
.Index(t => t.InstrumentID);
CreateTable(
"dbo.Tags",
c => new
{
ID = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
})
.PrimaryKey(t => t.ID);
CreateTable(
"dbo.UnderlyingSymbols",
c => new
{
ID = c.Int(nullable: false, identity: true),
Symbol = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
ExpirationRule = c.Binary(),
})
.PrimaryKey(t => t.ID);
CreateTable(
"dbo.SessionTemplates",
c => new
{
ID = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 255, unicode: false, storeType: "nvarchar"),
})
.PrimaryKey(t => t.ID);
CreateTable(
"dbo.templatesessions",
c => new
{
ID = c.Int(nullable: false, identity: true),
OpeningTime = c.Time(nullable: false, precision: 3),
ClosingTime = c.Time(nullable: false, precision: 3),
TemplateID = c.Int(nullable: false),
IsSessionEnd = c.Boolean(nullable: false),
OpeningDay = c.Int(nullable: false),
ClosingDay = c.Int(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.SessionTemplates", t => t.TemplateID, cascadeDelete: true)
.Index(t => t.TemplateID);
CreateTable(
"dbo.tag_map",
c => new
{
InstrumentID = c.Int(nullable: false),
TagID = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.InstrumentID, t.TagID })
.ForeignKey("dbo.Instruments", t => t.InstrumentID, cascadeDelete: true)
.ForeignKey("dbo.Tags", t => t.TagID, cascadeDelete: true)
.Index(t => t.InstrumentID)
.Index(t => t.TagID);
}
public override void Down()
{
DropForeignKey("dbo.templatesessions", "TemplateID", "dbo.SessionTemplates");
DropForeignKey("dbo.ContinuousFutures", "UnderlyingSymbolID", "dbo.UnderlyingSymbols");
DropForeignKey("dbo.ContinuousFutures", "InstrumentID", "dbo.Instruments");
DropForeignKey("dbo.tag_map", "TagID", "dbo.Tags");
DropForeignKey("dbo.tag_map", "InstrumentID", "dbo.Instruments");
DropForeignKey("dbo.instrumentsessions", "InstrumentID", "dbo.Instruments");
DropForeignKey("dbo.Instruments", "PrimaryExchangeID", "dbo.Exchanges");
DropForeignKey("dbo.Instruments", "ExchangeID", "dbo.Exchanges");
DropForeignKey("dbo.exchangesessions", "ExchangeID", "dbo.Exchanges");
DropForeignKey("dbo.Instruments", "DatasourceID", "dbo.Datasources");
DropForeignKey("dbo.Instruments", "ContinuousFutureID", "dbo.ContinuousFutures");
DropIndex("dbo.templatesessions", new[] { "TemplateID" });
DropIndex("dbo.ContinuousFutures", new[] { "UnderlyingSymbolID" });
DropIndex("dbo.ContinuousFutures", new[] { "InstrumentID" });
DropIndex("dbo.tag_map", new[] { "TagID" });
DropIndex("dbo.tag_map", new[] { "InstrumentID" });
DropIndex("dbo.instrumentsessions", new[] { "InstrumentID" });
DropIndex("dbo.Instruments", new[] { "PrimaryExchangeID" });
DropIndex("dbo.Instruments", new[] { "ExchangeID" });
DropIndex("dbo.exchangesessions", new[] { "ExchangeID" });
DropIndex("dbo.Instruments", new[] { "DatasourceID" });
DropIndex("dbo.Instruments", new[] { "ContinuousFutureID" });
DropTable("dbo.tag_map");
DropTable("dbo.templatesessions");
DropTable("dbo.SessionTemplates");
DropTable("dbo.UnderlyingSymbols");
DropTable("dbo.Tags");
DropTable("dbo.instrumentsessions");
DropTable("dbo.exchangesessions");
DropTable("dbo.Exchanges");
DropTable("dbo.Datasources");
DropTable("dbo.Instruments");
DropTable("dbo.ContinuousFutures");
}
}
}
| |
/*
* Deed API
*
* Land Registry Deed API
*
* OpenAPI spec version: 2.3.1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using RestSharp;
namespace IO.Swagger.Client
{
/// <summary>
/// API client is mainly responsible for making the HTTP call to the API backend.
/// </summary>
public partial class ApiClient
{
private JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
/// <summary>
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
partial void InterceptRequest(IRestRequest request);
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration and base path (https://api.landregistry.gov.uk/v1).
/// </summary>
public ApiClient()
{
Configuration = Configuration.Default;
RestClient = new RestClient("https://api.landregistry.gov.uk/v1");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default base path (https://api.landregistry.gov.uk/v1).
/// </summary>
/// <param name="config">An instance of Configuration.</param>
public ApiClient(Configuration config = null)
{
if (config == null)
Configuration = Configuration.Default;
else
Configuration = config;
RestClient = new RestClient("https://api.landregistry.gov.uk/v1");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default configuration.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(String basePath = "https://api.landregistry.gov.uk/v1")
{
if (String.IsNullOrEmpty(basePath))
throw new ArgumentException("basePath cannot be empty");
RestClient = new RestClient(basePath);
Configuration = Configuration.Default;
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The default API client.</value>
[Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")]
public static ApiClient Default;
/// <summary>
/// Gets or sets the Configuration.
/// </summary>
/// <value>An instance of the Configuration.</value>
public Configuration Configuration { get; set; }
/// <summary>
/// Gets or sets the RestClient.
/// </summary>
/// <value>An instance of the RestClient</value>
public RestClient RestClient { get; set; }
// Creates and sets up a RestRequest prior to a call.
private RestRequest PrepareRequest(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = new RestRequest(path, method);
// add path parameter, if any
foreach(var param in pathParams)
request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(var param in fileParams)
{
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
}
if (postBody != null) // http body (model or byte[]) parameter
{
if (postBody.GetType() == typeof(String))
{
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
}
else if (postBody.GetType() == typeof(byte[]))
{
request.AddParameter(contentType, postBody, ParameterType.RequestBody);
}
}
return request;
}
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content Type of the request</param>
/// <returns>Object</returns>
public Object CallApi(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
// set timeout
RestClient.Timeout = Configuration.Timeout;
// set user agent
RestClient.UserAgent = Configuration.UserAgent;
InterceptRequest(request);
var response = RestClient.Execute(request);
InterceptResponse(request, response);
return (Object) response;
}
/// <summary>
/// Makes the asynchronous HTTP request.
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content type.</param>
/// <returns>The Task instance.</returns>
public async System.Threading.Tasks.Task<Object> CallApiAsync(
String path, RestSharp.Method method, Dictionary<String, String> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
InterceptRequest(request);
var response = await RestClient.ExecuteTaskAsync(request);
InterceptResponse(request, response);
return (Object)response;
}
/// <summary>
/// Escape string (url-encoded).
/// </summary>
/// <param name="str">String to be escaped.</param>
/// <returns>Escaped string.</returns>
public string EscapeString(string str)
{
return UrlEncode(str);
}
/// <summary>
/// Create FileParameter based on Stream.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="stream">Input stream.</param>
/// <returns>FileParameter.</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream)
return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name));
else
return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided");
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <returns>Formatted string.</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTime)obj).ToString (Configuration.DateTimeFormat);
else if (obj is DateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat);
else if (obj is IList)
{
var flattenedString = new StringBuilder();
foreach (var param in (IList)obj)
{
if (flattenedString.Length > 0)
flattenedString.Append(",");
flattenedString.Append(param);
}
return flattenedString.ToString();
}
else
return Convert.ToString (obj);
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(IRestResponse response, Type type)
{
IList<Parameter> headers = response.Headers;
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
if (type == typeof(Stream))
{
if (headers != null)
{
var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, response.RawBytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(response.RawBytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return ConvertType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an input (model) into JSON string
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>JSON string.</returns>
public String Serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public String SelectHeaderContentType(String[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public String SelectHeaderAccept(String[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return String.Join(",", accepts);
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">String to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Dynamically cast the object into target type.
/// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
/// </summary>
/// <param name="source">Object to be casted</param>
/// <param name="dest">Target type</param>
/// <returns>Casted object</returns>
public static dynamic ConvertType(dynamic source, Type dest)
{
return Convert.ChangeType(source, dest);
}
/// <summary>
/// Convert stream to byte array
/// Credit/Ref: http://stackoverflow.com/a/221941/677735
/// </summary>
/// <param name="input">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">String to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
if (match.Success)
{
return match.Groups[1].Value;
}
else
{
return filename;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Fabric;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Actors;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Remoting.V1.FabricTransport.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using ServiceFabric.PubSubActors.Helpers;
using ServiceFabric.PubSubActors.Interfaces;
using ServiceFabric.PubSubActors.State;
namespace ServiceFabric.PubSubActors
{
/// <remarks>
/// Base class for a <see cref="StatefulService"/> that serves as a Broker that accepts messages from Actors & Services calling
/// <see cref="PublisherActorExtensions.PublishMessageAsync"/> and forwards them to <see cref="ISubscriberActor"/> Actors and
/// <see cref="ISubscriberService"/> Services. Every message type is mapped to one of the partitions of this service.
/// </remarks>
public abstract class BrokerServiceBase : StatefulService, IBrokerService
{
#region Public Constants
/// <summary>
/// The name that the <see cref="ServiceReplicaListener"/> instance will get.
/// </summary>
public const string ListenerName = BrokerServiceListenerSettings.ListenerName;
#endregion Public Constants
#region Protected Constants
/// <summary>
/// Gets the state key for all subscriber queues.
/// </summary>
protected const string Subscribers = "Queues";
#endregion Protected Constants
#region Private Fields
private readonly ManualResetEventSlim _initializer = new ManualResetEventSlim(false);
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
private readonly ConcurrentDictionary<string, ReferenceWrapper> _queues = new ConcurrentDictionary<string, ReferenceWrapper>();
#endregion Private Fields
#region Protected Constructors
/// <summary>
/// Creates a new instance using the provided context and registers this instance for automatic discovery if needed.
/// </summary>
/// <param name="serviceContext"></param>
/// <param name="enableAutoDiscovery"></param>
protected BrokerServiceBase(StatefulServiceContext serviceContext, bool enableAutoDiscovery = true)
: base(serviceContext)
{
if (enableAutoDiscovery)
{
new BrokerServiceLocator().RegisterAsync(Context.ServiceName)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
}
/// <summary>
/// Creates a new instance using the provided context and registers this instance for automatic discovery if needed.
/// </summary>
/// <param name="serviceContext"></param>
/// <param name="reliableStateManagerReplica"></param>
/// <param name="enableAutoDiscovery"></param>
protected BrokerServiceBase(StatefulServiceContext serviceContext,
IReliableStateManagerReplica2 reliableStateManagerReplica, bool enableAutoDiscovery = true)
: base(serviceContext, reliableStateManagerReplica)
{
if (enableAutoDiscovery)
{
new BrokerServiceLocator().RegisterAsync(Context.ServiceName)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
}
#endregion Protected Constructors
#region Protected Properties
/// <summary>
/// When Set, this callback will be used to trace Service messages to.
/// </summary>
protected Action<string> ServiceEventSourceMessageCallback { get; set; }
/// <summary>
/// Gets or sets the interval to wait before starting to publish messages. (Default: 5s after Activation)
/// </summary>
protected TimeSpan DueTime { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>
/// Gets or sets the interval to wait between batches of publishing messages. (Default: 5s)
/// </summary>
protected TimeSpan Period { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>
/// Get or Sets the maximum period to process messages before allowing enqueuing
/// </summary>
protected TimeSpan MaxProcessingPeriod { get; set; } = TimeSpan.FromSeconds(3);
/// <summary>
/// Gets or Sets the maximum number of messages to de-queue in one iteration of process queue
/// </summary>
protected long MaxDequeuesInOneIteration { get; set; } = 100;
#endregion Protected Properties
#region Public Methods
/// <summary>
/// Registers an Actor as a subscriber for messages.
/// </summary>
/// <param name="actor">Reference to the actor to register.</param>
/// <param name="messageTypeName">Full type name of message object.</param>
public async Task RegisterSubscriberAsync(ActorReference actor, string messageTypeName)
{
var actorReference = new ActorReferenceWrapper(actor);
await RegisterSubscriberAsync(actorReference, messageTypeName);
}
/// <summary>
/// Registers an Actor as a subscriber for messages that can be correlated to the subscriber.
/// </summary>
/// <param name="actor">Reference to the actor to register.</param>
/// <param name="messageTypeName">The full type name of the message to subscribe to.</param>
/// <param name="correlationId">
/// The correlation identifier to use to match messages to a specific subscriber (i.e., a simple message filter).
/// </param>
/// <returns>Task.</returns>
public async Task RegisterCorrelatedSubscriberAsync(ActorReference actor, string messageTypeName, string correlationId)
{
var actorReference = new ActorReferenceWrapper(actor, correlationId);
await RegisterSubscriberAsync(actorReference, messageTypeName);
}
/// <summary>
/// Unregisters an Actor as a subscriber for messages.
/// </summary>
/// <param name="actor">Reference to the actor to unsubscribe.</param>
/// <param name="messageTypeName">Full type name of message object.</param>
/// <param name="flushQueue">Publish any remaining messages.</param>
public async Task UnregisterSubscriberAsync(ActorReference actor, string messageTypeName, bool flushQueue)
{
var actorReference = new ActorReferenceWrapper(actor);
await UnregisterSubscriberAsync(actorReference, messageTypeName);
}
/// <summary>
/// Unregisters an Actor as a subscriber for messages that can be correlated to the subscriber.
/// </summary>
/// <param name="actor">Reference to the actor to unsubscribe.</param>
/// <param name="messageTypeName">Full type name of message object.</param>
/// <param name="correlationId">
/// The correlation identifier to use to match messages to a specific subscriber (i.e., a simple message filter).
/// </param>
/// <param name="flushQueue">Publish any remaining messages.</param>
public async Task UnregisterCorrelatedSubscriberAsync(ActorReference actor, string messageTypeName, string correlationId, bool flushQueue)
{
var actorReference = new ActorReferenceWrapper(actor, correlationId);
await UnregisterSubscriberAsync(actorReference, messageTypeName);
}
/// <summary>
/// Registers a service as a subscriber for messages.
/// </summary>
/// <param name="messageTypeName">Full type name of message object.</param>
/// <param name="service">Reference to the service to register.</param>
public async Task RegisterServiceSubscriberAsync(ServiceReference service, string messageTypeName)
{
var serviceReference = new ServiceReferenceWrapper(service);
await RegisterSubscriberAsync(serviceReference, messageTypeName);
}
/// <summary>
/// Registers a service as a subscriber for messages that can be correlated to the subscriber.
/// </summary>
/// <param name="messageTypeName">Full type name of message object.</param>
/// <param name="service">Reference to the service to register.</param>
/// <param name="correlationId">
/// The correlation identifier to use to match messages to a specific subscriber (i.e., a simple message filter).
/// </param>
public async Task RegisterCorrelatedServiceSubscriberAsync(ServiceReference service, string messageTypeName, string correlationId)
{
var serviceReference = new ServiceReferenceWrapper(service, correlationId);
await RegisterSubscriberAsync(serviceReference, messageTypeName);
}
/// <summary>
/// Unregisters a service as a subscriber for messages.
/// </summary>
/// <param name="messageTypeName">Full type name of message object.</param>
/// <param name="service">Reference to the actor to unsubscribe.</param>
/// <param name="flushQueue">Publish any remaining messages.</param>
public async Task UnregisterServiceSubscriberAsync(ServiceReference service, string messageTypeName, bool flushQueue)
{
var serviceReference = new ServiceReferenceWrapper(service);
await UnregisterSubscriberAsync(serviceReference, messageTypeName);
}
/// <summary>
/// Unregisters a service as a subscriber for messages that can be correlated to the subscriber.
/// </summary>
/// <param name="messageTypeName">Full type name of message object.</param>
/// <param name="service">Reference to the actor to unsubscribe.</param>
/// <param name="correlationId">
/// The correlation identifier to use to match messages to a specific subscriber (i.e., a simple message filter).
/// </param>
/// <param name="flushQueue">Publish any remaining messages.</param>
public async Task UnregisterCorrelatedServiceSubscriberAsync(ServiceReference service, string messageTypeName, string correlationId, bool flushQueue)
{
var serviceReference = new ServiceReferenceWrapper(service, correlationId);
await UnregisterSubscriberAsync(serviceReference, messageTypeName);
}
/// <summary>
/// Takes a published message and forwards it (indirectly) to all Subscribers.
/// </summary>
/// <param name="message">The message to publish</param>
/// <returns></returns>
public async Task PublishMessageAsync(MessageWrapper message)
{
await WaitForInitializeAsync(CancellationToken.None);
var myDictionary = await TimeoutRetryHelper.Execute((token, state) => StateManager.GetOrAddAsync<IReliableDictionary<string, BrokerServiceState>>(message.MessageType));
var subscribers = await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
var result = await myDictionary.TryGetValueAsync(tx, Subscribers);
if (result.HasValue)
{
// If specified, apply message filter so that we only publish to subscribers that can be correlated to this message. Subscribers
// that do not define a message filter will receive all messages. Those that do define a message filter will only receive messages
// that match the filter.
return result.Value.Subscribers.Where(r => r.ServiceOrActorReference.ShouldPublish(message)).ToArray();
}
return null;
});
if (subscribers == null || subscribers.Length == 0) return;
ServiceEventSourceMessage($"Publishing message '{message.MessageType}' to {subscribers.Length} subscribers.");
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
foreach (var subscriber in subscribers)
{
await EnqueueMessageAsync(message, subscriber, tx);
}
ServiceEventSourceMessage($"Published message '{message.MessageType}' to {subscribers.Length} subscribers.");
});
}
#endregion Public Methods
#region Protected Methods
protected abstract Task EnqueueMessageAsync(MessageWrapper message, Reference subscriber, ITransaction tx);
/// <summary>
/// Starts a loop that processes all queued messages.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected override async Task RunAsync(CancellationToken cancellationToken)
{
await WaitForInitializeAsync(cancellationToken);
ServiceEventSourceMessage($"Sleeping for {DueTime.TotalMilliseconds}ms before starting to publish messages.");
await Task.Delay(DueTime, cancellationToken);
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
//process messages for given time, then allow other transactions to enqueue messages
var cts = new CancellationTokenSource(MaxProcessingPeriod);
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
try
{
var elements = _queues.ToArray();
var tasks = new List<Task>(elements.Length);
foreach (var element in elements)
{
var subscriber = element.Value;
string queueName = element.Key;
tasks.Add(ProcessQueues(linkedTokenSource.Token, subscriber, queueName));
}
await Task.WhenAll(tasks);
}
catch (TaskCanceledException)
{//swallow and move on..
}
catch (OperationCanceledException)
{//swallow and move on..
}
catch (ObjectDisposedException)
{//swallow and move on..
}
catch (Exception ex)
{
ServiceEventSourceMessage($"Exception caught while processing messages:'{ex.Message}'");
//swallow and move on..
}
finally
{
linkedTokenSource.Dispose();
}
await Task.Delay(Period, cancellationToken);
}
// ReSharper disable once FunctionNeverReturns
}
/// <inheritdoc />
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
//add the pubsub listener
yield return new ServiceReplicaListener(context => new FabricTransportServiceRemotingListener(context, this), ListenerName);
}
/// <summary>
/// Sends out queued messages for the provided queue.
/// </summary>
/// <param name="cancellationToken"></param>
/// <param name="subscriber"></param>
/// <param name="queueName"></param>
/// <returns></returns>
protected abstract Task ProcessQueues(CancellationToken cancellationToken, ReferenceWrapper subscriber, string queueName);
/// <summary>
/// Outputs the provided message to the <see cref="ServiceEventSourceMessageCallback" /> if it's configured.
/// </summary>
/// <param name="message"></param>
/// <param name="caller"></param>
protected void ServiceEventSourceMessage(string message, [CallerMemberName] string caller = "unknown")
{
ServiceEventSourceMessageCallback?.Invoke($"{caller} - {message}");
}
protected abstract Task CreateQueueAsync(ITransaction tx, string queueName);
#endregion Protected Methods
#region Private Methods
/// <summary>
/// Creates a queuename to use for this reference. (message specific)
/// </summary>
/// <returns></returns>
private static string CreateDeadLetterQueueName(ReferenceWrapper reference, string messageTypeName)
{
return $"{messageTypeName}_{reference.GetDeadLetterQueueName()}";
}
/// <summary>
/// Creates a deadletter queuename to use for this reference. (not message specific)
/// </summary>
/// <returns></returns>
private static string CreateQueueName(ReferenceWrapper reference, string messageTypeName)
{
return $"{messageTypeName}_{reference.GetQueueName()}";
}
/// <summary>
/// Blocks the calling thread until <see cref="InitializeAsync" /> is complete.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task WaitForInitializeAsync(CancellationToken cancellationToken)
{
if (_initializer.IsSet) return;
await Task.Run(() => InitializeAsync(cancellationToken), cancellationToken);
_initializer.Wait(cancellationToken);
}
/// <summary>
/// Loads all registered message queues from state and keeps them in memory. Avoids some locks in the statemanager.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task InitializeAsync(CancellationToken cancellationToken)
{
if (_initializer.IsSet) return;
try
{
_semaphore.Wait(cancellationToken);
if (_initializer.IsSet) return;
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
_queues.Clear();
var enumerator = StateManager.GetAsyncEnumerator();
while (await enumerator.MoveNextAsync(cancellationToken))
{
var current = enumerator.Current as IReliableDictionary<string, BrokerServiceState>;
if (current == null) continue;
var result = await current.TryGetValueAsync(tx, Subscribers);
if (!result.HasValue) continue;
var subscribers = result.Value.Subscribers.ToList();
foreach (var subscriber in subscribers)
{
_queues.TryAdd(subscriber.QueueName, subscriber.ServiceOrActorReference);
}
}
}, cancellationToken: cancellationToken);
_initializer.Set();
}
finally
{
_semaphore.Release();
}
}
/// <summary>
/// Registers a Service or Actor <paramref name="reference" /> as subscriber for messages of type <paramref name="messageTypeName" />
/// </summary>
/// <param name="reference">The reference.</param>
/// <param name="messageTypeName">Name of the message type.</param>
/// <returns>Task.</returns>
private async Task RegisterSubscriberAsync(ReferenceWrapper reference, string messageTypeName)
{
await WaitForInitializeAsync(CancellationToken.None);
var myDictionary = await TimeoutRetryHelper.Execute((token, state) => StateManager.GetOrAddAsync<IReliableDictionary<string, BrokerServiceState>>(messageTypeName));
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
var queueName = CreateQueueName(reference, messageTypeName);
var deadLetterQueueName = CreateDeadLetterQueueName(reference, messageTypeName);
Func<string, BrokerServiceState> addValueFactory = key =>
{
Reference subscriber = new Reference(reference, queueName, deadLetterQueueName);
BrokerServiceState newState = new BrokerServiceState(messageTypeName);
newState = BrokerServiceState.AddSubscriber(newState, subscriber);
return newState;
};
Func<string, BrokerServiceState, BrokerServiceState> updateValueFactory = (key, current) =>
{
Reference subscriber = new Reference(reference, queueName, deadLetterQueueName);
BrokerServiceState newState = BrokerServiceState.AddSubscriber(current, subscriber);
return newState;
};
await myDictionary.AddOrUpdateAsync(tx, Subscribers, addValueFactory, updateValueFactory);
await CreateQueueAsync(tx, queueName);
await CreateQueueAsync(tx, deadLetterQueueName);
_queues.AddOrUpdate(queueName, reference, (key, old) => reference);
ServiceEventSourceMessage($"Registered subscriber: {reference.Name}");
}, cancellationToken: CancellationToken.None);
}
/// <summary>
/// Unregisters a Service or Actor <paramref name="reference" /> as subscriber for messages of type <paramref name="messageTypeName" />
/// </summary>
/// <param name="reference"></param>
/// <param name="messageTypeName"></param>
/// <returns></returns>
private async Task UnregisterSubscriberAsync(ReferenceWrapper reference, string messageTypeName)
{
await WaitForInitializeAsync(CancellationToken.None);
var myDictionary = await TimeoutRetryHelper.Execute((token, state) => StateManager.GetOrAddAsync<IReliableDictionary<string, BrokerServiceState>>(messageTypeName));
var queueName = CreateQueueName(reference, messageTypeName);
var deadLetterQueueName = CreateDeadLetterQueueName(reference, messageTypeName);
await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
{
var subscribers = await myDictionary.TryGetValueAsync(tx, Subscribers, LockMode.Update);
if (subscribers.HasValue)
{
var newState = BrokerServiceState.RemoveSubscriber(subscribers.Value, reference);
await myDictionary.SetAsync(tx, Subscribers, newState);
}
await StateManager.RemoveAsync(tx, queueName);
await StateManager.RemoveAsync(tx, deadLetterQueueName);
ServiceEventSourceMessage($"Unregistered subscriber: {reference.Name}");
_queues.TryRemove(queueName, out reference);
});
}
#endregion Private Methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// ----------------------------------------------------------------------------
// This class takes an EXPRMEMGRP and a set of arguments and binds the arguments
// to the best applicable method in the group.
// ----------------------------------------------------------------------------
internal sealed partial class ExpressionBinder
{
internal sealed class GroupToArgsBinder
{
private enum Result
{
Success,
Failure_SearchForExpanded,
Failure_NoSearchForExpanded
}
private readonly ExpressionBinder _pExprBinder;
private bool _fCandidatesUnsupported;
private readonly BindingFlag _fBindFlags;
private readonly EXPRMEMGRP _pGroup;
private readonly ArgInfos _pArguments;
private readonly ArgInfos _pOriginalArguments;
private readonly bool _bHasNamedArguments;
private readonly AggregateType _pDelegate;
private AggregateType _pCurrentType;
private MethodOrPropertySymbol _pCurrentSym;
private TypeArray _pCurrentTypeArgs;
private TypeArray _pCurrentParameters;
private TypeArray _pBestParameters;
private int _nArgBest;
// Keep track of the first 20 or so syms with the wrong arg count.
private readonly SymWithType[] _swtWrongCount = new SymWithType[20];
private int _nWrongCount;
private bool _bIterateToEndOfNsList; // we have found an appliacable extension method only itereate to
// end of current namespaces extension method list
private bool _bBindingCollectionAddArgs; // Report parameter modifiers as error
private readonly GroupToArgsBinderResult _results;
private readonly List<CandidateFunctionMember> _methList;
private readonly MethPropWithInst _mpwiParamTypeConstraints;
private readonly MethPropWithInst _mpwiBogus;
private readonly MethPropWithInst _mpwiCantInferInstArg;
private readonly MethWithType _mwtBadArity;
private Name _pInvalidSpecifiedName;
private Name _pNameUsedInPositionalArgument;
private Name _pDuplicateSpecifiedName;
// When we find a type with an interface, then we want to mark all other interfaces that it
// implements as being hidden. We also want to mark object as being hidden. So stick them
// all in this list, and then for subsequent types, if they're in this list, then we
// ignore them.
private readonly List<CType> _HiddenTypes;
private bool _bArgumentsChangedForNamedOrOptionalArguments;
public GroupToArgsBinder(ExpressionBinder exprBinder, BindingFlag bindFlags, EXPRMEMGRP grp, ArgInfos args, ArgInfos originalArgs, bool bHasNamedArguments, AggregateType atsDelegate)
{
Debug.Assert(grp != null);
Debug.Assert(exprBinder != null);
Debug.Assert(args != null);
_pExprBinder = exprBinder;
_fCandidatesUnsupported = false;
_fBindFlags = bindFlags;
_pGroup = grp;
_pArguments = args;
_pOriginalArguments = originalArgs;
_bHasNamedArguments = bHasNamedArguments;
_pDelegate = atsDelegate;
_pCurrentType = null;
_pCurrentSym = null;
_pCurrentTypeArgs = null;
_pCurrentParameters = null;
_pBestParameters = null;
_nArgBest = -1;
_nWrongCount = 0;
_bIterateToEndOfNsList = false;
_bBindingCollectionAddArgs = false;
_results = new GroupToArgsBinderResult();
_methList = new List<CandidateFunctionMember>();
_mpwiParamTypeConstraints = new MethPropWithInst();
_mpwiBogus = new MethPropWithInst();
_mpwiCantInferInstArg = new MethPropWithInst();
_mwtBadArity = new MethWithType();
_HiddenTypes = new List<CType>();
}
// ----------------------------------------------------------------------------
// This method does the actual binding.
// ----------------------------------------------------------------------------
public bool Bind(bool bReportErrors)
{
Debug.Assert(_pGroup.sk == SYMKIND.SK_MethodSymbol || _pGroup.sk == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.flags & EXPRFLAG.EXF_INDEXER));
// We need the EXPRs for error reporting for non-delegates
Debug.Assert(_pDelegate != null || _pArguments.fHasExprs);
LookForCandidates();
if (!GetResultOfBind(bReportErrors))
{
if (bReportErrors)
{
ReportErrorsOnFailure();
}
return false;
}
return true;
}
public GroupToArgsBinderResult GetResultsOfBind()
{
return _results;
}
public bool BindCollectionAddArgs()
{
_bBindingCollectionAddArgs = true;
return Bind(true /* bReportErrors */);
}
private SymbolLoader GetSymbolLoader()
{
return _pExprBinder.GetSymbolLoader();
}
private CSemanticChecker GetSemanticChecker()
{
return _pExprBinder.GetSemanticChecker();
}
private ErrorHandling GetErrorContext()
{
return _pExprBinder.GetErrorContext();
}
private static CType GetTypeQualifier(EXPRMEMGRP pGroup)
{
Debug.Assert(pGroup != null);
CType rval = null;
if (0 != (pGroup.flags & EXPRFLAG.EXF_BASECALL))
{
rval = null;
}
else if (0 != (pGroup.flags & EXPRFLAG.EXF_CTOR))
{
rval = pGroup.GetParentType();
}
else if (pGroup.GetOptionalObject() != null)
{
rval = pGroup.GetOptionalObject().type;
}
else
{
rval = null;
}
return rval;
}
private void LookForCandidates()
{
bool fExpanded = false;
bool bSearchForExpanded = true;
int cswtMaxWrongCount = _swtWrongCount.Length;
bool allCandidatesUnsupported = true;
bool lookedAtCandidates = false;
// Calculate the mask based on the type of the sym we've found so far. This
// is to ensure that if we found a propsym (or methsym, or whatever) the
// iterator will only return propsyms (or methsyms, or whatever)
symbmask_t mask = (symbmask_t)(1 << (int)_pGroup.sk);
CType pTypeThrough = _pGroup.GetOptionalObject() != null ? _pGroup.GetOptionalObject().type : null;
CMemberLookupResults.CMethodIterator iterator = _pGroup.GetMemberLookupResults().GetMethodIterator(GetSemanticChecker(), GetSymbolLoader(), pTypeThrough, GetTypeQualifier(_pGroup), _pExprBinder.ContextForMemberLookup(), true, // AllowBogusAndInaccessible
false, _pGroup.typeArgs.size, _pGroup.flags, mask);
while (true)
{
bool bFoundExpanded;
bFoundExpanded = false;
if (bSearchForExpanded && !fExpanded)
{
bFoundExpanded = fExpanded = ConstructExpandedParameters();
}
// Get the next sym to search for.
if (!bFoundExpanded)
{
fExpanded = false;
if (!GetNextSym(iterator))
{
break;
}
// Get the parameters.
_pCurrentParameters = _pCurrentSym.Params;
bSearchForExpanded = true;
}
if (_bArgumentsChangedForNamedOrOptionalArguments)
{
// If we changed them last time, then we need to reset them.
_bArgumentsChangedForNamedOrOptionalArguments = false;
CopyArgInfos(_pOriginalArguments, _pArguments);
}
// If we have named arguments, reorder them for this method.
if (_pArguments.fHasExprs)
{
// If we don't have EXPRs, its because we're doing a method group conversion.
// In those scenarios, we never want to add named arguments or optional arguments.
if (_bHasNamedArguments)
{
if (!ReOrderArgsForNamedArguments())
{
continue;
}
}
else if (HasOptionalParameters())
{
if (!AddArgumentsForOptionalParameters())
{
continue;
}
}
}
if (!bFoundExpanded)
{
lookedAtCandidates = true;
allCandidatesUnsupported &= _pCurrentSym.getBogus();
// If we have the wrong number of arguments and still have room in our cache of 20,
// then store it in our cache and go to the next sym.
if (_pCurrentParameters.size != _pArguments.carg)
{
if (_nWrongCount < cswtMaxWrongCount &&
(!_pCurrentSym.isParamArray || _pArguments.carg < _pCurrentParameters.size - 1))
{
_swtWrongCount[_nWrongCount++] = new SymWithType(_pCurrentSym, _pCurrentType);
}
bSearchForExpanded = true;
continue;
}
}
// If we cant use the current symbol, then we've filtered it, so get the next one.
if (!iterator.CanUseCurrentSymbol())
{
continue;
}
// Get the current type args.
Result currentTypeArgsResult = DetermineCurrentTypeArgs();
if (currentTypeArgsResult != Result.Success)
{
bSearchForExpanded = (currentTypeArgsResult == Result.Failure_SearchForExpanded);
continue;
}
// Check access.
bool fCanAccess = !iterator.IsCurrentSymbolInaccessible();
if (!fCanAccess && (!_methList.IsEmpty() || _results.GetInaccessibleResult()))
{
// We'll never use this one for error reporting anyway, so just skip it.
bSearchForExpanded = false;
continue;
}
// Check bogus.
bool fBogus = fCanAccess && iterator.IsCurrentSymbolBogus();
if (fBogus && (!_methList.IsEmpty() || _results.GetInaccessibleResult() || _mpwiBogus))
{
// We'll never use this one for error reporting anyway, so just skip it.
bSearchForExpanded = false;
continue;
}
// Check convertibility of arguments.
if (!ArgumentsAreConvertible())
{
bSearchForExpanded = true;
continue;
}
// We know we have the right number of arguments and they are all convertible.
if (!fCanAccess)
{
// In case we never get an accessible method, this will allow us to give
// a better error...
Debug.Assert(!_results.GetInaccessibleResult());
_results.GetInaccessibleResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
else if (fBogus)
{
// In case we never get a good method, this will allow us to give
// a better error...
Debug.Assert(!_mpwiBogus);
_mpwiBogus.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
else
{
// This is a plausible method / property to call.
// Link it in at the end of the list.
_methList.Add(new CandidateFunctionMember(
new MethPropWithInst(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs),
_pCurrentParameters,
0,
fExpanded));
// When we find a method, we check if the type has interfaces. If so, mark the other interfaces
// as hidden, and object as well.
if (_pCurrentType.isInterfaceType())
{
TypeArray ifaces = _pCurrentType.GetIfacesAll();
for (int i = 0; i < ifaces.size; i++)
{
AggregateType type = ifaces.Item(i).AsAggregateType();
Debug.Assert(type.isInterfaceType());
_HiddenTypes.Add(type);
}
// Mark object.
AggregateType typeObject = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT, true);
_HiddenTypes.Add(typeObject);
}
}
// Don't look at the expanded form.
bSearchForExpanded = false;
}
_fCandidatesUnsupported = allCandidatesUnsupported && lookedAtCandidates;
// Restore the arguments to their original state if we changed them for named/optional arguments.
// ILGen will take care of putting the real arguments in there.
if (_bArgumentsChangedForNamedOrOptionalArguments)
{
// If we changed them last time, then we need to reset them.
CopyArgInfos(_pOriginalArguments, _pArguments);
}
}
private void CopyArgInfos(ArgInfos src, ArgInfos dst)
{
dst.carg = src.carg;
dst.types = src.types;
dst.fHasExprs = src.fHasExprs;
dst.prgexpr.Clear();
for (int i = 0; i < src.prgexpr.Count; i++)
{
dst.prgexpr.Add(src.prgexpr[i]);
}
}
private bool GetResultOfBind(bool bReportErrors)
{
// We looked at all the evidence, and we come to render the verdict:
if (!_methList.IsEmpty())
{
CandidateFunctionMember pmethBest;
if (_methList.Count == 1)
{
// We found the single best method to call.
pmethBest = _methList.Head();
}
else
{
// We have some ambiguities, lets sort them out.
CandidateFunctionMember pAmbig1 = null;
CandidateFunctionMember pAmbig2 = null;
CType pTypeThrough = _pGroup.GetOptionalObject() != null ? _pGroup.GetOptionalObject().type : null;
pmethBest = _pExprBinder.FindBestMethod(_methList, pTypeThrough, _pArguments, out pAmbig1, out pAmbig2);
if (null == pmethBest)
{
// Arbitrarily use the first one, but make sure to report errors or give the ambiguous one
// back to the caller.
pmethBest = pAmbig1;
_results.AmbiguousResult = pAmbig2.mpwi;
if (bReportErrors)
{
if (pAmbig1.@params != pAmbig2.@params ||
pAmbig1.mpwi.MethProp().Params.size != pAmbig2.mpwi.MethProp().Params.size ||
pAmbig1.mpwi.TypeArgs != pAmbig2.mpwi.TypeArgs ||
pAmbig1.mpwi.GetType() != pAmbig2.mpwi.GetType() ||
pAmbig1.mpwi.MethProp().Params == pAmbig2.mpwi.MethProp().Params)
{
GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi, pAmbig2.mpwi);
}
else
{
// The two signatures are identical so don't use the type args in the error message.
GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi.MethProp(), pAmbig2.mpwi.MethProp());
}
}
}
}
// This is the "success" exit path.
Debug.Assert(pmethBest != null);
_results.BestResult = pmethBest.mpwi;
// Record our best match in the memgroup as well. This is temporary.
if (bReportErrors)
{
ReportErrorsOnSuccess();
}
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////
// This method returns true if we're able to match arguments to their names.
// If we either have too many arguments, or we cannot match their names, then
// we return false.
//
// Note that if we have not enough arguments, we still return true as long as
// we can find matching parameters for each named arguments, and all parameters
// that do not have a matching argument are optional parameters.
private bool ReOrderArgsForNamedArguments()
{
// First we need to find the method that we're actually trying to call.
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.GetOptionalObject());
if (methprop == null)
{
return false;
}
int numParameters = _pCurrentParameters.size;
// If we have no parameters, or fewer parameters than we have arguments, bail.
if (numParameters == 0 || numParameters < _pArguments.carg)
{
return false;
}
// Make sure all the names we specified are in the list and we don't have duplicates.
if (!NamedArgumentNamesAppearInParameterList(methprop))
{
return false;
}
_bArgumentsChangedForNamedOrOptionalArguments = ReOrderArgsForNamedArguments(
methprop,
_pCurrentParameters,
_pCurrentType,
_pGroup,
_pArguments,
_pExprBinder.GetTypes(),
_pExprBinder.GetExprFactory(),
GetSymbolLoader());
return _bArgumentsChangedForNamedOrOptionalArguments;
}
internal static bool ReOrderArgsForNamedArguments(
MethodOrPropertySymbol methprop,
TypeArray pCurrentParameters,
AggregateType pCurrentType,
EXPRMEMGRP pGroup,
ArgInfos pArguments,
TypeManager typeManager,
ExprFactory exprFactory,
SymbolLoader symbolLoader)
{
// We use the param count from pCurrentParameters because they may have been resized
// for param arrays.
int numParameters = pCurrentParameters.size;
EXPR[] pExprArguments = new EXPR[numParameters];
// Now go through the parameters. First set all positional arguments in the new argument
// set, then for the remainder, look for a named argument with a matching name.
int index = 0;
EXPR paramArrayArgument = null;
TypeArray @params = typeManager.SubstTypeArray(
pCurrentParameters,
pCurrentType,
pGroup.typeArgs);
foreach (Name name in methprop.ParameterNames)
{
// This can happen if we had expanded our param array to size 0.
if (index >= pCurrentParameters.size)
{
break;
}
// If:
// (1) we have a param array method
// (2) we're on the last arg
// (3) the thing we have is an array init thats generated for param array
// then let us through.
if (methprop.isParamArray &&
index < pArguments.carg &&
pArguments.prgexpr[index].isARRINIT() && pArguments.prgexpr[index].asARRINIT().GeneratedForParamArray)
{
paramArrayArgument = pArguments.prgexpr[index];
}
// Positional.
if (index < pArguments.carg &&
!pArguments.prgexpr[index].isNamedArgumentSpecification() &&
!(pArguments.prgexpr[index].isARRINIT() && pArguments.prgexpr[index].asARRINIT().GeneratedForParamArray))
{
pExprArguments[index] = pArguments.prgexpr[index++];
continue;
}
// Look for names.
EXPR pNewArg = FindArgumentWithName(pArguments, name);
if (pNewArg == null)
{
if (methprop.IsParameterOptional(index))
{
pNewArg = GenerateOptionalArgument(symbolLoader, exprFactory, methprop, @params.Item(index), index);
}
else if (paramArrayArgument != null && index == methprop.Params.Count - 1)
{
// If we have a param array argument and we're on the last one, then use it.
pNewArg = paramArrayArgument;
}
else
{
// No name and no default value.
return false;
}
}
pExprArguments[index++] = pNewArg;
}
// Here we've found all the arguments, or have default values for them.
CType[] prgTypes = new CType[pCurrentParameters.size];
for (int i = 0; i < numParameters; i++)
{
if (i < pArguments.prgexpr.Count)
{
pArguments.prgexpr[i] = pExprArguments[i];
}
else
{
pArguments.prgexpr.Add(pExprArguments[i]);
}
prgTypes[i] = pArguments.prgexpr[i].type;
}
pArguments.carg = pCurrentParameters.size;
pArguments.types = symbolLoader.getBSymmgr().AllocParams(pCurrentParameters.size, prgTypes);
return true;
}
/////////////////////////////////////////////////////////////////////////////////
private static EXPR GenerateOptionalArgument(
SymbolLoader symbolLoader,
ExprFactory exprFactory,
MethodOrPropertySymbol methprop,
CType type,
int index)
{
CType pParamType = type;
CType pRawParamType = type.IsNullableType() ? type.AsNullableType().GetUnderlyingType() : type;
EXPR optionalArgument = null;
if (methprop.HasDefaultParameterValue(index))
{
CType pConstValType = methprop.GetDefaultParameterValueConstValType(index);
CONSTVAL cv = methprop.GetDefaultParameterValue(index);
if (pConstValType.isPredefType(PredefinedType.PT_DATETIME) &&
(pRawParamType.isPredefType(PredefinedType.PT_DATETIME) || pRawParamType.isPredefType(PredefinedType.PT_OBJECT) || pRawParamType.isPredefType(PredefinedType.PT_VALUE)))
{
// This is the specific case where we want to create a DateTime
// but the constval that stores it is a long.
AggregateType dateTimeType = symbolLoader.GetReqPredefType(PredefinedType.PT_DATETIME);
optionalArgument = exprFactory.CreateConstant(dateTimeType, new CONSTVAL(DateTime.FromBinary(cv.longVal)));
}
else if (pConstValType.isSimpleOrEnumOrString())
{
// In this case, the constval is a simple type (all the numerics, including
// decimal), or an enum or a string. This covers all the substantial values,
// and everything else that can be encoded is just null or default(something).
// For enum parameters, we create a constant of the enum type. For everything
// else, we create the appropriate constant.
if (pRawParamType.isEnumType() && pConstValType == pRawParamType.underlyingType())
{
optionalArgument = exprFactory.CreateConstant(pRawParamType, cv);
}
else
{
optionalArgument = exprFactory.CreateConstant(pConstValType, cv);
}
}
else if ((pParamType.IsRefType() || pParamType.IsNullableType()) && cv.IsNullRef())
{
// We have an "= null" default value with a reference type or a nullable type.
optionalArgument = exprFactory.CreateNull();
}
else
{
// We have a default value that is encoded as a nullref, and that nullref is
// interpreted as default(something). For instance, the pParamType could be
// a type parameter type or a non-simple value type.
optionalArgument = exprFactory.CreateZeroInit(pParamType);
}
}
else
{
// There was no default parameter specified, so generally use default(T),
// except for some cases when the parameter type in metatdata is object.
if (pParamType.isPredefType(PredefinedType.PT_OBJECT))
{
if (methprop.MarshalAsObject(index))
{
// For [opt] parameters of type object, if we have marshal(iunknown),
// marshal(idispatch), or marshal(interface), then we emit a null.
optionalArgument = exprFactory.CreateNull();
}
else
{
// Otherwise, we generate Type.Missing
AggregateSymbol agg = symbolLoader.GetOptPredefAgg(PredefinedType.PT_MISSING);
Name name = symbolLoader.GetNameManager().GetPredefinedName(PredefinedName.PN_CAP_VALUE);
FieldSymbol field = symbolLoader.LookupAggMember(name, agg, symbmask_t.MASK_FieldSymbol).AsFieldSymbol();
FieldWithType fwt = new FieldWithType(field, agg.getThisType());
EXPRFIELD exprField = exprFactory.CreateField(0, agg.getThisType(), null, 0, fwt, null);
if (agg.getThisType() != type)
{
optionalArgument = exprFactory.CreateCast(0, type, exprField);
}
else
{
optionalArgument = exprField;
}
}
}
else
{
// Every type aside from object that doesn't have a default value gets
// its default value.
optionalArgument = exprFactory.CreateZeroInit(pParamType);
}
}
Debug.Assert(optionalArgument != null);
optionalArgument.IsOptionalArgument = true;
return optionalArgument;
}
/////////////////////////////////////////////////////////////////////////////////
private MethodOrPropertySymbol FindMostDerivedMethod(
MethodOrPropertySymbol pMethProp,
EXPR pObject)
{
return FindMostDerivedMethod(GetSymbolLoader(), pMethProp, pObject?.type);
}
/////////////////////////////////////////////////////////////////////////////////
public static MethodOrPropertySymbol FindMostDerivedMethod(
SymbolLoader symbolLoader,
MethodOrPropertySymbol pMethProp,
CType pType)
{
MethodSymbol method;
bool bIsIndexer = false;
if (pMethProp.IsMethodSymbol())
{
method = pMethProp.AsMethodSymbol();
}
else
{
PropertySymbol prop = pMethProp.AsPropertySymbol();
method = prop.methGet != null ? prop.methGet : prop.methSet;
if (method == null)
{
return null;
}
bIsIndexer = prop.isIndexer();
}
if (!method.isVirtual)
{
return method;
}
if (pType == null)
{
// This must be a static call.
return method;
}
// Now get the slot method.
var slotMethod = method.swtSlot?.Meth();
if (slotMethod != null)
{
method = slotMethod;
}
if (!pType.IsAggregateType())
{
// Not something that can have overrides anyway.
return method;
}
for (AggregateSymbol pAggregate = pType.AsAggregateType().GetOwningAggregate();
pAggregate != null && pAggregate.GetBaseAgg() != null;
pAggregate = pAggregate.GetBaseAgg())
{
for (MethodOrPropertySymbol meth = symbolLoader.LookupAggMember(method.name, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol).AsMethodOrPropertySymbol();
meth != null;
meth = symbolLoader.LookupNextSym(meth, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol).AsMethodOrPropertySymbol())
{
if (!meth.isOverride)
{
continue;
}
if (meth.swtSlot.Sym != null && meth.swtSlot.Sym == method)
{
if (bIsIndexer)
{
Debug.Assert(meth.IsMethodSymbol());
return meth.AsMethodSymbol().getProperty();
}
else
{
return meth;
}
}
}
}
// If we get here, it means we can have two cases: one is that we have
// a delegate. This is because the delegate invoke method is virtual and is
// an override, but we won't have the slots set up correctly, and will
// not find the base type in the inheritance hierarchy. The second is that
// we're calling off of the base itself.
Debug.Assert(method.parent.IsAggregateSymbol());
return method;
}
/////////////////////////////////////////////////////////////////////////////////
private bool HasOptionalParameters()
{
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.GetOptionalObject());
return methprop != null && methprop.HasOptionalParameters();
}
/////////////////////////////////////////////////////////////////////////////////
// Returns true if we can either add enough optional parameters to make the
// argument list match, or if we don't need to at all.
private bool AddArgumentsForOptionalParameters()
{
if (_pCurrentParameters.size <= _pArguments.carg)
{
// If we have enough arguments, or too many, no need to add any optionals here.
return true;
}
// First we need to find the method that we're actually trying to call.
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.GetOptionalObject());
if (methprop == null)
{
return false;
}
// If we're here, we know we're not in a named argument case. As such, we can
// just generate defaults for every missing argument.
int i = _pArguments.carg;
int index = 0;
TypeArray @params = _pExprBinder.GetTypes().SubstTypeArray(
_pCurrentParameters,
_pCurrentType,
_pGroup.typeArgs);
EXPR[] pArguments = new EXPR[_pCurrentParameters.size - i];
for (; i < @params.size; i++, index++)
{
if (!methprop.IsParameterOptional(i))
{
// We don't have an optional here, but we need to fill it in.
return false;
}
pArguments[index] = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), methprop, @params.Item(i), i);
}
// Success. Lets copy them in now.
for (int n = 0; n < index; n++)
{
_pArguments.prgexpr.Add(pArguments[n]);
}
CType[] prgTypes = new CType[@params.size];
for (int n = 0; n < @params.size; n++)
{
prgTypes[n] = _pArguments.prgexpr[n].type;
}
_pArguments.types = GetSymbolLoader().getBSymmgr().AllocParams(@params.size, prgTypes);
_pArguments.carg = @params.size;
_bArgumentsChangedForNamedOrOptionalArguments = true;
return true;
}
/////////////////////////////////////////////////////////////////////////////////
private static EXPR FindArgumentWithName(ArgInfos pArguments, Name pName)
{
for (int i = 0; i < pArguments.carg; i++)
{
if (pArguments.prgexpr[i].isNamedArgumentSpecification() &&
pArguments.prgexpr[i].asNamedArgumentSpecification().Name == pName)
{
return pArguments.prgexpr[i];
}
}
return null;
}
/////////////////////////////////////////////////////////////////////////////////
private bool NamedArgumentNamesAppearInParameterList(
MethodOrPropertySymbol methprop)
{
// Keep track of the current position in the parameter list so that we can check
// containment from this point onwards as well as complete containment. This is
// for error reporting. The user cannot specify a named argument for a parameter
// that has a fixed argument value.
List<Name> currentPosition = methprop.ParameterNames;
HashSet<Name> names = new HashSet<Name>();
for (int i = 0; i < _pArguments.carg; i++)
{
if (!_pArguments.prgexpr[i].isNamedArgumentSpecification())
{
if (!currentPosition.IsEmpty())
{
currentPosition = currentPosition.Tail();
}
continue;
}
Name name = _pArguments.prgexpr[i].asNamedArgumentSpecification().Name;
if (!methprop.ParameterNames.Contains(name))
{
if (_pInvalidSpecifiedName == null)
{
_pInvalidSpecifiedName = name;
}
return false;
}
else if (!currentPosition.Contains(name))
{
if (_pNameUsedInPositionalArgument == null)
{
_pNameUsedInPositionalArgument = name;
}
return false;
}
if (names.Contains(name))
{
if (_pDuplicateSpecifiedName == null)
{
_pDuplicateSpecifiedName = name;
}
return false;
}
names.Add(name);
}
return true;
}
// This method returns true if we have another sym to consider.
// If we've found a match in the current type, and have no more syms to consider in this type, then we
// return false.
private bool GetNextSym(CMemberLookupResults.CMethodIterator iterator)
{
if (!iterator.MoveNext(_methList.IsEmpty(), _bIterateToEndOfNsList))
{
return false;
}
_pCurrentSym = iterator.GetCurrentSymbol();
AggregateType type = iterator.GetCurrentType();
// If our current type is null, this is our first iteration, so set the type.
// If our current type is not null, and we've got a new type now, and we've already matched
// a symbol, then bail out.
if (_pCurrentType != type &&
_pCurrentType != null &&
!_methList.IsEmpty() &&
!_methList.Head().mpwi.GetType().isInterfaceType() &&
(!_methList.Head().mpwi.Sym.IsMethodSymbol() || !_methList.Head().mpwi.Meth().IsExtension()))
{
return false;
}
else if (_pCurrentType != type &&
_pCurrentType != null &&
!_methList.IsEmpty() &&
!_methList.Head().mpwi.GetType().isInterfaceType() &&
_methList.Head().mpwi.Sym.IsMethodSymbol() &&
_methList.Head().mpwi.Meth().IsExtension())
{
// we have found a applicable method that is an extension now we must move to the end of the NS list before quiting
if (_pGroup.GetOptionalObject() != null)
{
// if we find this while looking for static methods we should ignore it
_bIterateToEndOfNsList = true;
}
}
_pCurrentType = type;
// We have a new type. If this type is hidden, we need another type.
while (_HiddenTypes.Contains(_pCurrentType))
{
// Move through this type and get the next one.
for (; iterator.GetCurrentType() == _pCurrentType; iterator.MoveNext(_methList.IsEmpty(), _bIterateToEndOfNsList)) ;
_pCurrentSym = iterator.GetCurrentSymbol();
_pCurrentType = iterator.GetCurrentType();
if (iterator.AtEnd())
{
return false;
}
}
return true;
}
private bool ConstructExpandedParameters()
{
// Deal with params.
if (_pCurrentSym == null || _pArguments == null || _pCurrentParameters == null)
{
return false;
}
if (0 != (_fBindFlags & BindingFlag.BIND_NOPARAMS))
{
return false;
}
if (!_pCurrentSym.isParamArray)
{
return false;
}
// Count the number of optionals in the method. If there are enough optionals
// and actual arguments, then proceed.
{
int numOptionals = 0;
for (int i = _pArguments.carg; i < _pCurrentSym.Params.size; i++)
{
if (_pCurrentSym.IsParameterOptional(i))
{
numOptionals++;
}
}
if (_pArguments.carg + numOptionals < _pCurrentParameters.size - 1)
{
return false;
}
}
Debug.Assert(_methList.IsEmpty() || _methList.Head().mpwi.MethProp() != _pCurrentSym);
// Construct the expanded params.
return _pExprBinder.TryGetExpandedParams(_pCurrentSym.Params, _pArguments.carg, out _pCurrentParameters);
}
private Result DetermineCurrentTypeArgs()
{
TypeArray typeArgs = _pGroup.typeArgs;
// Get the type args.
if (_pCurrentSym.IsMethodSymbol() && _pCurrentSym.AsMethodSymbol().typeVars.size != typeArgs.size)
{
MethodSymbol methSym = _pCurrentSym.AsMethodSymbol();
// Can't infer if some type args are specified.
if (typeArgs.size > 0)
{
if (!_mwtBadArity)
{
_mwtBadArity.Set(methSym, _pCurrentType);
}
return Result.Failure_NoSearchForExpanded;
}
Debug.Assert(methSym.typeVars.size > 0);
// Try to infer. If we have an errorsym in the type arguments, we know we cant infer,
// but we want to attempt it anyway. We'll mark this as "cant infer" so that we can
// report the appropriate error, but we'll continue inferring, since we want
// error sym to go to any type.
bool inferenceSucceeded;
inferenceSucceeded = MethodTypeInferrer.Infer(
_pExprBinder, GetSymbolLoader(),
methSym, _pCurrentType.GetTypeArgsAll(), _pCurrentParameters,
_pArguments, out _pCurrentTypeArgs);
if (!inferenceSucceeded)
{
if (_results.IsBetterUninferableResult(_pCurrentTypeArgs))
{
TypeArray pTypeVars = methSym.typeVars;
if (pTypeVars != null && _pCurrentTypeArgs != null && pTypeVars.size == _pCurrentTypeArgs.size)
{
_mpwiCantInferInstArg.Set(_pCurrentSym.AsMethodSymbol(), _pCurrentType, _pCurrentTypeArgs);
}
else
{
_mpwiCantInferInstArg.Set(_pCurrentSym.AsMethodSymbol(), _pCurrentType, pTypeVars);
}
}
return Result.Failure_SearchForExpanded;
}
}
else
{
_pCurrentTypeArgs = typeArgs;
}
return Result.Success;
}
private bool ArgumentsAreConvertible()
{
bool containsErrorSym = false;
bool bIsInstanceParameterConvertible = false;
if (_pArguments.carg != 0)
{
UpdateArguments();
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pCurrentParameters.Item(ivar);
bool constraintErrors = !TypeBind.CheckConstraints(GetSemanticChecker(), GetErrorContext(), var, CheckConstraintsFlags.NoErrors);
if (constraintErrors && !DoesTypeArgumentsContainErrorSym(var))
{
_mpwiParamTypeConstraints.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
return false;
}
}
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pCurrentParameters.Item(ivar);
containsErrorSym |= DoesTypeArgumentsContainErrorSym(var);
bool fresult;
if (_pArguments.fHasExprs)
{
EXPR pArgument = _pArguments.prgexpr[ivar];
// If we have a named argument, strip it to do the conversion.
if (pArgument.isNamedArgumentSpecification())
{
pArgument = pArgument.asNamedArgumentSpecification().Value;
}
fresult = _pExprBinder.canConvert(pArgument, var);
}
else
{
fresult = _pExprBinder.canConvert(_pArguments.types.Item(ivar), var);
}
// Mark this as a legitimate error if we didn't have any error syms.
if (!fresult && !containsErrorSym)
{
if (ivar > _nArgBest)
{
_nArgBest = ivar;
// If we already have best method for instance methods don't overwrite with extensions
if (!_results.GetBestResult())
{
_results.GetBestResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
_pBestParameters = _pCurrentParameters;
}
}
else if (ivar == _nArgBest && _pArguments.types.Item(ivar) != var)
{
// this is to eliminate the paranoid case of types that are equal but can't convert
// (think ErrorType != ErrorType)
// See if they just differ in out / ref.
CType argStripped = _pArguments.types.Item(ivar).IsParameterModifierType() ?
_pArguments.types.Item(ivar).AsParameterModifierType().GetParameterType() : _pArguments.types.Item(ivar);
CType varStripped = var.IsParameterModifierType() ? var.AsParameterModifierType().GetParameterType() : var;
if (argStripped == varStripped)
{
// If we already have best method for instance methods don't overwrite with extensions
if (!_results.GetBestResult())
{
_results.GetBestResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
_pBestParameters = _pCurrentParameters;
}
}
}
if (_pCurrentSym.IsMethodSymbol())
{
// Do not store the result if we have an extension method and the instance
// parameter isn't convertible.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() || bIsInstanceParameterConvertible)
{
_results.AddInconvertibleResult(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
return false;
}
}
}
if (containsErrorSym)
{
if (_results.IsBetterUninferableResult(_pCurrentTypeArgs) && _pCurrentSym.IsMethodSymbol())
{
// If we're an instance method or we're an extension that has an inferable instance argument,
// then mark us down. Note that the extension may not need to infer type args,
// so check if we have any type variables at all to begin with.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() ||
_pCurrentSym.AsMethodSymbol().typeVars.size == 0 ||
MethodTypeInferrer.CanObjectOfExtensionBeInferred(
_pExprBinder,
GetSymbolLoader(),
_pCurrentSym.AsMethodSymbol(),
_pCurrentType.GetTypeArgsAll(),
_pCurrentSym.AsMethodSymbol().Params,
_pArguments))
{
_results.GetUninferableResult().Set(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
}
else
{
if (_pCurrentSym.IsMethodSymbol())
{
// Do not store the result if we have an extension method and the instance
// parameter isn't convertible.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() || bIsInstanceParameterConvertible)
{
_results.AddInconvertibleResult(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
}
return !containsErrorSym;
}
private void UpdateArguments()
{
// Parameter types might have changed as a result of
// method type inference.
_pCurrentParameters = _pExprBinder.GetTypes().SubstTypeArray(
_pCurrentParameters, _pCurrentType, _pCurrentTypeArgs);
// It is also possible that an optional argument has changed its value
// as a result of method type inference. For example, when inferring
// from Foo(10) to Foo<T>(T t1, T t2 = default(T)), the fabricated
// argument list starts off as being (10, default(T)). After type
// inference has successfully inferred T as int, it needs to be
// transformed into (10, default(int)) before applicability checking
// notices that default(T) is not assignable to int.
if (_pArguments.prgexpr == null || _pArguments.prgexpr.Count == 0)
{
return;
}
MethodOrPropertySymbol pMethod = null;
for (int iParam = 0; iParam < _pCurrentParameters.size; ++iParam)
{
EXPR pArgument = _pArguments.prgexpr[iParam];
if (!pArgument.IsOptionalArgument)
{
continue;
}
CType pType = _pCurrentParameters.Item(iParam);
if (pType == pArgument.type)
{
continue;
}
// Argument has changed its type because of method type inference. Recompute it.
if (pMethod == null)
{
pMethod = FindMostDerivedMethod(_pCurrentSym, _pGroup.GetOptionalObject());
Debug.Assert(pMethod != null);
}
Debug.Assert(pMethod.IsParameterOptional(iParam));
EXPR pArgumentNew = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), pMethod, _pCurrentParameters[iParam], iParam);
_pArguments.prgexpr[iParam] = pArgumentNew;
}
}
private bool DoesTypeArgumentsContainErrorSym(CType var)
{
if (!var.IsAggregateType())
{
return false;
}
TypeArray typeVars = var.AsAggregateType().GetTypeArgsAll();
for (int i = 0; i < typeVars.size; i++)
{
CType type = typeVars.Item(i);
if (type.IsErrorType())
{
return true;
}
else if (type.IsAggregateType())
{
// If we have an agg type sym, check if its type args have errors.
if (DoesTypeArgumentsContainErrorSym(type))
{
return true;
}
}
}
return false;
}
// ----------------------------------------------------------------------------
private void ReportErrorsOnSuccess()
{
// used for Methods and Indexers
Debug.Assert(_pGroup.sk == SYMKIND.SK_MethodSymbol || _pGroup.sk == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.flags & EXPRFLAG.EXF_INDEXER));
Debug.Assert(_pGroup.typeArgs.size == 0 || _pGroup.sk == SYMKIND.SK_MethodSymbol);
// if this is a binding to finalize on object, then complain:
if (_results.GetBestResult().MethProp().name == GetSymbolLoader().GetNameManager().GetPredefName(PredefinedName.PN_DTOR) &&
_results.GetBestResult().MethProp().getClass().isPredefAgg(PredefinedType.PT_OBJECT))
{
if (0 != (_pGroup.flags & EXPRFLAG.EXF_BASECALL))
{
GetErrorContext().Error(ErrorCode.ERR_CallingBaseFinalizeDeprecated);
}
else
{
GetErrorContext().Error(ErrorCode.ERR_CallingFinalizeDepracated);
}
}
Debug.Assert(0 == (_pGroup.flags & EXPRFLAG.EXF_USERCALLABLE) || _results.GetBestResult().MethProp().isUserCallable());
if (_pGroup.sk == SYMKIND.SK_MethodSymbol)
{
Debug.Assert(_results.GetBestResult().MethProp().IsMethodSymbol());
if (_results.GetBestResult().TypeArgs.size > 0)
{
// Check method type variable constraints.
TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_results.GetBestResult()));
}
}
}
private void ReportErrorsOnFailure()
{
// First and foremost, report if the user specified a name more than once.
if (_pDuplicateSpecifiedName != null)
{
GetErrorContext().Error(ErrorCode.ERR_DuplicateNamedArgument, _pDuplicateSpecifiedName);
return;
}
Debug.Assert(_methList.IsEmpty());
// Report inaccessible.
if (_results.GetInaccessibleResult())
{
// We might have called this, but it is inaccessible...
GetSemanticChecker().ReportAccessError(_results.GetInaccessibleResult(), _pExprBinder.ContextForMemberLookup(), GetTypeQualifier(_pGroup));
return;
}
// Report bogus.
if (_mpwiBogus)
{
// We might have called this, but it is bogus...
GetErrorContext().ErrorRef(ErrorCode.ERR_BindToBogus, _mpwiBogus);
return;
}
bool bUseDelegateErrors = false;
Name nameErr = _pGroup.name;
// Check for an invoke.
if (_pGroup.GetOptionalObject() != null &&
_pGroup.GetOptionalObject().type != null &&
_pGroup.GetOptionalObject().type.isDelegateType() &&
_pGroup.name == GetSymbolLoader().GetNameManager().GetPredefName(PredefinedName.PN_INVOKE))
{
Debug.Assert(!_results.GetBestResult() || _results.GetBestResult().MethProp().getClass().IsDelegate());
Debug.Assert(!_results.GetBestResult() || _results.GetBestResult().GetType().getAggregate().IsDelegate());
bUseDelegateErrors = true;
nameErr = _pGroup.GetOptionalObject().type.getAggregate().name;
}
if (_results.GetBestResult())
{
// If we had some invalid arguments for best matching.
ReportErrorsForBestMatching(bUseDelegateErrors, nameErr);
}
else if (_results.GetUninferableResult() || _mpwiCantInferInstArg)
{
if (!_results.GetUninferableResult())
{
//copy the extension method for which instance argument type inference failed
_results.GetUninferableResult().Set(_mpwiCantInferInstArg.Sym.AsMethodSymbol(), _mpwiCantInferInstArg.GetType(), _mpwiCantInferInstArg.TypeArgs);
}
Debug.Assert(_results.GetUninferableResult().Sym.IsMethodSymbol());
MethodSymbol sym = _results.GetUninferableResult().Meth();
TypeArray pCurrentParameters = sym.Params;
// if we tried to bind to an extensionmethod and the instance argument Type Inference failed then the method does not exist
// on the type at all. this is treated as a lookup error
CType type = null;
if (_pGroup.GetOptionalObject() != null)
{
type = _pGroup.GetOptionalObject().type;
}
else if (_pGroup.GetOptionalLHS() != null)
{
type = _pGroup.GetOptionalLHS().type;
}
MethWithType mwtCantInfer = new MethWithType();
mwtCantInfer.Set(_results.GetUninferableResult().Meth(), _results.GetUninferableResult().GetType());
GetErrorContext().Error(ErrorCode.ERR_CantInferMethTypeArgs, mwtCantInfer);
}
else if (_mwtBadArity)
{
int cvar = _mwtBadArity.Meth().typeVars.size;
GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _mwtBadArity, new ErrArgSymKind(_mwtBadArity.Meth()), _pArguments.carg);
}
else if (_mpwiParamTypeConstraints)
{
// This will always report an error
TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_mpwiParamTypeConstraints));
}
else if (_pInvalidSpecifiedName != null)
{
// Give a better message for delegate invoke.
if (_pGroup.GetOptionalObject() != null &&
_pGroup.GetOptionalObject().type.IsAggregateType() &&
_pGroup.GetOptionalObject().type.AsAggregateType().GetOwningAggregate().IsDelegate())
{
GetErrorContext().Error(ErrorCode.ERR_BadNamedArgumentForDelegateInvoke, _pGroup.GetOptionalObject().type.AsAggregateType().GetOwningAggregate().name, _pInvalidSpecifiedName);
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadNamedArgument, _pGroup.name, _pInvalidSpecifiedName);
}
}
else if (_pNameUsedInPositionalArgument != null)
{
GetErrorContext().Error(ErrorCode.ERR_NamedArgumentUsedInPositional, _pNameUsedInPositionalArgument);
}
else
{
CParameterizedError error;
if (_pDelegate != null)
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_MethDelegateMismatch, nameErr, _pDelegate);
GetErrorContext().AddRelatedTypeLoc(error, _pDelegate);
}
else
{
// The number of arguments must be wrong.
if (_fCandidatesUnsupported)
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_BindToBogus, nameErr);
}
else if (bUseDelegateErrors)
{
Debug.Assert(0 == (_pGroup.flags & EXPRFLAG.EXF_CTOR));
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadDelArgCount, nameErr, _pArguments.carg);
}
else
{
if (0 != (_pGroup.flags & EXPRFLAG.EXF_CTOR))
{
Debug.Assert(!_pGroup.GetParentType().IsTypeParameterType());
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadCtorArgCount, _pGroup.GetParentType(), _pArguments.carg);
}
else
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadArgCount, nameErr, _pArguments.carg);
}
}
}
// Report possible matches (same name and is accessible). We stored these in m_swtWrongCount.
for (int i = 0; i < _nWrongCount; i++)
{
if (GetSemanticChecker().CheckAccess(
_swtWrongCount[i].Sym,
_swtWrongCount[i].GetType(),
_pExprBinder.ContextForMemberLookup(),
GetTypeQualifier(_pGroup)))
{
GetErrorContext().AddRelatedSymLoc(error, _swtWrongCount[i].Sym);
}
}
GetErrorContext().SubmitError(error);
}
}
private void ReportErrorsForBestMatching(bool bUseDelegateErrors, Name nameErr)
{
// Best matching overloaded method 'name' had some invalid arguments.
if (_pDelegate != null)
{
GetErrorContext().ErrorRef(ErrorCode.ERR_MethDelegateMismatch, nameErr, _pDelegate, _results.GetBestResult());
return;
}
if (_bBindingCollectionAddArgs)
{
if (ReportErrorsForCollectionAdd())
{
return;
}
}
if (bUseDelegateErrors)
{
// Point to the Delegate, not the Invoke method
GetErrorContext().Error(ErrorCode.ERR_BadDelArgTypes, _results.GetBestResult().GetType());
}
else
{
if (_results.GetBestResult().Sym.IsMethodSymbol() && _results.GetBestResult().Sym.AsMethodSymbol().IsExtension() && _pGroup.GetOptionalObject() != null)
{
GetErrorContext().Error(ErrorCode.ERR_BadExtensionArgTypes, _pGroup.GetOptionalObject().type, _pGroup.name, _results.GetBestResult().Sym);
}
else if (_bBindingCollectionAddArgs)
{
GetErrorContext().Error(ErrorCode.ERR_BadArgTypesForCollectionAdd, _results.GetBestResult());
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadArgTypes, _results.GetBestResult());
}
}
// Argument X: cannot convert type 'Y' to type 'Z'
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pBestParameters.Item(ivar);
if (!_pExprBinder.canConvert(_pArguments.prgexpr[ivar], var))
{
// See if they just differ in out / ref.
CType argStripped = _pArguments.types.Item(ivar).IsParameterModifierType() ?
_pArguments.types.Item(ivar).AsParameterModifierType().GetParameterType() : _pArguments.types.Item(ivar);
CType varStripped = var.IsParameterModifierType() ? var.AsParameterModifierType().GetParameterType() : var;
if (argStripped == varStripped)
{
if (varStripped != var)
{
// The argument is wrong in ref / out-ness.
GetErrorContext().Error(ErrorCode.ERR_BadArgRef, ivar + 1, (var.IsParameterModifierType() && var.AsParameterModifierType().isOut) ? "out" : "ref");
}
else
{
CType argument = _pArguments.types.Item(ivar);
// the argument is decorated, but doesn't needs a 'ref' or 'out'
GetErrorContext().Error(ErrorCode.ERR_BadArgExtraRef, ivar + 1, (argument.IsParameterModifierType() && argument.AsParameterModifierType().isOut) ? "out" : "ref");
}
}
else
{
// if we tried to bind to an extensionmethod and the instance argument conversion failed then the method does not exist
// on the type at all.
Symbol sym = _results.GetBestResult().Sym;
if (ivar == 0 && sym.IsMethodSymbol() && sym.AsMethodSymbol().IsExtension() && _pGroup.GetOptionalObject() != null &&
!_pExprBinder.canConvertInstanceParamForExtension(_pGroup.GetOptionalObject(), sym.AsMethodSymbol().Params.Item(0)))
{
if (!_pGroup.GetOptionalObject().type.getBogus())
{
GetErrorContext().Error(ErrorCode.ERR_BadInstanceArgType, _pGroup.GetOptionalObject().type, var);
}
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadArgType, ivar + 1, new ErrArg(_pArguments.types.Item(ivar), ErrArgFlags.Unique), new ErrArg(var, ErrArgFlags.Unique));
}
}
}
}
}
private bool ReportErrorsForCollectionAdd()
{
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pBestParameters.Item(ivar);
if (var.IsParameterModifierType())
{
GetErrorContext().ErrorRef(ErrorCode.ERR_InitializerAddHasParamModifiers, _results.GetBestResult());
return true;
}
}
return false;
}
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Contoso.Micro.Internal;
namespace Contoso.Micro
{
/// <summary>
/// JsonSerializer
/// </summary>
/// <typeparam name="T"></typeparam>
/// <seealso cref="Contoso.Micro.JsonSerializer" />
public class JsonSerializer<T> : JsonSerializer
{
readonly Dictionary<string, JsonMemberSerializationInfo> _memberSerializers = new Dictionary<string, JsonMemberSerializationInfo>();
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer<T>"/> class.
/// </summary>
public JsonSerializer()
: this(true) { }
/// <summary>
/// Creates the serializer.
/// </summary>
/// <returns>JsonSerializer<T>.</returns>
public static JsonSerializer<T> CreateSerializer() =>
CreateSerializer(JsonValueType.Unknown);
/// <summary>
/// Creates the serializer.
/// </summary>
/// <param name="serializeAs">The serialize as.</param>
/// <returns>JsonSerializer<T>.</returns>
public static JsonSerializer<T> CreateSerializer(JsonValueType serializeAs)
{
var serializer = CreateSerializer(typeof(T), serializeAs);
return serializer is JsonSerializer<T> ? (JsonSerializer<T>)serializer : new JsonGenericSerializerAdapter<T>(serializer);
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer<T>" /> class.
/// </summary>
/// <param name="createSerializers">if set to <c>true</c> [create serializers].</param>
protected internal JsonSerializer(bool createSerializers)
{
if (createSerializers)
{
var markedSerializeable = Attribute.IsDefined(typeof(T), typeof(JsonSerializableAttribute));
if (markedSerializeable)
{
foreach (PropertyInfo pInfo in typeof(T).GetProperties())
if (Attribute.IsDefined(pInfo, typeof(JsonPropertyAttribute)))
{
var serializationInfo = new JsonMemberSerializationInfo(pInfo);
_memberSerializers.Add(serializationInfo.Name, serializationInfo);
}
foreach (FieldInfo fInfo in typeof(T).GetFields())
if (Attribute.IsDefined(fInfo, typeof(JsonPropertyAttribute)))
{
var serializationInfo = new JsonMemberSerializationInfo(fInfo);
_memberSerializers.Add(serializationInfo.Name, serializationInfo);
}
}
else
foreach (PropertyInfo pInfo in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var serializationInfo = new JsonMemberSerializationInfo(pInfo);
_memberSerializers.Add(serializationInfo.Name, serializationInfo);
}
}
}
/// <summary>
/// Deserializes the specified r.
/// </summary>
/// <param name="r">The r.</param>
/// <returns>T.</returns>
public T Deserialize(TextReader r) =>
Deserialize(WrapTextReader.Wrap(r, WrapTextReader.WrapOptions.Default), string.Empty);
/// <summary>
/// Deserializes the specified r.
/// </summary>
/// <param name="r">The r.</param>
/// <param name="path">The path.</param>
/// <returns>T.</returns>
protected internal virtual T Deserialize(TextReader r, string path)
{
var result = Activator.CreateInstance<T>();
var parens = JsonParserUtil.ReadStartObject(r);
var hasMembers = JsonParserUtil.PeekNextChar(r, true) != '}';
while (hasMembers)
{
ReadMemeber(r, path, result);
hasMembers = JsonParserUtil.PeekNextChar(r, true) == ',';
if (hasMembers)
JsonParserUtil.ReadNextChar(r, true);
}
JsonParserUtil.ReadEndObject(r, parens);
return result;
}
void ReadMemeber(TextReader r, string path, T result)
{
var name = JsonParserUtil.ReadMemberName(r);
var sInfo = _memberSerializers[name];
var memberValue = sInfo.Serializer.BaseDeserialize(r, path + "/" + name);
var targetType = sInfo.MemberType;
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
targetType = targetType.GetGenericArguments()[0];
if (memberValue == null)
sInfo.SetValue(result, null);
else
{
if (targetType.IsEnum)
{
var integerType = Enum.GetUnderlyingType(targetType);
if (integerType == typeof(ulong)) sInfo.SetValue(result, Convert.ToUInt64(memberValue));
else if (integerType == typeof(long)) sInfo.SetValue(result, Convert.ToInt64(memberValue));
else if (integerType == typeof(uint)) sInfo.SetValue(result, Convert.ToUInt32(memberValue));
else if (integerType == typeof(int)) sInfo.SetValue(result, Convert.ToInt32(memberValue));
else if (integerType == typeof(ushort)) sInfo.SetValue(result, Convert.ToUInt16(memberValue));
else if (integerType == typeof(short)) sInfo.SetValue(result, Convert.ToInt16(memberValue));
else if (integerType == typeof(byte)) sInfo.SetValue(result, Convert.ToByte(memberValue));
else if (integerType == typeof(sbyte)) sInfo.SetValue(result, Convert.ToSByte(memberValue));
}
else
{
try { sInfo.SetValue(result, Convert.ChangeType(memberValue, targetType)); }
catch
{
if (memberValue != null)
{
if (memberValue is string && targetType == typeof(Uri))
sInfo.SetValue(result, new Uri((string)memberValue, UriKind.RelativeOrAbsolute));
else
{
var ctorInfo = targetType.GetConstructor(new[] { memberValue.GetType() });
if (ctorInfo != null) sInfo.SetValue(result, ctorInfo.Invoke(new[] { memberValue }));
else throw;
}
}
else throw;
}
}
}
}
/// <summary>
/// Serializes the specified w.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="obj">The obj.</param>
public void Serialize(TextWriter w, T obj) =>
Serialize(w, obj, JsonOptions.None, null, 0);
/// <summary>
/// Serializes the specified w.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="obj">The obj.</param>
/// <param name="options">The options.</param>
public void Serialize(TextWriter w, T obj, JsonOptions options) =>
Serialize(w, obj, options, null, 0);
/// <summary>
/// Serializes the specified w.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="obj">The obj.</param>
/// <param name="options">The options.</param>
/// <param name="format">The format.</param>
public void Serialize(TextWriter w, T obj, JsonOptions options, string format) =>
Serialize(w, obj, options, format, 0);
/// <summary>
/// Serializes the specified w.
/// </summary>
/// <param name="w">The w.</param>
/// <param name="obj">The obj.</param>
/// <param name="options">The options.</param>
/// <param name="format">The format.</param>
/// <param name="tabDepth">The tab depth.</param>
protected internal virtual void Serialize(TextWriter w, T obj, JsonOptions options, string format, int tabDepth)
{
if ((options & JsonOptions.EnclosingParens) != 0) w.Write('(');
w.Write('{');
var first = true;
foreach (JsonMemberSerializationInfo sInfo in _memberSerializers.Values)
{
var value = sInfo.GetValue(obj);
if (value != null || (options & JsonOptions.IncludeNulls) != 0)
{
if (!first) w.Write(',');
else first = false;
if ((options & JsonOptions.Formatted) != 0) { w.WriteLine(); w.Write(new string(' ', tabDepth * 2)); }
if ((options & JsonOptions.QuoteNames) != 0) w.Write('"');
w.Write(sInfo.Name);
if ((options & JsonOptions.QuoteNames) != 0) w.Write('"');
w.Write(':');
if ((options & JsonOptions.Formatted) != 0) w.Write(' ');
if (value == null) w.Write("null");
else if (sInfo.JsonProperty == null) sInfo.Serializer.BaseSerialize(w, value, options, null, tabDepth + 1);
else sInfo.Serializer.BaseSerialize(w, value, options, sInfo.JsonProperty.Format, tabDepth + 1);
}
}
w.Write('}');
if ((options & JsonOptions.EnclosingParens) != 0) w.Write(')');
}
internal override object BaseDeserialize(TextReader r, string path) =>
JsonParserUtil.PeekIsNull(r, true, path) ? null : (object)Deserialize(r, path);
internal override void BaseSerialize(TextWriter w, object obj, JsonOptions options, string format, int tabDepth) =>
Serialize(w, (T)obj, options, format, tabDepth);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal delegate void CompletionRoutine();
internal delegate void CompletionRoutine<TResult>(TResult result);
/// <summary>
/// Computes expansion of <see cref="DkmClrValue"/> instances.
/// </summary>
/// <remarks>
/// This class provides implementation for the default ResultProvider component.
/// </remarks>
public abstract class ResultProvider : IDkmClrResultProvider
{
internal readonly Formatter Formatter;
static ResultProvider()
{
FatalError.Handler = FailFast.OnFatalException;
}
internal ResultProvider(Formatter formatter)
{
this.Formatter = formatter;
}
void IDkmClrResultProvider.GetResult(DkmClrValue value, DkmWorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers, string resultName, string resultFullName, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine)
{
// TODO: Use full name
var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationAsyncResult.CreateErrorResult(e)));
GetRootResultAndContinue(
value,
wl,
declaredType,
declaredTypeInfo,
inspectionContext,
resultName,
result => wl.ContinueWith(() => completionRoutine(new DkmEvaluationAsyncResult(result))));
wl.Execute();
}
DkmClrValue IDkmClrResultProvider.GetClrValue(DkmSuccessEvaluationResult evaluationResult)
{
try
{
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
return null;
}
return dataItem.Value;
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmClrResultProvider.GetChildren(DkmEvaluationResult evaluationResult, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine)
{
var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
evaluationResult.GetChildren(workList, initialRequestSize, inspectionContext, completionRoutine);
return;
}
var stackFrame = evaluationResult.StackFrame;
GetChildrenAndContinue(dataItem, workList, stackFrame, initialRequestSize, inspectionContext, completionRoutine);
}
void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine)
{
var dataItem = enumContext.GetDataItem<EnumContextDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
enumContext.GetItems(workList, startIndex, count, completionRoutine);
return;
}
GetItemsAndContinue(dataItem.EvalResultDataItem, workList, startIndex, count, enumContext.InspectionContext, completionRoutine);
}
string IDkmClrResultProvider.GetUnderlyingString(DkmEvaluationResult result)
{
try
{
var dataItem = result.GetDataItem<EvalResultDataItem>();
if (dataItem == null)
{
// We don't know about this result. Call next implementation
return result.GetUnderlyingString();
}
return dataItem.Value?.GetUnderlyingString(result.InspectionContext);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void CreateEvaluationResultAndContinue(EvalResultDataItem dataItem, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
switch (dataItem.Kind)
{
case ExpansionKind.Error:
completionRoutine(DkmFailedEvaluationResult.Create(
inspectionContext,
StackFrame: stackFrame,
Name: dataItem.Name,
FullName: dataItem.FullName,
ErrorMessage: dataItem.DisplayValue,
Flags: DkmEvaluationResultFlags.None,
Type: null,
DataItem: null));
break;
case ExpansionKind.NativeView:
{
var value = dataItem.Value;
var name = Resources.NativeView;
var fullName = dataItem.FullName;
var display = dataItem.Name;
DkmEvaluationResult evalResult;
if (value.IsError())
{
evalResult = DkmFailedEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: name,
FullName: fullName,
ErrorMessage: display,
Flags: dataItem.Flags,
Type: null,
DataItem: dataItem);
}
else
{
// For Native View, create a DkmIntermediateEvaluationResult.
// This will allow the C++ EE to take over expansion.
var process = inspectionContext.RuntimeInstance.Process;
var cpp = process.EngineSettings.GetLanguage(new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.Cpp));
evalResult = DkmIntermediateEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: name,
FullName: fullName,
Expression: display,
IntermediateLanguage: cpp,
TargetRuntime: process.GetNativeRuntimeInstance(),
DataItem: dataItem);
}
completionRoutine(evalResult);
}
break;
case ExpansionKind.NonPublicMembers:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Resources.NonPublicMembers,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: null,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.StaticMembers:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Formatter.StaticMembersString,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: null,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Class,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.RawView:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: Resources.RawView,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: null,
EditableValue: dataItem.EditableValue,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.ResultsView:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
Name: dataItem.Name,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: Resources.ResultsViewValueWarning,
EditableValue: null,
Type: string.Empty,
Category: DkmEvaluationResultCategory.Method,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.TypeVariable:
completionRoutine(DkmSuccessEvaluationResult.Create(
inspectionContext,
stackFrame,
dataItem.Name,
dataItem.FullName,
dataItem.Flags,
dataItem.DisplayValue,
EditableValue: null,
Type: dataItem.DisplayValue,
Category: DkmEvaluationResultCategory.Data,
Access: DkmEvaluationResultAccessType.None,
StorageType: DkmEvaluationResultStorageType.None,
TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None,
Address: dataItem.Value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
break;
case ExpansionKind.PointerDereference:
case ExpansionKind.Default:
// This call will evaluate DebuggerDisplayAttributes.
GetResultAndContinue(
dataItem,
workList,
declaredType: DkmClrType.Create(dataItem.Value.Type.AppDomain, dataItem.DeclaredTypeAndInfo.Type),
declaredTypeInfo: dataItem.DeclaredTypeAndInfo.Info,
inspectionContext: inspectionContext,
parent: dataItem.Parent,
completionRoutine: completionRoutine);
break;
default:
throw ExceptionUtilities.UnexpectedValue(dataItem.Kind);
}
}
private static DkmEvaluationResult CreateEvaluationResult(
DkmInspectionContext inspectionContext,
DkmClrValue value,
string name,
string typeName,
string display,
EvalResultDataItem dataItem)
{
if (value.IsError())
{
// Evaluation failed
return DkmFailedEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: name,
FullName: dataItem.FullName,
ErrorMessage: display,
Flags: dataItem.Flags,
Type: typeName,
DataItem: dataItem);
}
else
{
ReadOnlyCollection<DkmCustomUIVisualizerInfo> customUIVisualizers = null;
if (!value.IsNull)
{
DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = value.Type.GetDebuggerCustomUIVisualizerInfo();
if (customUIVisualizerInfo != null)
{
customUIVisualizers = new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo);
}
}
// If the EvalResultDataItem doesn't specify a particular category, we'll just propagate DkmClrValue.Category,
// which typically appears to be set to the default value ("Other").
var category = (dataItem.Category != DkmEvaluationResultCategory.Other) ? dataItem.Category : value.Category;
// Valid value
return DkmSuccessEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: name,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: display,
EditableValue: dataItem.EditableValue,
Type: typeName,
Category: category,
Access: value.Access,
StorageType: value.StorageType,
TypeModifierFlags: value.TypeModifierFlags,
Address: value.Address,
CustomUIVisualizers: customUIVisualizers,
ExternalModules: null,
DataItem: dataItem);
}
}
/// <returns>
/// The qualified name (i.e. including containing types and namespaces) of a named, pointer,
/// or array type followed by the qualified name of the actual runtime type, if provided.
/// </returns>
private static string GetTypeName(DkmInspectionContext inspectionContext, DkmClrValue value, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, ExpansionKind kind)
{
var declaredLmrType = declaredType.GetLmrType();
var runtimeType = value.Type;
var runtimeLmrType = runtimeType.GetLmrType();
var declaredTypeName = inspectionContext.GetTypeName(declaredType, declaredTypeInfo, Formatter.NoFormatSpecifiers);
var runtimeTypeName = inspectionContext.GetTypeName(runtimeType, CustomTypeInfo: null, FormatSpecifiers: Formatter.NoFormatSpecifiers);
var includeRuntimeTypeName =
!string.Equals(declaredTypeName, runtimeTypeName, StringComparison.OrdinalIgnoreCase) && // Names will reflect "dynamic", types will not.
!declaredLmrType.IsPointer &&
(kind != ExpansionKind.PointerDereference) &&
(!declaredLmrType.IsNullable() || value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown));
return includeRuntimeTypeName ?
string.Format("{0} {{{1}}}", declaredTypeName, runtimeTypeName) :
declaredTypeName;
}
internal EvalResultDataItem CreateDataItem(
DkmInspectionContext inspectionContext,
string name,
TypeAndCustomInfo typeDeclaringMemberAndInfo,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
EvalResultDataItem parent,
ExpansionFlags expansionFlags,
bool childShouldParenthesize,
string fullName,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultCategory category,
DkmEvaluationResultFlags flags,
DkmEvaluationFlags evalFlags)
{
if ((evalFlags & DkmEvaluationFlags.ShowValueRaw) != 0)
{
formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, "raw");
}
Expansion expansion;
// If the declared type is Nullable<T>, the value should
// have no expansion if null, or be expanded as a T.
var declaredType = declaredTypeAndInfo.Type;
var lmrNullableTypeArg = declaredType.GetNullableTypeArgument();
if (lmrNullableTypeArg != null && !value.HasExceptionThrown())
{
Debug.Assert(value.Type.GetProxyType() == null);
DkmClrValue nullableValue;
if (value.IsError())
{
expansion = null;
}
else if ((nullableValue = value.GetNullableValue(inspectionContext)) == null)
{
Debug.Assert(declaredType.Equals(value.Type.GetLmrType()));
// No expansion of "null".
expansion = null;
}
else
{
value = nullableValue;
Debug.Assert(lmrNullableTypeArg.Equals(value.Type.GetLmrType())); // If this is not the case, add a test for includeRuntimeTypeIfNecessary.
// CONSIDER: The DynamicAttribute for the type argument should just be Skip(1) of the original flag array.
expansion = this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(lmrNullableTypeArg), value, ExpansionFlags.IncludeResultsView);
}
}
else if (value.IsError() || (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0)
{
expansion = null;
}
else
{
expansion = DebuggerTypeProxyExpansion.CreateExpansion(
this,
inspectionContext,
name,
typeDeclaringMemberAndInfo,
declaredTypeAndInfo,
value,
childShouldParenthesize,
fullName,
flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName,
formatSpecifiers,
flags,
this.Formatter.GetEditableValue(value, inspectionContext));
if (expansion == null)
{
expansion = value.HasExceptionThrown()
? this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(value.Type), value, expansionFlags)
: this.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, expansionFlags);
}
}
return new EvalResultDataItem(
ExpansionKind.Default,
name,
typeDeclaringMemberAndInfo,
declaredTypeAndInfo,
parent: parent,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: childShouldParenthesize,
fullName: fullName,
childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName,
formatSpecifiers: formatSpecifiers,
category: category,
flags: flags,
editableValue: this.Formatter.GetEditableValue(value, inspectionContext),
inspectionContext: inspectionContext);
}
private void GetRootResultAndContinue(
DkmClrValue value,
WorkList workList,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
DkmInspectionContext inspectionContext,
string name,
CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
var type = value.Type.GetLmrType();
if (type.IsTypeVariables())
{
Debug.Assert(type.Equals(declaredType.GetLmrType()));
var declaredTypeAndInfo = new TypeAndCustomInfo(type, declaredTypeInfo);
var expansion = new TypeVariablesExpansion(declaredTypeAndInfo);
var dataItem = new EvalResultDataItem(
ExpansionKind.Default,
name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: declaredTypeAndInfo,
parent: null,
value: value,
displayValue: null,
expansion: expansion,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: null,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: DkmEvaluationResultCategory.Data,
flags: DkmEvaluationResultFlags.ReadOnly,
editableValue: null,
inspectionContext: inspectionContext);
Debug.Assert(dataItem.Flags == (DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable));
// Note: We're not including value.EvalFlags in Flags parameter
// below (there shouldn't be a reason to do so).
completionRoutine(DkmSuccessEvaluationResult.Create(
InspectionContext: inspectionContext,
StackFrame: value.StackFrame,
Name: Resources.TypeVariablesName,
FullName: dataItem.FullName,
Flags: dataItem.Flags,
Value: "",
EditableValue: null,
Type: "",
Category: dataItem.Category,
Access: value.Access,
StorageType: value.StorageType,
TypeModifierFlags: value.TypeModifierFlags,
Address: value.Address,
CustomUIVisualizers: null,
ExternalModules: null,
DataItem: dataItem));
}
else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ResultsOnly) != 0)
{
var dataItem = ResultsViewExpansion.CreateResultsOnlyRow(
inspectionContext,
name,
declaredType,
declaredTypeInfo,
value,
this.Formatter);
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else
{
var dataItem = ResultsViewExpansion.CreateResultsOnlyRowIfSynthesizedEnumerable(
inspectionContext,
name,
declaredType,
declaredTypeInfo,
value,
this.Formatter);
if (dataItem != null)
{
CreateEvaluationResultAndContinue(
dataItem,
workList,
inspectionContext,
value.StackFrame,
completionRoutine);
}
else
{
ReadOnlyCollection<string> formatSpecifiers;
var fullName = this.Formatter.TrimAndGetFormatSpecifiers(name, out formatSpecifiers);
dataItem = CreateDataItem(
inspectionContext,
name,
typeDeclaringMemberAndInfo: default(TypeAndCustomInfo),
declaredTypeAndInfo: new TypeAndCustomInfo(declaredType.GetLmrType(), declaredTypeInfo),
value: value,
parent: null,
expansionFlags: ExpansionFlags.All,
childShouldParenthesize: this.Formatter.NeedsParentheses(fullName),
fullName: fullName,
formatSpecifiers: formatSpecifiers,
category: DkmEvaluationResultCategory.Other,
flags: value.EvalFlags,
evalFlags: inspectionContext.EvaluationFlags);
GetResultAndContinue(dataItem, workList, declaredType, declaredTypeInfo, inspectionContext, parent: null, completionRoutine: completionRoutine);
}
}
}
private void GetResultAndContinue(
EvalResultDataItem dataItem,
WorkList workList,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
CompletionRoutine<DkmEvaluationResult> completionRoutine)
{
var value = dataItem.Value; // Value may have been replaced (specifically, for Nullable<T>).
DebuggerDisplayInfo displayInfo;
if (value.TryGetDebuggerDisplayInfo(out displayInfo))
{
var targetType = displayInfo.TargetType;
var attribute = displayInfo.Attribute;
CompletionRoutine<Exception> onException =
e => completionRoutine(CreateEvaluationResultFromException(e, dataItem, inspectionContext));
EvaluateDebuggerDisplayStringAndContinue(value, workList, inspectionContext, targetType, attribute.Name,
displayName => EvaluateDebuggerDisplayStringAndContinue(value, workList, inspectionContext, targetType, attribute.Value,
displayValue => EvaluateDebuggerDisplayStringAndContinue(value, workList, inspectionContext, targetType, attribute.TypeName,
displayType =>
{
completionRoutine(GetResult(inspectionContext, dataItem, declaredType, declaredTypeInfo, displayName.Result, displayValue.Result, displayType.Result, parent));
workList.Execute();
},
onException),
onException),
onException);
}
else
{
completionRoutine(GetResult(inspectionContext, dataItem, declaredType, declaredTypeInfo, displayName: null, displayValue: null, displayType: null, parent: parent));
}
}
private static void EvaluateDebuggerDisplayStringAndContinue(
DkmClrValue value,
WorkList workList,
DkmInspectionContext inspectionContext,
DkmClrType targetType,
string str,
CompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> onCompleted,
CompletionRoutine<Exception> onException)
{
DkmCompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> completionRoutine =
result =>
{
try
{
onCompleted(result);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.ReportNonFatalException(e, DkmComponentManager.ReportCurrentNonFatalException))
{
onException(e);
}
};
if (str == null)
{
completionRoutine(default(DkmEvaluateDebuggerDisplayStringAsyncResult));
}
else
{
value.EvaluateDebuggerDisplayString(workList.InnerWorkList, inspectionContext, targetType, str, completionRoutine);
}
}
private DkmEvaluationResult GetResult(
DkmInspectionContext inspectionContext,
EvalResultDataItem dataItem,
DkmClrType declaredType,
DkmClrCustomTypeInfo declaredTypeInfo,
string displayName,
string displayValue,
string displayType,
EvalResultDataItem parent)
{
var name = dataItem.Name;
Debug.Assert(name != null);
var typeDeclaringMemberAndInfo = dataItem.TypeDeclaringMemberAndInfo;
// Note: Don't respect the debugger display name on the root element:
// 1) In the Watch window, that's where the user's text goes.
// 2) In the Locals window, that's where the local name goes.
// Note: Dev12 respects the debugger display name in the Locals window,
// but not in the Watch window, but we can't distinguish and this
// behavior seems reasonable.
if (displayName != null && parent != null)
{
name = displayName;
}
else if (typeDeclaringMemberAndInfo.Type != null)
{
if (typeDeclaringMemberAndInfo.Type.IsInterface)
{
var interfaceTypeName = this.Formatter.GetTypeName(typeDeclaringMemberAndInfo, escapeKeywordIdentifiers: true);
name = string.Format("{0}.{1}", interfaceTypeName, name);
}
else
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
builder.Append(" (");
builder.Append(this.Formatter.GetTypeName(typeDeclaringMemberAndInfo));
builder.Append(')');
name = pooled.ToStringAndFree();
}
}
var value = dataItem.Value;
string display;
if (value.HasExceptionThrown())
{
display = dataItem.DisplayValue ?? value.GetExceptionMessage(dataItem.FullNameWithoutFormatSpecifiers, this.Formatter);
}
else if (displayValue != null)
{
display = value.IncludeObjectId(displayValue);
}
else
{
display = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers);
}
var typeName = displayType ?? GetTypeName(inspectionContext, value, declaredType, declaredTypeInfo, dataItem.Kind);
return CreateEvaluationResult(inspectionContext, value, name, typeName, display, dataItem);
}
private void GetChildrenAndContinue(EvalResultDataItem dataItem, DkmWorkList workList, DkmStackWalkFrame stackFrame, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine)
{
var expansion = dataItem.Expansion;
var rows = ArrayBuilder<EvalResultDataItem>.GetInstance();
int index = 0;
if (expansion != null)
{
expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, 0, initialRequestSize, visitAll: true, index: ref index);
}
var numRows = rows.Count;
Debug.Assert(index >= numRows);
Debug.Assert(initialRequestSize >= numRows);
var initialChildren = new DkmEvaluationResult[numRows];
var wl = new WorkList(workList, e => completionRoutine(DkmGetChildrenAsyncResult.CreateErrorResult(e)));
GetEvaluationResultsAndContinue(rows, initialChildren, 0, numRows, wl, inspectionContext, stackFrame,
() => wl.ContinueWith(
() =>
{
var enumContext = DkmEvaluationResultEnumContext.Create(index, stackFrame, inspectionContext, new EnumContextDataItem(dataItem));
completionRoutine(new DkmGetChildrenAsyncResult(initialChildren, enumContext));
rows.Free();
}));
wl.Execute();
}
private void GetItemsAndContinue(EvalResultDataItem dataItem, DkmWorkList workList, int startIndex, int count, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine)
{
var expansion = dataItem.Expansion;
var value = dataItem.Value;
var rows = ArrayBuilder<EvalResultDataItem>.GetInstance();
if (expansion != null)
{
int index = 0;
expansion.GetRows(this, rows, inspectionContext, dataItem, value, startIndex, count, visitAll: false, index: ref index);
}
var numRows = rows.Count;
Debug.Assert(count >= numRows);
var results = new DkmEvaluationResult[numRows];
var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationEnumAsyncResult.CreateErrorResult(e)));
GetEvaluationResultsAndContinue(rows, results, 0, numRows, wl, inspectionContext, value.StackFrame,
() => wl.ContinueWith(
() =>
{
completionRoutine(new DkmEvaluationEnumAsyncResult(results));
rows.Free();
}));
wl.Execute();
}
private void GetEvaluationResultsAndContinue(ArrayBuilder<EvalResultDataItem> rows, DkmEvaluationResult[] results, int index, int numRows, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine completionRoutine)
{
if (index < numRows)
{
CreateEvaluationResultAndContinue(rows[index], workList, inspectionContext, stackFrame,
result => workList.ContinueWith(
() =>
{
results[index] = result;
GetEvaluationResultsAndContinue(rows, results, index + 1, numRows, workList, inspectionContext, stackFrame, completionRoutine);
}));
}
else
{
completionRoutine();
}
}
internal Expansion GetTypeExpansion(
DkmInspectionContext inspectionContext,
TypeAndCustomInfo declaredTypeAndInfo,
DkmClrValue value,
ExpansionFlags flags)
{
var declaredType = declaredTypeAndInfo.Type;
Debug.Assert(!declaredType.IsTypeVariables());
if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0)
{
return null;
}
var runtimeType = value.Type.GetLmrType();
// If the value is an array, expand the array elements.
if (runtimeType.IsArray)
{
var sizes = value.ArrayDimensions;
if (sizes == null)
{
// Null array. No expansion.
return null;
}
var lowerBounds = value.ArrayLowerBounds;
Type elementType;
DkmClrCustomTypeInfo elementTypeInfo;
if (declaredType.IsArray)
{
elementType = declaredType.GetElementType();
elementTypeInfo = new DynamicFlagsCustomTypeInfo(declaredTypeAndInfo.Info).SkipOne().GetCustomTypeInfo();
}
else
{
elementType = runtimeType.GetElementType();
elementTypeInfo = null;
}
return ArrayExpansion.CreateExpansion(new TypeAndCustomInfo(elementType, elementTypeInfo), sizes, lowerBounds);
}
if (this.Formatter.IsPredefinedType(runtimeType))
{
return null;
}
if (declaredType.IsPointer)
{
// If this ever happens, the element type info is just .SkipOne().
Debug.Assert(!new DynamicFlagsCustomTypeInfo(declaredTypeAndInfo.Info).Any());
var elementType = declaredType.GetElementType();
return value.IsNull || elementType.IsVoid()
? null
: new PointerDereferenceExpansion(new TypeAndCustomInfo(elementType));
}
if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown) &&
runtimeType.IsEmptyResultsViewException())
{
// The value is an exception thrown expanding an empty
// IEnumerable. Use the runtime type of the exception and
// skip base types. (This matches the native EE behavior
// to expose a single property from the exception.)
flags &= ~ExpansionFlags.IncludeBaseMembers;
}
return MemberExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, flags, TypeHelpers.IsVisibleMember, this.Formatter);
}
private static DkmEvaluationResult CreateEvaluationResultFromException(Exception e, EvalResultDataItem dataItem, DkmInspectionContext inspectionContext)
{
return DkmFailedEvaluationResult.Create(
inspectionContext,
dataItem.Value.StackFrame,
Name: dataItem.Name,
FullName: null,
ErrorMessage: e.Message,
Flags: DkmEvaluationResultFlags.None,
Type: null,
DataItem: null);
}
private sealed class WorkList
{
internal readonly DkmWorkList InnerWorkList;
private readonly CompletionRoutine<Exception> _onException;
private CompletionRoutine _completionRoutine;
internal WorkList(DkmWorkList workList, CompletionRoutine<Exception> onException)
{
InnerWorkList = workList;
_onException = onException;
}
internal void ContinueWith(CompletionRoutine completionRoutine)
{
Debug.Assert(_completionRoutine == null);
_completionRoutine = completionRoutine;
}
internal void Execute()
{
while (_completionRoutine != null)
{
var completionRoutine = _completionRoutine;
_completionRoutine = null;
try
{
completionRoutine();
}
catch (Exception e) when (ExpressionEvaluatorFatalError.ReportNonFatalException(e, DkmComponentManager.ReportCurrentNonFatalException))
{
_onException(e);
}
}
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: crm/rpc/correspondence_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.CRM.RPC {
public static partial class CorrespondenceSvc
{
static readonly string __ServiceName = "holms.types.crm.rpc.CorrespondenceSvc";
static readonly grpc::Marshaller<global::HOLMS.Types.CRM.RPC.CorrespondenceRequest> __Marshaller_CorrespondenceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.RPC.CorrespondenceRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> __Marshaller_CorrespondenceServiceEmailSendResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport> __Marshaller_CorrespondenceRequestForReport = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText> __Marshaller_PropertyArrivalLetterText = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Marshaller_HtmlReportResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.PbLocalDate> __Marshaller_PbLocalDate = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.PbLocalDate.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> __Marshaller_ReservationIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Indicators.ReservationIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText> __Marshaller_PropertyConfirmationLetterText = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText> __Marshaller_PropertyCancellationLetterText = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator> __Marshaller_GroupBookingIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.CRM.RPC.PrintReservationRequest> __Marshaller_PrintReservationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.RPC.PrintReservationRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest> __Marshaller_PrintGroupReservationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions> __Marshaller_CorrespondenceRequestWithExclusions = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse> __Marshaller_CorrespondenceHideRateResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse.Parser.ParseFrom);
static readonly grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequest, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> __Method_SendConfirmationLetter = new grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequest, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse>(
grpc::MethodType.Unary,
__ServiceName,
"SendConfirmationLetter",
__Marshaller_CorrespondenceRequest,
__Marshaller_CorrespondenceServiceEmailSendResponse);
static readonly grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequest, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> __Method_SendCancellationEmail = new grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequest, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse>(
grpc::MethodType.Unary,
__ServiceName,
"SendCancellationEmail",
__Marshaller_CorrespondenceRequest,
__Marshaller_CorrespondenceServiceEmailSendResponse);
static readonly grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequest, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> __Method_SendGuestFolio = new grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequest, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse>(
grpc::MethodType.Unary,
__ServiceName,
"SendGuestFolio",
__Marshaller_CorrespondenceRequest,
__Marshaller_CorrespondenceServiceEmailSendResponse);
static readonly grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> __Method_SendReportToEmail = new grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse>(
grpc::MethodType.Unary,
__ServiceName,
"SendReportToEmail",
__Marshaller_CorrespondenceRequestForReport,
__Marshaller_CorrespondenceServiceEmailSendResponse);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_PreviewArrivalLetter = new grpc::Method<global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"PreviewArrivalLetter",
__Marshaller_PropertyArrivalLetterText,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Primitive.PbLocalDate, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetArrivalLetterDocumentsArrivingOn = new grpc::Method<global::HOLMS.Types.Primitive.PbLocalDate, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetArrivalLetterDocumentsArrivingOn",
__Marshaller_PbLocalDate,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetArrivalLetterDocument = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetArrivalLetterDocument",
__Marshaller_ReservationIndicator,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_PreviewConfirmationLetter = new grpc::Method<global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"PreviewConfirmationLetter",
__Marshaller_PropertyConfirmationLetterText,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_PreviewCancellationEmail = new grpc::Method<global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"PreviewCancellationEmail",
__Marshaller_PropertyCancellationLetterText,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetReservationFolioPrintDoc = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetReservationFolioPrintDoc",
__Marshaller_ReservationIndicator,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetGroupBookingFolioPrintDoc = new grpc::Method<global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetGroupBookingFolioPrintDoc",
__Marshaller_GroupBookingIndicator,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetReservationConfirmationPrintDoc = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetReservationConfirmationPrintDoc",
__Marshaller_ReservationIndicator,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.CRM.RPC.PrintReservationRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetReservationFolioPrintDocExcluded = new grpc::Method<global::HOLMS.Types.CRM.RPC.PrintReservationRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetReservationFolioPrintDocExcluded",
__Marshaller_PrintReservationRequest,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> __Method_GetGroupBookingFolioPrintDocExcluded = new grpc::Method<global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest, global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetGroupBookingFolioPrintDocExcluded",
__Marshaller_PrintGroupReservationRequest,
__Marshaller_HtmlReportResponse);
static readonly grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> __Method_SendGuestFolioExcluded = new grpc::Method<global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions, global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse>(
grpc::MethodType.Unary,
__ServiceName,
"SendGuestFolioExcluded",
__Marshaller_CorrespondenceRequestWithExclusions,
__Marshaller_CorrespondenceServiceEmailSendResponse);
static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse> __Method_GetCorrespondenceHideRate = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse>(
grpc::MethodType.Unary,
__ServiceName,
"GetCorrespondenceHideRate",
__Marshaller_ReservationIndicator,
__Marshaller_CorrespondenceHideRateResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.CRM.RPC.CorrespondenceSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of CorrespondenceSvc</summary>
public abstract partial class CorrespondenceSvcBase
{
/// <summary>
/// Email
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendConfirmationLetter(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendCancellationEmail(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendGuestFolio(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendReportToEmail(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Print (get HTML)
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewArrivalLetter(global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetArrivalLetterDocumentsArrivingOn(global::HOLMS.Types.Primitive.PbLocalDate request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetArrivalLetterDocument(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewConfirmationLetter(global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Don't think this is used?
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewCancellationEmail(global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioPrintDoc(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetGroupBookingFolioPrintDoc(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationConfirmationPrintDoc(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioPrintDocExcluded(global::HOLMS.Types.CRM.RPC.PrintReservationRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetGroupBookingFolioPrintDocExcluded(global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendGuestFolioExcluded(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse> GetCorrespondenceHideRate(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for CorrespondenceSvc</summary>
public partial class CorrespondenceSvcClient : grpc::ClientBase<CorrespondenceSvcClient>
{
/// <summary>Creates a new client for CorrespondenceSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public CorrespondenceSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for CorrespondenceSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public CorrespondenceSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected CorrespondenceSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected CorrespondenceSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Email
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendConfirmationLetter(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendConfirmationLetter(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Email
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendConfirmationLetter(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SendConfirmationLetter, null, options, request);
}
/// <summary>
/// Email
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendConfirmationLetterAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendConfirmationLetterAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Email
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendConfirmationLetterAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SendConfirmationLetter, null, options, request);
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendCancellationEmail(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendCancellationEmail(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendCancellationEmail(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SendCancellationEmail, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendCancellationEmailAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendCancellationEmailAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendCancellationEmailAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SendCancellationEmail, null, options, request);
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendGuestFolio(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendGuestFolio(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendGuestFolio(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SendGuestFolio, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendGuestFolioAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendGuestFolioAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendGuestFolioAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SendGuestFolio, null, options, request);
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendReportToEmail(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendReportToEmail(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendReportToEmail(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SendReportToEmail, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendReportToEmailAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendReportToEmailAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendReportToEmailAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestForReport request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SendReportToEmail, null, options, request);
}
/// <summary>
/// Print (get HTML)
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse PreviewArrivalLetter(global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PreviewArrivalLetter(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Print (get HTML)
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse PreviewArrivalLetter(global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PreviewArrivalLetter, null, options, request);
}
/// <summary>
/// Print (get HTML)
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewArrivalLetterAsync(global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PreviewArrivalLetterAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Print (get HTML)
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewArrivalLetterAsync(global::HOLMS.Types.TenancyConfig.PropertyArrivalLetterText request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PreviewArrivalLetter, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetArrivalLetterDocumentsArrivingOn(global::HOLMS.Types.Primitive.PbLocalDate request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetArrivalLetterDocumentsArrivingOn(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetArrivalLetterDocumentsArrivingOn(global::HOLMS.Types.Primitive.PbLocalDate request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetArrivalLetterDocumentsArrivingOn, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetArrivalLetterDocumentsArrivingOnAsync(global::HOLMS.Types.Primitive.PbLocalDate request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetArrivalLetterDocumentsArrivingOnAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetArrivalLetterDocumentsArrivingOnAsync(global::HOLMS.Types.Primitive.PbLocalDate request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetArrivalLetterDocumentsArrivingOn, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetArrivalLetterDocument(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetArrivalLetterDocument(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetArrivalLetterDocument(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetArrivalLetterDocument, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetArrivalLetterDocumentAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetArrivalLetterDocumentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetArrivalLetterDocumentAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetArrivalLetterDocument, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse PreviewConfirmationLetter(global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PreviewConfirmationLetter(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse PreviewConfirmationLetter(global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PreviewConfirmationLetter, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewConfirmationLetterAsync(global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PreviewConfirmationLetterAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewConfirmationLetterAsync(global::HOLMS.Types.TenancyConfig.PropertyConfirmationLetterText request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PreviewConfirmationLetter, null, options, request);
}
/// <summary>
/// Don't think this is used?
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse PreviewCancellationEmail(global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PreviewCancellationEmail(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Don't think this is used?
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse PreviewCancellationEmail(global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_PreviewCancellationEmail, null, options, request);
}
/// <summary>
/// Don't think this is used?
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewCancellationEmailAsync(global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PreviewCancellationEmailAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Don't think this is used?
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> PreviewCancellationEmailAsync(global::HOLMS.Types.TenancyConfig.PropertyCancellationLetterText request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_PreviewCancellationEmail, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetReservationFolioPrintDoc(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationFolioPrintDoc(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetReservationFolioPrintDoc(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetReservationFolioPrintDoc, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioPrintDocAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationFolioPrintDocAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioPrintDocAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetReservationFolioPrintDoc, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetGroupBookingFolioPrintDoc(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetGroupBookingFolioPrintDoc(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetGroupBookingFolioPrintDoc(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetGroupBookingFolioPrintDoc, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetGroupBookingFolioPrintDocAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetGroupBookingFolioPrintDocAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetGroupBookingFolioPrintDocAsync(global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetGroupBookingFolioPrintDoc, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetReservationConfirmationPrintDoc(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationConfirmationPrintDoc(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetReservationConfirmationPrintDoc(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetReservationConfirmationPrintDoc, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationConfirmationPrintDocAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationConfirmationPrintDocAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationConfirmationPrintDocAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetReservationConfirmationPrintDoc, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetReservationFolioPrintDocExcluded(global::HOLMS.Types.CRM.RPC.PrintReservationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationFolioPrintDocExcluded(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetReservationFolioPrintDocExcluded(global::HOLMS.Types.CRM.RPC.PrintReservationRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetReservationFolioPrintDocExcluded, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioPrintDocExcludedAsync(global::HOLMS.Types.CRM.RPC.PrintReservationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetReservationFolioPrintDocExcludedAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetReservationFolioPrintDocExcludedAsync(global::HOLMS.Types.CRM.RPC.PrintReservationRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetReservationFolioPrintDocExcluded, null, options, request);
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetGroupBookingFolioPrintDocExcluded(global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetGroupBookingFolioPrintDocExcluded(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse GetGroupBookingFolioPrintDocExcluded(global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetGroupBookingFolioPrintDocExcluded, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetGroupBookingFolioPrintDocExcludedAsync(global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetGroupBookingFolioPrintDocExcludedAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Reporting.Outputs.HtmlReportResponse> GetGroupBookingFolioPrintDocExcludedAsync(global::HOLMS.Types.CRM.RPC.PrintGroupReservationRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetGroupBookingFolioPrintDocExcluded, null, options, request);
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendGuestFolioExcluded(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendGuestFolioExcluded(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse SendGuestFolioExcluded(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SendGuestFolioExcluded, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendGuestFolioExcludedAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SendGuestFolioExcludedAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceServiceEmailSendResponse> SendGuestFolioExcludedAsync(global::HOLMS.Types.CRM.RPC.CorrespondenceRequestWithExclusions request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SendGuestFolioExcluded, null, options, request);
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse GetCorrespondenceHideRate(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetCorrespondenceHideRate(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse GetCorrespondenceHideRate(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetCorrespondenceHideRate, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse> GetCorrespondenceHideRateAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetCorrespondenceHideRateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.RPC.CorrespondenceHideRateResponse> GetCorrespondenceHideRateAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetCorrespondenceHideRate, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override CorrespondenceSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new CorrespondenceSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(CorrespondenceSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_SendConfirmationLetter, serviceImpl.SendConfirmationLetter)
.AddMethod(__Method_SendCancellationEmail, serviceImpl.SendCancellationEmail)
.AddMethod(__Method_SendGuestFolio, serviceImpl.SendGuestFolio)
.AddMethod(__Method_SendReportToEmail, serviceImpl.SendReportToEmail)
.AddMethod(__Method_PreviewArrivalLetter, serviceImpl.PreviewArrivalLetter)
.AddMethod(__Method_GetArrivalLetterDocumentsArrivingOn, serviceImpl.GetArrivalLetterDocumentsArrivingOn)
.AddMethod(__Method_GetArrivalLetterDocument, serviceImpl.GetArrivalLetterDocument)
.AddMethod(__Method_PreviewConfirmationLetter, serviceImpl.PreviewConfirmationLetter)
.AddMethod(__Method_PreviewCancellationEmail, serviceImpl.PreviewCancellationEmail)
.AddMethod(__Method_GetReservationFolioPrintDoc, serviceImpl.GetReservationFolioPrintDoc)
.AddMethod(__Method_GetGroupBookingFolioPrintDoc, serviceImpl.GetGroupBookingFolioPrintDoc)
.AddMethod(__Method_GetReservationConfirmationPrintDoc, serviceImpl.GetReservationConfirmationPrintDoc)
.AddMethod(__Method_GetReservationFolioPrintDocExcluded, serviceImpl.GetReservationFolioPrintDocExcluded)
.AddMethod(__Method_GetGroupBookingFolioPrintDocExcluded, serviceImpl.GetGroupBookingFolioPrintDocExcluded)
.AddMethod(__Method_SendGuestFolioExcluded, serviceImpl.SendGuestFolioExcluded)
.AddMethod(__Method_GetCorrespondenceHideRate, serviceImpl.GetCorrespondenceHideRate).Build();
}
}
}
#endregion
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
namespace System.ServiceModel
{
public class DuplexChannelFactory<TChannel> : ChannelFactory<TChannel>
{
//Type overloads
public DuplexChannelFactory(Type callbackInstanceType)
: this((object)callbackInstanceType)
{ }
public DuplexChannelFactory(Type callbackInstanceType, Binding binding, String remoteAddress)
: this((object)callbackInstanceType, binding, new EndpointAddress(remoteAddress))
{ }
public DuplexChannelFactory(Type callbackInstanceType, Binding binding, EndpointAddress remoteAddress)
: this((object)callbackInstanceType, binding, remoteAddress)
{ }
public DuplexChannelFactory(Type callbackInstanceType, Binding binding)
: this((object)callbackInstanceType, binding)
{ }
public DuplexChannelFactory(Type callbackInstanceType, string endpointConfigurationName, EndpointAddress remoteAddress)
: this((object)callbackInstanceType, endpointConfigurationName, remoteAddress)
{ }
public DuplexChannelFactory(Type callbackInstanceType, string endpointConfigurationName)
: this((object)callbackInstanceType, endpointConfigurationName)
{ }
public DuplexChannelFactory(Type callbackInstanceType, ServiceEndpoint endpoint)
: this((object)callbackInstanceType, endpoint)
{ }
//InstanceContext overloads
public DuplexChannelFactory(InstanceContext callbackInstance)
: this((object)callbackInstance)
{ }
public DuplexChannelFactory(InstanceContext callbackInstance, Binding binding, String remoteAddress)
: this((object)callbackInstance, binding, new EndpointAddress(remoteAddress))
{ }
public DuplexChannelFactory(InstanceContext callbackInstance, Binding binding, EndpointAddress remoteAddress)
: this((object)callbackInstance, binding, remoteAddress)
{ }
public DuplexChannelFactory(InstanceContext callbackInstance, Binding binding)
: this((object)callbackInstance, binding)
{ }
public DuplexChannelFactory(InstanceContext callbackInstance, string endpointConfigurationName, EndpointAddress remoteAddress)
: this((object)callbackInstance, endpointConfigurationName, remoteAddress)
{ }
public DuplexChannelFactory(InstanceContext callbackInstance, string endpointConfigurationName)
: this((object)callbackInstance, endpointConfigurationName)
{ }
public DuplexChannelFactory(InstanceContext callbackInstance, ServiceEndpoint endpoint)
: this((object)callbackInstance, endpoint)
{ }
// TChannel provides ContractDescription
public DuplexChannelFactory(object callbackObject)
: base(typeof(TChannel))
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, TraceUtility.CreateSourceString(this)), ActivityType.Construct);
}
if (callbackObject == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackObject");
}
this.CheckAndAssignCallbackInstance(callbackObject);
this.InitializeEndpoint((string)null, (EndpointAddress)null);
}
}
// TChannel provides ContractDescription, attr/config [TChannel,name] provides Address,Binding
public DuplexChannelFactory(object callbackObject, string endpointConfigurationName)
: this(callbackObject, endpointConfigurationName, null)
{
}
// TChannel provides ContractDescription, attr/config [TChannel,name] provides Binding, provide Address explicitly
public DuplexChannelFactory(object callbackObject, string endpointConfigurationName, EndpointAddress remoteAddress)
: base(typeof(TChannel))
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, TraceUtility.CreateSourceString(this)), ActivityType.Construct);
}
if (callbackObject == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackObject");
}
if (endpointConfigurationName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName");
}
this.CheckAndAssignCallbackInstance(callbackObject);
this.InitializeEndpoint(endpointConfigurationName, remoteAddress);
}
}
// TChannel provides ContractDescription, attr/config [TChannel,name] provides Address,Binding
public DuplexChannelFactory(object callbackObject, Binding binding)
: this(callbackObject, binding, (EndpointAddress)null)
{
}
// TChannel provides ContractDescription, provide Address,Binding explicitly
public DuplexChannelFactory(object callbackObject, Binding binding, String remoteAddress)
: this(callbackObject, binding, new EndpointAddress(remoteAddress))
{
}
// TChannel provides ContractDescription, provide Address,Binding explicitly
public DuplexChannelFactory(object callbackObject, Binding binding, EndpointAddress remoteAddress)
: base(typeof(TChannel))
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, TraceUtility.CreateSourceString(this)), ActivityType.Construct);
}
if (callbackObject == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackObject");
}
if (binding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
}
this.CheckAndAssignCallbackInstance(callbackObject);
this.InitializeEndpoint(binding, remoteAddress);
}
}
// provide ContractDescription,Address,Binding explicitly
public DuplexChannelFactory(object callbackObject, ServiceEndpoint endpoint)
: base(typeof(TChannel))
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, TraceUtility.CreateSourceString(this)), ActivityType.Construct);
}
if (callbackObject == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackObject");
}
if (endpoint == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint");
}
this.CheckAndAssignCallbackInstance(callbackObject);
this.InitializeEndpoint(endpoint);
}
}
internal void CheckAndAssignCallbackInstance(object callbackInstance)
{
if (callbackInstance is Type)
{
this.CallbackType = (Type)callbackInstance;
}
else if (callbackInstance is InstanceContext)
{
this.CallbackInstance = (InstanceContext)callbackInstance;
}
else
{
this.CallbackInstance = new InstanceContext(callbackInstance);
}
}
public TChannel CreateChannel(InstanceContext callbackInstance)
{
return CreateChannel(callbackInstance, CreateEndpointAddress(this.Endpoint), null);
}
public TChannel CreateChannel(InstanceContext callbackInstance, EndpointAddress address)
{
if (address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
}
return CreateChannel(callbackInstance, address, address.Uri);
}
public override TChannel CreateChannel(EndpointAddress address, Uri via)
{
return CreateChannel(this.CallbackInstance, address, via);
}
public virtual TChannel CreateChannel(InstanceContext callbackInstance, EndpointAddress address, Uri via)
{
if (address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
}
if (this.CallbackType != null && callbackInstance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxCreateDuplexChannelNoCallback1));
}
if (callbackInstance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxCreateDuplexChannelNoCallback));
}
if (callbackInstance.UserObject == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxCreateDuplexChannelNoCallbackUserObject));
}
if (!this.HasDuplexOperations())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxCreateDuplexChannel1, this.Endpoint.Contract.Name)));
}
Type userObjectType = callbackInstance.UserObject.GetType();
Type callbackType = this.Endpoint.Contract.CallbackContractType;
if (callbackType != null && !callbackType.IsAssignableFrom(userObjectType))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.SFxCreateDuplexChannelBadCallbackUserObject, callbackType)));
}
EnsureOpened();
TChannel result = this.ServiceChannelFactory.CreateChannel<TChannel>(address, via);
// Desktop: this.ServiceChannelFactory.CreateChannel(typeof(TChannel), address, via);
IDuplexContextChannel duplexChannel = result as IDuplexContextChannel;
if (duplexChannel != null)
{
duplexChannel.CallbackInstance = callbackInstance;
}
return result;
}
//Static functions to create channels
private static InstanceContext GetInstanceContextForObject(object callbackObject)
{
if (callbackObject is InstanceContext)
{
return (InstanceContext)callbackObject;
}
return new InstanceContext(callbackObject);
}
public static TChannel CreateChannel(object callbackObject, String endpointConfigurationName)
{
return CreateChannel(GetInstanceContextForObject(callbackObject), endpointConfigurationName);
}
public static TChannel CreateChannel(object callbackObject, Binding binding, EndpointAddress endpointAddress)
{
return CreateChannel(GetInstanceContextForObject(callbackObject), binding, endpointAddress);
}
public static TChannel CreateChannel(object callbackObject, Binding binding, EndpointAddress endpointAddress, Uri via)
{
return CreateChannel(GetInstanceContextForObject(callbackObject), binding, endpointAddress, via);
}
public static TChannel CreateChannel(InstanceContext callbackInstance, String endpointConfigurationName)
{
DuplexChannelFactory<TChannel> channelFactory = new DuplexChannelFactory<TChannel>(callbackInstance, endpointConfigurationName);
TChannel channel = channelFactory.CreateChannel();
SetFactoryToAutoClose(channel);
return channel;
}
public static TChannel CreateChannel(InstanceContext callbackInstance, Binding binding, EndpointAddress endpointAddress)
{
DuplexChannelFactory<TChannel> channelFactory = new DuplexChannelFactory<TChannel>(callbackInstance, binding, endpointAddress);
TChannel channel = channelFactory.CreateChannel();
SetFactoryToAutoClose(channel);
return channel;
}
public static TChannel CreateChannel(InstanceContext callbackInstance, Binding binding, EndpointAddress endpointAddress, Uri via)
{
DuplexChannelFactory<TChannel> channelFactory = new DuplexChannelFactory<TChannel>(callbackInstance, binding);
TChannel channel = channelFactory.CreateChannel(endpointAddress, via);
SetFactoryToAutoClose(channel);
return channel;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Fabric;
using System.Fabric.Description;
using System.Net;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Newtonsoft.Json;
using NSubstitute;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Hosting.ServiceFabric;
using Orleans.ServiceFabric;
using Xunit;
namespace TestServiceFabric
{
[TestCategory("ServiceFabric"), TestCategory("Functional")]
public class OrleansCommunicationListenerTests
{
private readonly ICodePackageActivationContext activationContext = Substitute.For<ICodePackageActivationContext>();
private readonly NodeContext nodeContext = new NodeContext(
"bobble",
new NodeId(BigInteger.One, BigInteger.One),
BigInteger.One,
"amazing",
Dns.GetHostName());
private readonly MockServiceContext serviceContext;
public OrleansCommunicationListenerTests()
{
serviceContext = new MockServiceContext(
this.nodeContext,
this.activationContext,
"ChocolateMunchingService",
new Uri("fabric:/Cocoa/ChocolateMunchingService"),
new byte[0],
Guid.NewGuid(),
9823);
}
[Fact]
public async Task SimpleUsageScenarioTest()
{
var endpoints = new EndpointsCollection
{
CreateEndpoint(ServiceFabricConstants.SiloEndpointName, 9082),
CreateEndpoint(ServiceFabricConstants.GatewayEndpointName, 8888)
};
activationContext.GetEndpoints().Returns(_ => endpoints);
var listener = new OrleansCommunicationListener(
builder =>
{
builder.ConfigureServices(
services =>
{
// Use our mock silo host.
services.Replace(ServiceDescriptor.Singleton<ISiloHost>(sp => Substitute.ForPartsOf<MockSiloHost>(sp)));
});
builder.UseLocalhostClustering();
builder.Configure<EndpointOptions>(options =>
{
options.SiloPort = 9082;
options.GatewayPort = 8888;
});
});
var result = await listener.OpenAsync(CancellationToken.None);
var siloHost = listener.Host;
var publishedEndpoints = JsonConvert.DeserializeObject<FabricSiloInfo>(result);
var siloAddress = publishedEndpoints.SiloAddress;
siloAddress.Generation.Should().NotBe(0);
siloAddress.Endpoint.Port.ShouldBeEquivalentTo(9082);
var gatewayAddress = publishedEndpoints.GatewayAddress;
gatewayAddress.Generation.Should().Be(0);
gatewayAddress.Endpoint.Port.ShouldBeEquivalentTo(8888);
await siloHost.ReceivedWithAnyArgs(1).StartAsync(Arg.Is<CancellationToken>(c => !c.IsCancellationRequested));
await siloHost.DidNotReceive().StopAsync(Arg.Any<CancellationToken>());
siloHost.ClearReceivedCalls();
await listener.CloseAsync(CancellationToken.None);
await siloHost.ReceivedWithAnyArgs(1).StopAsync(Arg.Is<CancellationToken>(c => !c.IsCancellationRequested));
await siloHost.DidNotReceiveWithAnyArgs().StartAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task AbortStopAndDisposesSilo()
{
var endpoints = new EndpointsCollection
{
CreateEndpoint(ServiceFabricConstants.SiloEndpointName, 9082),
CreateEndpoint(ServiceFabricConstants.GatewayEndpointName, 8888)
};
activationContext.GetEndpoints().Returns(_ => endpoints);
var listener = new OrleansCommunicationListener(
builder =>
{
builder.ConfigureServices(
services =>
{
// Use our mock silo host.
services.Replace(ServiceDescriptor.Singleton<ISiloHost>(sp => Substitute.ForPartsOf<MockSiloHost>(sp)));
});
builder.Configure<EndpointOptions>(options =>
{
options.SiloPort = 9082;
options.GatewayPort = 8888;
});
builder.UseLocalhostClustering();
});
await listener.OpenAsync(CancellationToken.None);
var siloHost = listener.Host;
siloHost.ClearReceivedCalls();
listener.Abort();
await siloHost.ReceivedWithAnyArgs(1).StopAsync(Arg.Is<CancellationToken>(c => c.IsCancellationRequested));
await siloHost.DidNotReceiveWithAnyArgs().StartAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task CloseStopsSilo()
{
var endpoints = new EndpointsCollection
{
CreateEndpoint(ServiceFabricConstants.SiloEndpointName, 9082),
CreateEndpoint(ServiceFabricConstants.GatewayEndpointName, 8888)
};
activationContext.GetEndpoints().Returns(_ => endpoints);
var listener = new OrleansCommunicationListener(
builder =>
{
builder.ConfigureServices(
services =>
{
// Use our mock silo host.
services.Replace(ServiceDescriptor.Singleton<ISiloHost>(sp => Substitute.ForPartsOf<MockSiloHost>(sp)));
});
builder.Configure<EndpointOptions>(options =>
{
options.SiloPort = 9082;
options.GatewayPort = 8888;
});
builder.UseLocalhostClustering();
});
await listener.OpenAsync(CancellationToken.None);
var siloHost = listener.Host;
siloHost.ClearReceivedCalls();
await listener.CloseAsync(CancellationToken.None);
await siloHost.ReceivedWithAnyArgs(1).StopAsync(Arg.Is<CancellationToken>(c => !c.IsCancellationRequested));
await siloHost.DidNotReceiveWithAnyArgs().StartAsync(Arg.Any<CancellationToken>());
}
private static EndpointResourceDescription CreateEndpoint(string name, int port)
{
var endpoint = new EndpointResourceDescription { Name = name };
typeof(EndpointResourceDescription).GetProperty("Port")
.GetSetMethod(true)
.Invoke(endpoint, new object[] { port });
return endpoint;
}
public class MockSiloHost : ISiloHost
{
private readonly TaskCompletionSource<int> stopped = new TaskCompletionSource<int>();
public MockSiloHost(IServiceProvider services)
{
this.Services = services;
}
/// <inheritdoc />
public virtual IServiceProvider Services { get; }
/// <inheritdoc />
public virtual Task Stopped => this.stopped.Task;
/// <inheritdoc />
public virtual async Task StartAsync(CancellationToken cancellationToken)
{
// Await to avoid compiler warnings.
await Task.CompletedTask;
}
/// <inheritdoc />
public virtual Task StopAsync(CancellationToken cancellationToken)
{
this.stopped.TrySetResult(0);
return Task.CompletedTask;
}
public void Dispose()
{
}
public ValueTask DisposeAsync() => default;
}
}
/// <summary>
/// A grain which is not used but which satisfies startup configuration checks.
/// </summary>
public class UnusedGrain : Grain { }
public interface IUnusedGrain : IGrain { }
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D05_CountryColl (editable child list).<br/>
/// This is a generated base class of <see cref="D05_CountryColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="D04_SubContinent"/> editable child object.<br/>
/// The items of the collection are <see cref="D06_Country"/> objects.
/// </remarks>
[Serializable]
public partial class D05_CountryColl : BusinessListBase<D05_CountryColl, D06_Country>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="D06_Country"/> item from the collection.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to be removed.</param>
public void Remove(int country_ID)
{
foreach (var d06_Country in this)
{
if (d06_Country.Country_ID == country_ID)
{
Remove(d06_Country);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="D06_Country"/> item is in the collection.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to search for.</param>
/// <returns><c>true</c> if the D06_Country is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int country_ID)
{
foreach (var d06_Country in this)
{
if (d06_Country.Country_ID == country_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="D06_Country"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="country_ID">The Country_ID of the item to search for.</param>
/// <returns><c>true</c> if the D06_Country is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int country_ID)
{
foreach (var d06_Country in DeletedList)
{
if (d06_Country.Country_ID == country_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="D06_Country"/> item of the <see cref="D05_CountryColl"/> collection, based on a given Country_ID.
/// </summary>
/// <param name="country_ID">The Country_ID.</param>
/// <returns>A <see cref="D06_Country"/> object.</returns>
public D06_Country FindD06_CountryByCountry_ID(int country_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Country_ID.Equals(country_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D05_CountryColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="D05_CountryColl"/> collection.</returns>
internal static D05_CountryColl NewD05_CountryColl()
{
return DataPortal.CreateChild<D05_CountryColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="D05_CountryColl"/> collection, based on given parameters.
/// </summary>
/// <param name="parent_SubContinent_ID">The Parent_SubContinent_ID parameter of the D05_CountryColl to fetch.</param>
/// <returns>A reference to the fetched <see cref="D05_CountryColl"/> collection.</returns>
internal static D05_CountryColl GetD05_CountryColl(int parent_SubContinent_ID)
{
return DataPortal.FetchChild<D05_CountryColl>(parent_SubContinent_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D05_CountryColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D05_CountryColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="D05_CountryColl"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="parent_SubContinent_ID">The Parent Sub Continent ID.</param>
protected void Child_Fetch(int parent_SubContinent_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetD05_CountryColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent_SubContinent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, parent_SubContinent_ID);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="D05_CountryColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(D06_Country.GetD06_Country(dr));
}
RaiseListChangedEvents = rlce;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
using Belikov.Common.ThreadProcessing;
using Belikov.GenuineChannels.BufferPooling;
using Belikov.GenuineChannels.Connection;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.Parameters;
using Belikov.GenuineChannels.Receiving;
using Belikov.GenuineChannels.Security;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
namespace Belikov.GenuineChannels.GenuineHttp
{
/// <summary>
/// Intercepts incoming requests come to the registered web handler and processes them.
/// </summary>
internal class HttpServerConnectionManager : ConnectionManager, ITimerConsumer
{
/// <summary>
/// Constructs an instance of the HttpServerConnectionManager class.
/// </summary>
/// <param name="iTransportContext">The transport context.</param>
public HttpServerConnectionManager(ITransportContext iTransportContext) : base(iTransportContext)
{
this.Local = new HostInformation("_ghttp://" + iTransportContext.HostIdentifier, iTransportContext);
this._releaseConnections_InspectPersistentConnections = new PersistentConnectionStorage.ProcessConnectionEventHandler(this.ReleaseConnections_InspectPersistentConnections);
this._internal_TimerCallback_InspectPersistentConnections = new PersistentConnectionStorage.ProcessConnectionEventHandler(this.Internal_TimerCallback_InspectPersistentConnections);
// calculate host renewing timespan
// this._hostRenewingSpan = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]) + GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]);
this._internal_TimerCallback = new WaitCallback(Internal_TimerCallback);
this._closeInvocationConnectionAfterInactivity = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.CloseInvocationConnectionAfterInactivity]);
TimerProvider.Attach(this);
}
/// <summary>
/// Sends the message to the remote host.
/// </summary>
/// <param name="message">The message to be sent.</param>
protected override void InternalSend(Message message)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
switch (message.SecuritySessionParameters.GenuineConnectionType)
{
case GenuineConnectionType.Persistent:
if (message.ConnectionName == null)
message.ConnectionName = message.SecuritySessionParameters.ConnectionName;
HttpServerConnection httpServerConnection = this._persistent.Get(message.Recipient.Uri, message.ConnectionName) as HttpServerConnection;
if (httpServerConnection == null)
throw GenuineExceptions.Get_Send_DestinationIsUnreachable(message.Recipient.Uri);
bool messageWasSent = false;
lock (httpServerConnection.Listener_Lock)
{
if (httpServerConnection.Listener != null)
{
try
{
// the listener request is available - send the message through it
if (httpServerConnection.Listener.HttpContext.Response.IsClientConnected)
{
messageWasSent = true;
// some data is available, gather the stream and send it
GenuineChunkedStream responseStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.Usual, httpServerConnection.Listener_SequenceNo, message.Recipient);
MessageCoder.FillInLabelledStream(message, httpServerConnection.Listener_MessageContainer,
httpServerConnection.Listener_MessagesBeingSent, responseStream,
httpServerConnection.Listener_IntermediateBuffer,
(int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]);
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
{
for ( int i = 0; i < httpServerConnection.Listener_MessagesBeingSent.Count; i++)
{
Message nextMessage = (Message) httpServerConnection.Listener_MessagesBeingSent[i];
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "HttpServerConnectionManager.InternalSend",
LogMessageType.MessageIsSentAsynchronously, null, nextMessage, httpServerConnection.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.Listener_SecuritySession,
null,
httpServerConnection.DbgConnectionId, httpServerConnection.Listener_SequenceNo, 0, 0, null, null, null, null,
"The message will be sent in the LISTENER stream N: {0}.", httpServerConnection.Listener_SequenceNo);
}
}
httpServerConnection.Listener_SentStream = responseStream;
this.LowLevel_SendStream(httpServerConnection.Listener.HttpContext, true, httpServerConnection, true, ref httpServerConnection.Listener_SentStream, httpServerConnection);
}
}
catch(Exception ex)
{
// a client is expected to re-request this data
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.InternalSend",
LogMessageType.ConnectionEstablishing, ex, null, httpServerConnection.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
"Asynchronous sending failed. Listener seq no: {0}.", httpServerConnection.Listener_SequenceNo);
}
}
finally
{
httpServerConnection.Listener.Complete(false);
httpServerConnection.Listener = null;
}
}
if (! messageWasSent)
{
try
{
// there is no listener requests available, so put the message into the queue
httpServerConnection.Listener_MessageContainer.AddMessage(message, false);
}
catch(Exception ex)
{
// too many messages in the queue
httpServerConnection.Dispose(ex);
this.ITransportContext.KnownHosts.ReleaseHostResources(message.Recipient, ex);
}
}
}
break;
case GenuineConnectionType.Named:
// named connections are not supported
throw new NotSupportedException("The named pattern is not supported by the GHTTP server channel.");
case GenuineConnectionType.Invocation:
// I/connectionId
lock (this._invocation.SyncRoot)
{
if (this._invocation.ContainsKey(message.SecuritySessionParameters.ConnectionName))
{
// the response has been already registered
if (this._invocation[message.SecuritySessionParameters.ConnectionName] != null)
throw GenuineExceptions.Get_Processing_LogicError("The response has been already registered.");
this._invocation[message.SecuritySessionParameters.ConnectionName] = message;
break;
}
}
// there is no invocation connection awaiting for this response
throw GenuineExceptions.Get_Send_DestinationIsUnreachable(message.SecuritySessionParameters.ConnectionName);
}
}
#region -- Handling incoming requests ------------------------------------------------------
private int _closeInvocationConnectionAfterInactivity;
/// <summary>
/// Handles the incoming HTTP request.
/// </summary>
/// <param name="httpServerRequestResultAsObject">The HTTP request.</param>
public void HandleIncomingRequest(object httpServerRequestResultAsObject)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
HttpServerRequestResult httpServerRequestResult = (HttpServerRequestResult) httpServerRequestResultAsObject;
HttpServerConnection httpServerConnection = null;
bool postponeResponse = false;
try
{
// get the stream
HttpRequest httpRequest = httpServerRequestResult.HttpContext.Request;
Stream incomingStream = httpRequest.InputStream;
if (incomingStream.Length <= 0)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest",
LogMessageType.LowLevelTransport_AsyncReceivingCompleted, null, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
-1, 0, 0, 0, null, null, null, null,
"Empty content has been received. It will be ignored.");
}
return ;
}
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 )
{
bool writeContent = binaryLogWriter[LogCategory.LowLevelTransport] > 1;
GenuineChunkedStream content = null;
if (writeContent)
{
content = new GenuineChunkedStream(false);
GenuineUtility.CopyStreamToStream(incomingStream, content);
}
binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpServerConnectionManager.HandleIncomingRequest",
LogMessageType.LowLevelTransport_AsyncReceivingCompleted, null, null, null,
writeContent ? content : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, -1, (int) httpServerRequestResult.HttpContext.Request.ContentLength,
httpServerRequestResult.HttpContext.Request.UserHostAddress,
null, null,
"HTTP request has been received.");
if (writeContent)
incomingStream = content;
}
BinaryReader binaryReader = new BinaryReader(incomingStream);
// read the header
byte protocolVersion;
GenuineConnectionType genuineConnectionType;
Guid hostId;
HttpPacketType httpPacketType;
int sequenceNo;
string connectionName;
int remoteHostUniqueIdentifier;
HttpMessageCoder.ReadRequestHeader(binaryReader, out protocolVersion, out genuineConnectionType, out hostId, out httpPacketType, out sequenceNo, out connectionName, out remoteHostUniqueIdentifier);
HostInformation remote = this.ITransportContext.KnownHosts["_ghttp://" + hostId.ToString("N")];
remote.ProtocolVersion = protocolVersion;
// remote.Renew(this._hostRenewingSpan, false);
remote.PhysicalAddress = httpRequest.UserHostAddress;
// raise an event if we were not recognized
remote.UpdateUri(remote.Uri, remoteHostUniqueIdentifier);
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest",
LogMessageType.ReceivingFinished, null, null, remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1,
0, 0, 0, null, null, null, null,
"HTTP request is being processed. Packet type: {0}. Sequence no: {1}. Content length: {2}. Host address: {3}.",
Enum.Format(typeof(HttpPacketType), httpPacketType, "g"), sequenceNo, httpRequest.ContentLength, httpRequest.UserHostAddress);
}
// prepare the output stream
GenuineChunkedStream outputStream = new GenuineChunkedStream(false);
BinaryWriter binaryWriter = new BinaryWriter(outputStream);
HttpMessageCoder.WriteResponseHeader(binaryWriter, protocolVersion, this.ITransportContext.ConnectionManager.Local.Uri, sequenceNo, httpPacketType, remote.LocalHostUniqueIdentifier);
// analyze the received packet
switch(genuineConnectionType)
{
case GenuineConnectionType.Persistent:
{
// get the server connection
lock (remote.PersistentConnectionEstablishingLock)
{
httpServerConnection = this._persistent.Get(remote.Uri, connectionName) as HttpServerConnection;
if (httpServerConnection != null && httpServerConnection._disposed)
httpServerConnection = null;
// initialize CLSS from the very beginning, if necessary
if (httpPacketType == HttpPacketType.Establishing_ResetConnection)
{
if (httpServerConnection != null)
httpServerConnection.Dispose(GenuineExceptions.Get_Receive_ConnectionClosed("Client sends Establishing_ResetCLSS flag."));
httpServerConnection = null;
}
if (httpServerConnection == null)
{
// create the new connection
httpServerConnection = new HttpServerConnection(this.ITransportContext, hostId, remote, connectionName,
GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]) + GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]));
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteConnectionParameterEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest",
LogMessageType.ConnectionParameters, null, remote, this.ITransportContext.IParameterProvider,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.DbgConnectionId,
"HTTP connection is being established.");
}
this._persistent.Set(remote.Uri, connectionName, httpServerConnection);
// and CLSS
string securitySessionName = this.ITransportContext.IParameterProvider[GenuineParameter.SecuritySessionForPersistentConnections] as string;
if (securitySessionName != null)
{
httpServerConnection.Sender_SecuritySession = this.ITransportContext.IKeyStore.GetKey(securitySessionName).CreateSecuritySession(securitySessionName, null);
httpServerConnection.Listener_SecuritySession = this.ITransportContext.IKeyStore.GetKey(securitySessionName).CreateSecuritySession(securitySessionName, null);
}
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest",
LogMessageType.ConnectionEstablished, null, null, remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.Sender_SecuritySession, securitySessionName,
httpServerConnection.DbgConnectionId, (int) GenuineConnectionType.Persistent, 0, 0, this.GetType().Name, null, null, null,
"The connection is being established.");
}
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 )
{
binaryLogWriter.WriteHostInformationEvent("HttpServerConnectionManager.HandleIncomingRequest",
LogMessageType.HostInformationCreated, null, remote,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.Sender_SecuritySession,
securitySessionName, httpServerConnection.DbgConnectionId,
"HostInformation is ready for actions.");
}
this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.GHttpConnectionAccepted, null, remote, httpRequest.UserHostAddress));
}
}
httpServerConnection.Renew();
httpServerConnection.SignalState(GenuineEventType.GeneralConnectionEstablished, null, null);
switch(httpPacketType)
{
case HttpPacketType.Establishing_ResetConnection:
case HttpPacketType.Establishing:
Stream clsseStream = Stream.Null;
// establish the CLSS
// P/Sender
int length = binaryReader.ReadInt32();
if (httpServerConnection.Sender_SecuritySession != null)
{
using (Stream senderClssReading = new DelimiterStream(incomingStream, length))
{
clsseStream = httpServerConnection.Sender_SecuritySession.EstablishSession(
senderClssReading, true);
}
}
if (clsseStream == null)
clsseStream = Stream.Null;
using (new GenuineChunkedStreamSizeLabel(outputStream))
GenuineUtility.CopyStreamToStream(clsseStream, outputStream);
// P/Listener
length = binaryReader.ReadInt32();
clsseStream = Stream.Null;
if (httpServerConnection.Listener_SecuritySession != null)
clsseStream = httpServerConnection.Listener_SecuritySession.EstablishSession(
new DelimiterStream(incomingStream, length), true);
if (clsseStream == null)
clsseStream = Stream.Null;
using (new GenuineChunkedStreamSizeLabel(outputStream))
GenuineUtility.CopyStreamToStream(clsseStream, outputStream);
// write the answer
Stream finalStream = outputStream;
this.LowLevel_SendStream(httpServerRequestResult.HttpContext, false, null, false, ref finalStream, httpServerConnection);
break;
case HttpPacketType.Listening:
postponeResponse = this.LowLevel_ProcessListenerRequest(httpServerRequestResult, httpServerConnection, sequenceNo);
break;
case HttpPacketType.Usual:
this.LowLevel_ProcessSenderRequest(genuineConnectionType, incomingStream, httpServerRequestResult, httpServerConnection, sequenceNo, remote);
break;
default:
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest",
LogMessageType.Error, GenuineExceptions.Get_Debugging_GeneralWarning("Unexpected type of the packet."), null, remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpServerConnection == null ? -1 : httpServerConnection.DbgConnectionId,
0, 0, 0, null, null, null, null,
"Unexpected type of the packet. Packet type: {0}. Sequence no: {1}. Content length: {2}. Host address: {3}.",
Enum.Format(typeof(HttpPacketType), httpPacketType, "g"), sequenceNo, httpRequest.ContentLength, httpRequest.UserHostAddress);
}
break;
}
}
break;
case GenuineConnectionType.Named:
throw new NotSupportedException("Named connections are not supported.");
case GenuineConnectionType.Invocation:
// renew the host
remote.Renew(this._closeInvocationConnectionAfterInactivity, false);
this.LowLevel_ProcessSenderRequest(genuineConnectionType, incomingStream, httpServerRequestResult, null, sequenceNo, remote);
break;
}
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest",
LogMessageType.ReceivingFinished, ex, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1,
0, 0, 0, null, null, null, null,
"Error occurred while processing incoming HTTP request.");
}
}
finally
{
if (! postponeResponse)
httpServerRequestResult.Complete(true);
}
}
#endregion
#region -- Low-level members ---------------------------------------------------------------
/// <summary>
/// Handles the listener request.
/// </summary>
/// <param name="httpServerRequestResult">The request.</param>
/// <param name="httpServerConnection">The connection.</param>
/// <param name="requestedSequenceNo">The sequence number.</param>
/// <returns>True if the response should be delayed.</returns>
public bool LowLevel_ProcessListenerRequest(HttpServerRequestResult httpServerRequestResult, HttpServerConnection httpServerConnection, int requestedSequenceNo)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
GenuineChunkedStream responseStream = null;
lock (httpServerConnection.Listener_Lock)
{
// if there is an already registered listener request, release it
if (httpServerConnection.Listener != null)
{
try
{
this.LowLevel_ReportServerError(httpServerConnection.Listener.HttpContext);
}
finally
{
httpServerConnection.Listener.Complete(false);
httpServerConnection.Listener = null;
}
}
try
{
Debug.Assert(httpServerConnection.Listener == null);
// if the previous content requested - send it
if (requestedSequenceNo == httpServerConnection.Listener_SequenceNo && httpServerConnection.Listener_SentStream != null)
{
httpServerConnection.Listener_SentStream.Position = 0;
this.LowLevel_SendStream(httpServerRequestResult.HttpContext, true, httpServerConnection, false, ref httpServerConnection.Listener_SentStream, httpServerConnection);
return false;
}
// if too old content version requested - send an error
if (requestedSequenceNo < httpServerConnection.Listener_SequenceNo || requestedSequenceNo > httpServerConnection.Listener_SequenceNo + 1)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
string errorMessage = string.Format("Desynchronization error. Current sequence number: {0}. Requested sequence number: {1}.", httpServerConnection.Listener_SequenceNo, requestedSequenceNo);
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ProcessListenerRequest",
LogMessageType.Error, GenuineExceptions.Get_Debugging_GeneralWarning(errorMessage), null, httpServerConnection.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
errorMessage);
}
// send the error
Stream errorResponseStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.Desynchronization, requestedSequenceNo, httpServerConnection.Remote);
MessageCoder.FillInLabelledStream(null, null, null, (GenuineChunkedStream) errorResponseStream, httpServerConnection.Listener_IntermediateBuffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]);
this.LowLevel_SendStream(httpServerRequestResult.HttpContext, true, httpServerConnection, true, ref errorResponseStream, httpServerConnection);
return false;
}
// the next sequence is requested
if (httpServerConnection.Listener_SentStream != null)
{
// release the content
httpServerConnection.Listener_MessagesBeingSent.Clear();
httpServerConnection.Listener_SentStream.Close();
httpServerConnection.Listener_SentStream = null;
}
Message message = httpServerConnection.Listener_MessageContainer.GetMessage();
if (message == null)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ProcessListenerRequest",
LogMessageType.ReceivingFinished, null, null, httpServerConnection.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
"Listener request is postponed.");
}
// no data is available, postpone the request
httpServerConnection.Listener_Opened = GenuineUtility.TickCount;
httpServerConnection.Listener = httpServerRequestResult;
httpServerConnection.Listener_SequenceNo = requestedSequenceNo;
return true;
}
// some data is available, gather the stream and send it
responseStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.Usual, requestedSequenceNo, httpServerConnection.Remote);
MessageCoder.FillInLabelledStream(message, httpServerConnection.Listener_MessageContainer,
httpServerConnection.Listener_MessagesBeingSent, responseStream,
httpServerConnection.Listener_IntermediateBuffer,
(int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]);
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 )
{
for ( int i = 0; i < httpServerConnection.Listener_MessagesBeingSent.Count; i++)
{
Message nextMessage = (Message) httpServerConnection.Listener_MessagesBeingSent[i];
binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "HttpServerConnectionManager.LowLevel_ProcessListenerRequest",
LogMessageType.MessageIsSentAsynchronously, null, nextMessage, httpServerConnection.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.Listener_SecuritySession,
null,
httpServerConnection.DbgConnectionId, httpServerConnection.Listener_SequenceNo, 0, 0, null, null, null, null,
"The message is sent in the LISTENER stream N: {0}.", httpServerConnection.Listener_SequenceNo);
}
}
httpServerConnection.Listener_SentStream = responseStream;
httpServerConnection.Listener_SequenceNo = requestedSequenceNo;
this.LowLevel_SendStream(httpServerRequestResult.HttpContext, true, httpServerConnection, true, ref httpServerConnection.Listener_SentStream, httpServerConnection);
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ProcessListenerRequest",
LogMessageType.Error, ex, null, httpServerConnection.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
"Error occurred while processing the listener request N: {0}.", httpServerConnection.Listener_SequenceNo);
}
}
}
return false;
}
/// <summary>
/// Processes the sender's request.
/// </summary>
/// <param name="genuineConnectionType">The type of the connection.</param>
/// <param name="input">The incoming data.</param>
/// <param name="httpServerRequestResult">The request.</param>
/// <param name="httpServerConnection">The connection.</param>
/// <param name="sequenceNo">The sequence number.</param>
/// <param name="remote">The information about remote host.</param>
public void LowLevel_ProcessSenderRequest(GenuineConnectionType genuineConnectionType, Stream input, HttpServerRequestResult httpServerRequestResult, HttpServerConnection httpServerConnection, int sequenceNo, HostInformation remote)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
GenuineChunkedStream outputStream = null;
// parse the incoming stream
bool directExecution = genuineConnectionType != GenuineConnectionType.Persistent;
BinaryReader binaryReader = new BinaryReader(input);
using (BufferKeeper bufferKeeper = new BufferKeeper(0))
{
switch(genuineConnectionType)
{
case GenuineConnectionType.Persistent:
Exception gotException = null;
try
{
if (httpServerConnection.Sender_SecuritySession != null)
{
input = httpServerConnection.Sender_SecuritySession.Decrypt(input);
binaryReader = new BinaryReader(input);
}
while (binaryReader.ReadByte() == 0)
using(LabelledStream labelledStream = new LabelledStream(this.ITransportContext, input, bufferKeeper.Buffer))
{
GenuineChunkedStream receivedContent = new GenuineChunkedStream(true);
GenuineUtility.CopyStreamToStream(labelledStream, receivedContent);
this.ITransportContext.IIncomingStreamHandler.HandleMessage(receivedContent, httpServerConnection.Remote, genuineConnectionType, httpServerConnection.ConnectionName, httpServerConnection.DbgConnectionId, false, this._iMessageRegistrator, httpServerConnection.Sender_SecuritySession, httpServerRequestResult);
}
}
catch(Exception ex)
{
gotException = ex;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ProcessSenderRequest",
LogMessageType.Error, ex, null, httpServerConnection.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
"Error occurred while processing the sender request N: {0}.", httpServerConnection.Sender_SequenceNo);
}
}
if (gotException != null)
{
gotException = OperationException.WrapException(gotException);
outputStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.SenderError, sequenceNo, remote);
BinaryFormatter binaryFormatter = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Other));
binaryFormatter.Serialize(outputStream, gotException);
}
else
{
// serialize and send the empty response
outputStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.SenderResponse, sequenceNo, remote);
MessageCoder.FillInLabelledStream(null, null, null, outputStream,
bufferKeeper.Buffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]);
}
break;
case GenuineConnectionType.Invocation:
// register the http context as an invocation waiters
string connectionGuid = Guid.NewGuid().ToString("N");
try
{
if (binaryReader.ReadByte() != 0)
{
// LOG:
if ( binaryLogWriter != null )
{
binaryLogWriter.WriteImplementationWarningEvent("HttpServerConnectionManager.LowLevel_ProcessSenderRequest", LogMessageType.Error,
GenuineExceptions.Get_Debugging_GeneralWarning("The invocation request doesn't contain any messages."),
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
"The invocation request doesn't contain any messages.");
}
}
using(LabelledStream labelledStream = new LabelledStream(this.ITransportContext, input, bufferKeeper.Buffer))
{
// process the response
this._invocation[connectionGuid] = null;
this.ITransportContext.IIncomingStreamHandler.HandleMessage(labelledStream, remote, genuineConnectionType, connectionGuid, -1, true, null, null, httpServerRequestResult);
}
if (binaryReader.ReadByte() != 1)
{
// LOG:
if ( binaryLogWriter != null )
{
binaryLogWriter.WriteImplementationWarningEvent("HttpServerConnectionManager.LowLevel_ProcessSenderRequest", LogMessageType.Error,
GenuineExceptions.Get_Debugging_GeneralWarning("The invocation request must not contain more than one message."),
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
"The invocation request must not contain more than one message.");
}
}
// if there is a response, serialize it
outputStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.Usual, sequenceNo, remote);
Message message = this._invocation[connectionGuid] as Message;
MessageCoder.FillInLabelledStream(message, null, null, outputStream,
bufferKeeper.Buffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]);
}
finally
{
this._invocation.Remove(connectionGuid);
}
break;
}
}
// report back to the client
Stream finalStream = outputStream;
this.LowLevel_SendStream(httpServerRequestResult.HttpContext, false, null, true, ref finalStream, httpServerConnection);
}
/// <summary>
/// Creates and returns the stream with a written response header.
/// </summary>
/// <param name="httpPacketType">The type of the packet.</param>
/// <param name="sequenceNo">The sequence number.</param>
/// <param name="remote">The HostInformation of the remote host.</param>
/// <returns>The stream with a written response header.</returns>
public GenuineChunkedStream LowLevel_CreateStreamWithHeader(HttpPacketType httpPacketType, int sequenceNo, HostInformation remote)
{
GenuineChunkedStream output = new GenuineChunkedStream(false);
BinaryWriter binaryWriter = new BinaryWriter(output);
HttpMessageCoder.WriteResponseHeader(binaryWriter, remote.ProtocolVersion, this.ITransportContext.ConnectionManager.Local.Uri, sequenceNo, httpPacketType, remote.LocalHostUniqueIdentifier);
return output;
}
/// <summary>
/// Sends the response to the remote host.
/// </summary>
/// <param name="httpContext">The http context.</param>
/// <param name="listener">True if it's a listener.</param>
/// <param name="httpServerConnection">The connection containing CLSS.</param>
/// <param name="applyClss">Indicates whether it is necessary to apply Connection Level Security Session.</param>
/// <param name="content">The content being sent to the remote host.</param>
/// <param name="httpServerConnectionForDebugging">The connection that will be mentioned in the debug records.</param>
public void LowLevel_SendStream(HttpContext httpContext, bool listener, HttpServerConnection httpServerConnection, bool applyClss, ref Stream content, HttpServerConnection httpServerConnectionForDebugging)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
try
{
if (applyClss)
{
// detect clss
SecuritySession clss = null;
if (httpServerConnection != null && listener && httpServerConnection.Listener_SecuritySession != null && httpServerConnection.Listener_SecuritySession.IsEstablished)
clss = httpServerConnection.Listener_SecuritySession;
if (httpServerConnection != null && ! listener && httpServerConnection.Sender_SecuritySession != null && httpServerConnection.Sender_SecuritySession.IsEstablished)
clss = httpServerConnection.Sender_SecuritySession;
// apply clss
if (clss != null)
{
GenuineChunkedStream encryptedContent = new GenuineChunkedStream(false);
clss.Encrypt(content, encryptedContent);
content = encryptedContent;
}
}
#if DEBUG
Debug.Assert(content.CanSeek);
Debug.Assert(content.Length >= 0);
#endif
// prepare the response
HttpResponse response = httpContext.Response;
response.ContentType = "application/octet-stream";
response.StatusCode = 200;
response.StatusDescription = "OK";
int contentLength = (int) content.Length;
response.AppendHeader("Content-Length", contentLength.ToString() );
// write the response
Stream responseStream = response.OutputStream;
GenuineUtility.CopyStreamToStream(content, responseStream, contentLength);
this.ITransportContext.ConnectionManager.IncreaseBytesSent(contentLength);
#if DEBUG
// the content must end up here
Debug.Assert(content.ReadByte() == -1);
#endif
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 )
{
bool writeContent = binaryLogWriter[LogCategory.LowLevelTransport] > 1;
GenuineChunkedStream copiedContent = null;
if (writeContent)
{
copiedContent = new GenuineChunkedStream(false);
GenuineUtility.CopyStreamToStream(content, copiedContent);
}
binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpServerConnectionManager.LowLevel_SendStream",
LogMessageType.LowLevelTransport_AsyncSendingInitiating, null, null, httpServerConnectionForDebugging.Remote,
copiedContent,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnectionForDebugging.DbgConnectionId,
(int) content.Length, null, null, null,
"Response is sent back to the client. Buffer: {0}; BufferOutput: {1}; Charset: {2}; ContentEncoding: {3}; ContentType: {4}; IsClientConnected: {5}; StatusCode: {6}; StatusDescription: {7}; SuppressContent: {8}; Content-Length: {9}. Connection: {10}.",
response.Buffer, response.BufferOutput, response.Charset,
response.ContentEncoding, response.ContentType, response.IsClientConnected,
response.StatusCode, response.StatusDescription, response.SuppressContent,
contentLength, listener ? "LISTENER" : "SENDER");
}
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_SendStream",
LogMessageType.MessageIsSentAsynchronously, ex, null, httpServerConnectionForDebugging.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
httpServerConnectionForDebugging.DbgConnectionId, 0, 0, 0, null, null, null, null,
"Error occurred while sending a response.");
}
throw;
}
}
/// <summary>
/// Sends the response to the remote host.
/// </summary>
/// <param name="httpContext">The http context.</param>
public void LowLevel_ReportServerError(HttpContext httpContext)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
try
{
// prepare the response
HttpResponse response = httpContext.Response;
response.ContentType = "application/octet-stream";
response.StatusCode = 409;
response.StatusDescription = "Conflict";
response.AppendHeader ( "Content-Length", "0" );
}
catch (Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ReportServerError",
LogMessageType.Error, ex, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
-1, 0, 0, 0, null, null, null, null,
"Error occurred while sending 409/conflict error.");
}
}
}
#endregion
#region -- Pool management -----------------------------------------------------------------
/// <summary>
/// The message registrator.
/// </summary>
private IMessageRegistrator _iMessageRegistrator = new MessageRegistratorWithLimitedTime();
/// <summary>
/// The set of persistent connections (with CLSS and message queues): Uri -> connection.
/// </summary>
private PersistentConnectionStorage _persistent = new PersistentConnectionStorage();
/// <summary>
/// The set of response to messages received via invocation connections (connection Id => Message or a null reference).
/// </summary>
private Hashtable _invocation = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Sends the packet with empty content and specified type of packet to the remote host
/// through the listening connection.
/// </summary>
/// <param name="httpServerConnection">The connection.</param>
/// <param name="httpPacketType">The type of packet.</param>
private void Pool_SendThroughListener(HttpServerConnection httpServerConnection, HttpPacketType httpPacketType)
{
lock (httpServerConnection.Listener_Lock)
{
if ( httpServerConnection.Listener == null )
return ;
try
{
Stream outputStream = this.LowLevel_CreateStreamWithHeader(httpPacketType, httpServerConnection.Listener_SequenceNo, httpServerConnection.Remote);
this.LowLevel_SendStream(httpServerConnection.Listener.HttpContext, true, httpServerConnection, true, ref outputStream, httpServerConnection);
}
finally
{
httpServerConnection.Listener.Complete(false);
httpServerConnection.Listener = null;
}
}
}
#endregion
#region -- Resource releasing --------------------------------------------------------------
private PersistentConnectionStorage.ProcessConnectionEventHandler _releaseConnections_InspectPersistentConnections;
private class ReleaseConnections_Parameters
{
public ArrayList FailedConnections;
public HostInformation HostInformation;
}
/// <summary>
/// Finds connections to be released.
/// </summary>
/// <param name="httpServerConnectionAsObject">The connection.</param>
/// <param name="releaseConnections_ParametersAsObject">Stuff to make decisions and to save the results.</param>
private void ReleaseConnections_InspectPersistentConnections(object httpServerConnectionAsObject, object releaseConnections_ParametersAsObject)
{
HttpServerConnection httpServerConnection = (HttpServerConnection) httpServerConnectionAsObject;
ReleaseConnections_Parameters releaseConnections_Parameters = (ReleaseConnections_Parameters) releaseConnections_ParametersAsObject;
if (releaseConnections_Parameters.HostInformation != null && httpServerConnection.Remote != releaseConnections_Parameters.HostInformation)
return ;
releaseConnections_Parameters.FailedConnections.Add(httpServerConnection);
}
/// <summary>
/// Closes the specified connections to the remote host and releases acquired resources.
/// </summary>
/// <param name="hostInformation">Host information.</param>
/// <param name="genuineConnectionType">What kind of connections will be affected by this operation.</param>
/// <param name="reason">The reason of resource releasing.</param>
public override void ReleaseConnections(HostInformation hostInformation, GenuineConnectionType genuineConnectionType, Exception reason)
{
BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
ArrayList connectionsToClose = new ArrayList();
using (new WriterAutoLocker(this._disposeLock))
{
if (this._disposed)
return ;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.ReleaseConnections",
LogMessageType.ReleaseConnections, reason, null, hostInformation, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, Enum.Format(typeof(GenuineConnectionType), genuineConnectionType, "g"), null, null, null,
"Connections \"{0}\" will be terminated.", Enum.Format(typeof(GenuineConnectionType), genuineConnectionType, "g"), null);
}
// persistent
if ( (genuineConnectionType & GenuineConnectionType.Persistent) != 0 )
{
// persistent
ReleaseConnections_Parameters releaseConnections_Parameters = new ReleaseConnections_Parameters();
releaseConnections_Parameters.FailedConnections = connectionsToClose;
releaseConnections_Parameters.HostInformation = hostInformation;
this._persistent.InspectAllConnections(this._releaseConnections_InspectPersistentConnections, releaseConnections_Parameters);
}
// close connections
foreach (HttpServerConnection nextHttpServerConnection in connectionsToClose)
{
lock (nextHttpServerConnection.Listener_Lock)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReleaseConnections",
LogMessageType.ConnectionShuttingDown, reason, null, nextHttpServerConnection.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null,
nextHttpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null,
"The connection is being shut down manually.");
}
nextHttpServerConnection.SignalState(GenuineEventType.GeneralConnectionClosed, reason, null);
this._persistent.Remove(nextHttpServerConnection.Remote.Uri, nextHttpServerConnection.ConnectionName);
if (nextHttpServerConnection.Listener != null)
this.Pool_SendThroughListener(nextHttpServerConnection, HttpPacketType.ClosedManually);
}
}
}
}
/// <summary>
/// Returns names of connections opened to the specified destination.
/// Not all Connection Manager support this member.
/// </summary>
/// <param name="uri">The URI or URL of the remote host.</param>
/// <returns>Names of connections opened to the specified destination.</returns>
public override string[] GetConnectionNames(string uri)
{
string ignored;
uri = GenuineUtility.Parse(uri, out ignored);
return this._persistent.GetAll(uri);
}
/// <summary>
/// Releases all resources.
/// </summary>
/// <param name="reason">The reason of disposing.</param>
public override void InternalDispose(Exception reason)
{
this.ReleaseConnections(null, GenuineConnectionType.All, reason);
}
/// <summary>
/// Closes expired connections and sends ping via inactive connections.
/// </summary>
public void TimerCallback()
{
GenuineThreadPool.QueueUserWorkItem(_internal_TimerCallback, null, false);
}
private WaitCallback _internal_TimerCallback;
private PersistentConnectionStorage.ProcessConnectionEventHandler _internal_TimerCallback_InspectPersistentConnections;
private class Internal_TimerCallback_Parameters
{
public ArrayList SendPingTo = new ArrayList();
public ArrayList ExpiredConnections = new ArrayList();
public int CloseListenerConnectionsAfter;
public int Now;
}
/// <summary>
/// Finds connections to be released.
/// </summary>
/// <param name="httpServerConnectionAsObject">The connection.</param>
/// <param name="parametersAsObject">Stuff to make decisions and to save the results.</param>
private void Internal_TimerCallback_InspectPersistentConnections(object httpServerConnectionAsObject, object parametersAsObject)
{
HttpServerConnection httpServerConnection = (HttpServerConnection) httpServerConnectionAsObject;
Internal_TimerCallback_Parameters parameters = (Internal_TimerCallback_Parameters) parametersAsObject;
lock (httpServerConnection.Remote.PersistentConnectionEstablishingLock)
{
if (GenuineUtility.IsTimeoutExpired(httpServerConnection.ShutdownTime, parameters.Now))
parameters.ExpiredConnections.Add(httpServerConnection);
if (httpServerConnection.Listener != null && GenuineUtility.IsTimeoutExpired(httpServerConnection.Listener_Opened + parameters.CloseListenerConnectionsAfter, parameters.Now))
parameters.SendPingTo.Add(httpServerConnection);
}
}
/// <summary>
/// Closes expired connections and sends ping via inactive connections.
/// </summary>
/// <param name="ignored">Ignored.</param>
private void Internal_TimerCallback(object ignored)
{
Internal_TimerCallback_Parameters internal_TimerCallback_Parameters = new Internal_TimerCallback_Parameters();
internal_TimerCallback_Parameters.ExpiredConnections = new ArrayList();
internal_TimerCallback_Parameters.SendPingTo = new ArrayList();
internal_TimerCallback_Parameters.CloseListenerConnectionsAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]);
internal_TimerCallback_Parameters.Now = GenuineUtility.TickCount;
// go through the pool and close all expired connections
this._persistent.InspectAllConnections(this._internal_TimerCallback_InspectPersistentConnections, internal_TimerCallback_Parameters);
// send ping to expired
foreach (HttpServerConnection httpServerConnection in internal_TimerCallback_Parameters.SendPingTo)
this.Pool_SendThroughListener(httpServerConnection, HttpPacketType.ListenerTimedOut);
// close expired connections
foreach (HttpServerConnection httpServerConnection in internal_TimerCallback_Parameters.ExpiredConnections)
{
// just remove it silently
this._persistent.Remove(httpServerConnection.Remote.Uri, httpServerConnection.ConnectionName);
if (httpServerConnection.Listener != null)
this.Pool_SendThroughListener(httpServerConnection, HttpPacketType.ClosedManually);
}
}
#endregion
#region -- Listening -----------------------------------------------------------------------
/// <summary>
/// Starts listening to the specified end point and accepting incoming connections.
/// </summary>
/// <param name="endPoint">The end point.</param>
public override void StartListening(object endPoint)
{
throw new NotSupportedException();
}
/// <summary>
/// Stops listening to the specified end point. Does not close any connections.
/// </summary>
/// <param name="endPoint">The end point</param>
public override void StopListening(object endPoint)
{
throw new NotSupportedException();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace EZOper.TechTester.CSharpWebSI.Areas.ZApi
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace System.Security.Permissions {
using System;
using System.IO;
using System.Security;
using System.Security.Util;
using System.Globalization;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum IsolatedStorageContainment {
None = 0x00,
DomainIsolationByUser = 0x10,
ApplicationIsolationByUser = 0x15,
AssemblyIsolationByUser = 0x20,
DomainIsolationByMachine = 0x30,
AssemblyIsolationByMachine = 0x40,
ApplicationIsolationByMachine = 0x45,
DomainIsolationByRoamingUser = 0x50,
AssemblyIsolationByRoamingUser = 0x60,
ApplicationIsolationByRoamingUser = 0x65,
AdministerIsolatedStorageByUser = 0x70,
//AdministerIsolatedStorageByMachine = 0x80,
UnrestrictedIsolatedStorage = 0xF0
};
[Serializable]
#if !FEATURE_CORECLR
[SecurityPermissionAttribute( SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true )]
#endif
[System.Runtime.InteropServices.ComVisible(true)]
abstract public class IsolatedStoragePermission
: CodeAccessPermission, IUnrestrictedPermission
{
//------------------------------------------------------
//
// PRIVATE STATE DATA
//
//------------------------------------------------------
/// <internalonly/>
internal long m_userQuota;
/// <internalonly/>
internal long m_machineQuota;
/// <internalonly/>
internal long m_expirationDays;
/// <internalonly/>
internal bool m_permanentData;
/// <internalonly/>
internal IsolatedStorageContainment m_allowed;
//------------------------------------------------------
//
// CONSTRUCTORS
//
//------------------------------------------------------
protected IsolatedStoragePermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
m_userQuota = Int64.MaxValue;
m_machineQuota = Int64.MaxValue;
m_expirationDays = Int64.MaxValue ;
m_permanentData = true;
m_allowed = IsolatedStorageContainment.UnrestrictedIsolatedStorage;
}
else if (state == PermissionState.None)
{
m_userQuota = 0;
m_machineQuota = 0;
m_expirationDays = 0;
m_permanentData = false;
m_allowed = IsolatedStorageContainment.None;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
internal IsolatedStoragePermission(IsolatedStorageContainment UsageAllowed,
long ExpirationDays, bool PermanentData)
{
m_userQuota = 0; // typical demand won't include quota
m_machineQuota = 0; // typical demand won't include quota
m_expirationDays = ExpirationDays;
m_permanentData = PermanentData;
m_allowed = UsageAllowed;
}
internal IsolatedStoragePermission(IsolatedStorageContainment UsageAllowed,
long ExpirationDays, bool PermanentData, long UserQuota)
{
m_machineQuota = 0;
m_userQuota = UserQuota;
m_expirationDays = ExpirationDays;
m_permanentData = PermanentData;
m_allowed = UsageAllowed;
}
//------------------------------------------------------
//
// PUBLIC ACCESSOR METHODS
//
//------------------------------------------------------
// properties
public long UserQuota {
set{
m_userQuota = value;
}
get{
return m_userQuota;
}
}
#if false
internal long MachineQuota {
set{
m_machineQuota = value;
}
get{
return m_machineQuota;
}
}
internal long ExpirationDays {
set{
m_expirationDays = value;
}
get{
return m_expirationDays;
}
}
internal bool PermanentData {
set{
m_permanentData = value;
}
get{
return m_permanentData;
}
}
#endif
public IsolatedStorageContainment UsageAllowed {
set{
m_allowed = value;
}
get{
return m_allowed;
}
}
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public bool IsUnrestricted()
{
return m_allowed == IsolatedStorageContainment.UnrestrictedIsolatedStorage;
}
//------------------------------------------------------
//
// INTERNAL METHODS
//
//------------------------------------------------------
internal static long min(long x,long y) {return x>y?y:x;}
internal static long max(long x,long y) {return x<y?y:x;}
#if FEATURE_CAS_POLICY
//------------------------------------------------------
//
// PUBLIC ENCODING METHODS
//
//------------------------------------------------------
private const String _strUserQuota = "UserQuota";
private const String _strMachineQuota = "MachineQuota";
private const String _strExpiry = "Expiry";
private const String _strPermDat = "Permanent";
public override SecurityElement ToXml()
{
return ToXml ( this.GetType().FullName );
}
internal SecurityElement ToXml(String permName)
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, permName );
if (!IsUnrestricted())
{
esd.AddAttribute( "Allowed", Enum.GetName( typeof( IsolatedStorageContainment ), m_allowed ) );
if (m_userQuota>0)
{
esd.AddAttribute(_strUserQuota, (m_userQuota).ToString(CultureInfo.InvariantCulture)) ;
}
if (m_machineQuota>0)
{
esd.AddAttribute(_strMachineQuota, (m_machineQuota).ToString(CultureInfo.InvariantCulture)) ;
}
if (m_expirationDays>0)
{
esd.AddAttribute( _strExpiry, (m_expirationDays).ToString(CultureInfo.InvariantCulture)) ;
}
if (m_permanentData)
{
esd.AddAttribute(_strPermDat, (m_permanentData).ToString()) ;
}
}
else
{
esd.AddAttribute( "Unrestricted", "true" );
}
return esd;
}
public override void FromXml(SecurityElement esd)
{
CodeAccessPermission.ValidateElement( esd, this );
m_allowed = IsolatedStorageContainment.None; // default if no match
if (XMLUtil.IsUnrestricted(esd))
{
m_allowed = IsolatedStorageContainment.UnrestrictedIsolatedStorage;
}
else
{
String allowed = esd.Attribute( "Allowed" );
if (allowed != null)
m_allowed = (IsolatedStorageContainment)Enum.Parse( typeof( IsolatedStorageContainment ), allowed );
}
if (m_allowed == IsolatedStorageContainment.UnrestrictedIsolatedStorage)
{
m_userQuota = Int64.MaxValue;
m_machineQuota = Int64.MaxValue;
m_expirationDays = Int64.MaxValue ;
m_permanentData = true;
}
else
{
String param;
param = esd.Attribute (_strUserQuota) ;
m_userQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
param = esd.Attribute (_strMachineQuota) ;
m_machineQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
param = esd.Attribute (_strExpiry) ;
m_expirationDays = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
param = esd.Attribute (_strPermDat) ;
m_permanentData = param != null ? (Boolean.Parse(param)) : false ;
}
}
#endif // FEATURE_CAS_POLICY
}
}
| |
//
// DeliveryAddress.cs
//
// Author: Kees van Spelde <sicos2002@hotmail.com>
//
// Copyright (c) 2014-2021 Magic-Sessions. (www.magic-sessions.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 NON INFRINGEMENT. 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 VCardReader.Collections;
namespace VCardReader
{
#region Public enum DeliveryAddressTypes
/// <summary>
/// The type of a delivery address.
/// </summary>
[Flags]
public enum DeliveryAddressTypes
{
/// <summary>
/// Default address settings.
/// </summary>
Default = 0,
/// <summary>
/// A domestic delivery address.
/// </summary>
Domestic = 1,
/// <summary>
/// An international delivery address.
/// </summary>
International = 2,
/// <summary>
/// A postal delivery address.
/// </summary>
Postal = 4,
/// <summary>
/// A parcel delivery address.
/// </summary>
Parcel = 8,
/// <summary>
/// A home delivery address.
/// </summary>
Home = 16,
/// <summary>
/// A work delivery address.
/// </summary>
Work = 32
}
#endregion
/// <summary>
/// A postal address.
/// </summary>
/// <seealso cref="DeliveryAddressCollection" />
[Serializable]
public class DeliveryAddress
{
#region Fields
private string _city;
private string _country;
private string _postalCode;
private string _region;
private string _street;
#endregion
#region DeliveryAddress
/// <summary>
/// Creates a new delivery address object.
/// </summary>
public DeliveryAddress()
{
_city = string.Empty;
_country = string.Empty;
_postalCode = string.Empty;
_region = string.Empty;
_street = string.Empty;
}
#endregion
#region AddressType
/// <summary>
/// The type of postal address.
/// </summary>
public DeliveryAddressTypes AddressType { get; set; }
#endregion
#region City
/// <summary>
/// The city or locality of the address.
/// </summary>
public string City
{
get { return _city ?? string.Empty; }
set { _city = value; }
}
#endregion
#region Country
/// <summary>
/// The country name of the address.
/// </summary>
public string Country
{
get { return _country ?? string.Empty; }
set { _country = value; }
}
#endregion
#region IsDomestic
/// <summary>
/// Indicates a domestic delivery address.
/// </summary>
public bool IsDomestic
{
get
{
return AddressType.HasFlag(DeliveryAddressTypes.Domestic);
}
set
{
if (value)
AddressType |= DeliveryAddressTypes.Domestic;
else
AddressType &= ~DeliveryAddressTypes.Domestic;
}
}
#endregion
#region IsHome
/// <summary>
/// Indicates a home address.
/// </summary>
public bool IsHome
{
get
{
return AddressType.HasFlag(DeliveryAddressTypes.Home);
}
set
{
if (value)
AddressType |= DeliveryAddressTypes.Home;
else
AddressType &= ~DeliveryAddressTypes.Home;
}
}
#endregion
#region IsInternational
/// <summary>
/// Indicates an international address.
/// </summary>
public bool IsInternational
{
get
{
return AddressType.HasFlag(DeliveryAddressTypes.International);
}
set
{
if (value)
AddressType |= DeliveryAddressTypes.International;
else
AddressType &= ~DeliveryAddressTypes.International;
}
}
#endregion
#region IsParcel
/// <summary>
/// Indicates a parcel delivery address.
/// </summary>
public bool IsParcel
{
get
{
return AddressType.HasFlag(DeliveryAddressTypes.Parcel);
}
set
{
if (value)
AddressType |= DeliveryAddressTypes.Parcel;
else
AddressType &= ~DeliveryAddressTypes.Parcel;
}
}
#endregion
#region IsPostal
/// <summary>
/// Indicates a postal address.
/// </summary>
public bool IsPostal
{
get
{
return AddressType.HasFlag(DeliveryAddressTypes.Postal);
}
set
{
if (value)
AddressType |= DeliveryAddressTypes.Postal;
else
AddressType &= ~DeliveryAddressTypes.Postal;
}
}
#endregion
#region IsWork
/// <summary>
/// Indicates a work address.
/// </summary>
public bool IsWork
{
get
{
return AddressType.HasFlag(DeliveryAddressTypes.Work);
}
set
{
if (value)
AddressType |= DeliveryAddressTypes.Work;
else
AddressType &= ~DeliveryAddressTypes.Work;
}
}
#endregion
#region PostalCode
/// <summary>
/// The postal code (e.g. ZIP code) of the address.
/// </summary>
public string PostalCode
{
get { return _postalCode ?? string.Empty; }
set { _postalCode = value; }
}
#endregion
#region Region
/// <summary>
/// The region (state or province) of the address.
/// </summary>
public string Region
{
get { return _region ?? string.Empty; }
set { _region = value; }
}
#endregion
#region Street
/// <summary>
/// The street of the delivery address.
/// </summary>
public string Street
{
get { return _street ?? string.Empty; }
set { _street = value; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Storage;
using Xunit;
namespace UnitTests.StorageTests
{
public class HierarchicalKeyStoreTests : IClassFixture<HierarchicalKeyStoreTests.Fixture>
{
public class Fixture
{
public Fixture()
{
BufferPool.InitGlobalBufferPool(new SiloMessagingOptions());
}
}
private const string KeyName1 = "Key1";
private const string KeyName2 = "Key2";
private const string KeyName3 = "Key3";
private const string ValueName1 = "Value1";
private const string ValueName2 = "Value2";
private const string ValueName3 = "Value3";
private static int _keyCounter = 1;
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public void HKS_MakeKey()
{
//string testName = TestContext.TestName;
var keys = new[]
{
Tuple.Create("One", "1"),
Tuple.Create("Two", "2")
}.ToList();
string keyStr = HierarchicalKeyStore.MakeStoreKey(keys);
Assert.Equal("One=1+Two=2", keyStr); // Output from MakeStoreKey
}
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public void HKS_1Key_Read_Write()
{
string testName = Guid.NewGuid().ToString(); //TestContext.TestName;
int key1 = _keyCounter++;
var keys = new[]
{
Tuple.Create(KeyName1, key1.ToString(CultureInfo.InvariantCulture))
}.ToList();
var data = new Dictionary<string, object>();
data.Add(ValueName1, testName);
var store = new HierarchicalKeyStore(1);
string eTag = store.WriteRow(keys, data, null);
var result = store.ReadRow(keys);
Assert.NotNull(result); // Null result
foreach (string valueName in data.Keys)
{
Assert.Equal(data[valueName], result[valueName]);
}
}
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public void HKS_2Key_Read_Write()
{
string testName = Guid.NewGuid().ToString(); //TestContext.TestName;
int key1 = _keyCounter++;
int key2 = _keyCounter++;
var keys = new[]
{
Tuple.Create(KeyName1, key1.ToString(CultureInfo.InvariantCulture)),
Tuple.Create(KeyName2, key2.ToString(CultureInfo.InvariantCulture))
}.ToList();
var data = new Dictionary<string, object>();
data.Add(ValueName1, testName);
var store = new HierarchicalKeyStore(2);
string eTag = store.WriteRow(keys, data, null);
var result = store.ReadRow(keys);
Assert.NotNull(result); // Null result
foreach (string valueName in data.Keys)
{
Assert.Equal(data[valueName], result[valueName]);
}
}
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public void HKS_3Key_Read_Write()
{
string testName = Guid.NewGuid().ToString(); //TestContext.TestName;
int key1 = _keyCounter++;
int key2 = _keyCounter++;
int key3 = _keyCounter++;
var keys = new[]
{
Tuple.Create(KeyName1, key1.ToString(CultureInfo.InvariantCulture)),
Tuple.Create(KeyName2, key2.ToString(CultureInfo.InvariantCulture)),
Tuple.Create(KeyName3, key3.ToString(CultureInfo.InvariantCulture))
}.ToList();
var data = new Dictionary<string, object>();
data[ValueName1] = testName + 1;
data[ValueName2] = testName + 2;
data[ValueName3] = testName + 3;
var store = new HierarchicalKeyStore(3);
string eTag = store.WriteRow(keys, data, null);
var result = store.ReadRow(keys);
Assert.NotNull(result); // Null result
foreach (string valueName in data.Keys)
{
Assert.Equal(data[valueName], result[valueName]);
}
}
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public void HKS_Write2()
{
string testName = Guid.NewGuid().ToString(); //TestContext.TestName;
int key1 = _keyCounter++;
int key2 = _keyCounter++;
List<Tuple<string, string>> keys = MakeKeys(key1, key2);
var data = new Dictionary<string, object>();
data[ValueName1] = testName;
var store = new HierarchicalKeyStore(keys.Count);
// Write #1
string eTag = store.WriteRow(keys, data, null);
data[ValueName1] = "One";
data[ValueName2] = "Two";
data[ValueName3] = "Three";
// Write #2
string newEtag = store.WriteRow(keys, data, eTag);
var result = store.ReadRow(keys);
Assert.NotNull(result); // Null result
foreach (string valueName in data.Keys)
{
Assert.Equal(data[valueName], result[valueName]);
}
}
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public void HKS_DeleteRow()
{
string testName = Guid.NewGuid().ToString(); //TestContext.TestName;
int key1 = _keyCounter++;
int key2 = _keyCounter++;
int key3 = _keyCounter++;
int key4 = _keyCounter++;
List<Tuple<string, string>> keys1 = MakeKeys(key1, key2);
List<Tuple<string, string>> keys2 = MakeKeys(key3, key4);
var data = new Dictionary<string, object>();
data[ValueName1] = testName;
var store = new HierarchicalKeyStore(keys1.Count);
// Write #1
string eTag = store.WriteRow(keys1, data, null);
data[ValueName1] = "One";
data[ValueName2] = "Two";
data[ValueName3] = "Three";
// Write #2
string newEtag = store.WriteRow(keys2, data, eTag);
store.DeleteRow(keys1, newEtag);
var result = store.ReadRow(keys1);
Assert.NotNull(result); // Should not be Null result after DeleteRow
Assert.Equal(0, result.Count); // No data after DeleteRow
result = store.ReadRow(keys2);
Assert.NotNull(result); // Null result
foreach (string valueName in data.Keys)
{
Assert.Equal(data[valueName], result[valueName]);
}
}
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public void HKS_Read_PartialKey()
{
string testName = Guid.NewGuid().ToString(); //TestContext.TestName;
int key1 = _keyCounter++;
int key2 = _keyCounter++;
List<Tuple<string, string>> keys = MakeKeys(key1, key2);
var data = new Dictionary<string, object>();
data[ValueName1] = testName + 1;
data[ValueName2] = testName + 2;
data[ValueName3] = testName + 3;
var store = new HierarchicalKeyStore(keys.Count);
string eTag = store.WriteRow(keys, data, null);
var readKeys = new List<Tuple<string, string>>();
readKeys.Add(keys.First());
var results = store.ReadMultiRow(readKeys);
Assert.NotNull(results); // Null results
Assert.Equal(1, results.Count); // Number of results
var result = results.First();
Assert.NotNull(result); // Null result
foreach (string valueName in data.Keys)
{
Assert.Equal(data[valueName], result[valueName]);
}
}
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public void HKS_KeyNotFound()
{
string testName = Guid.NewGuid().ToString(); //TestContext.TestName;
int key1 = _keyCounter++;
int key2 = _keyCounter++;
List<Tuple<string, string>> keys = MakeKeys(key1, key2);
var store = new HierarchicalKeyStore(keys.Count);
var result = store.ReadRow(keys);
Assert.NotNull(result); // Null result
Assert.Equal(0, result.Count); // No data
}
// Utility methods
private List<Tuple<string, string>> MakeKeys(int key1, int key2)
{
var keys = new[]
{
Tuple.Create(KeyName1, key1.ToString(CultureInfo.InvariantCulture)),
Tuple.Create(KeyName2, key2.ToString(CultureInfo.InvariantCulture))
}.ToList();
return keys;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Linq;
namespace HTLib2
{
public static partial class LinAlg
{
static bool Eye_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr Eye(int size, double diagval=1)
{
if(Eye_SelfTest)
{
Eye_SelfTest = false;
MatrixByArr tT0 = new double[3, 3] { { 2, 0, 0 }, { 0, 2, 0 }, { 0, 0, 2 }, };
MatrixByArr tT1 = Eye(3, 2);
HDebug.AssertTolerance(double.Epsilon, tT0 - tT1);
}
MatrixByArr mat = new MatrixByArr(size,size);
for(int i=0; i<size; i++)
mat[i, i] = diagval;
return mat;
}
static bool Tr_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix Tr(this Matrix M)
{
if(Tr_SelfTest)
{
Tr_SelfTest = false;
Matrix tM0 = new double[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
Matrix tT0 = new double[3, 2] { { 1, 4 }, { 2, 5 }, { 3, 6 } };
Matrix tT1 = Tr(tM0);
HDebug.AssertToleranceMatrix(double.Epsilon, tT0 - tT1);
}
Matrix tr = Matrix.Zeros(M.RowSize, M.ColSize);
for(int c=0; c<tr.ColSize; c++)
for(int r=0; r<tr.RowSize; r++)
tr[c, r] = M[r, c];
return tr;
}
static bool Diagd_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr Diag(this Vector d)
{
if(Diagd_SelfTest)
{
Diagd_SelfTest = false;
MatrixByArr tD1 = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector td1 = new double[3] { 1, 2, 3 };
MatrixByArr tD = Diag(td1);
HDebug.AssertTolerance(double.Epsilon, tD - tD1);
}
int size = d.Size;
MatrixByArr D = new MatrixByArr(size, size);
for(int i=0; i < size; i++)
D[i, i] = d[i];
return D;
}
static bool DiagD_SelfTest = HDebug.IsDebuggerAttached;
public static Vector Diag(this Matrix D)
{
if(DiagD_SelfTest)
{
DiagD_SelfTest = false;
MatrixByArr tD1 = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector td1 = new double[3] { 1, 2, 3 };
Vector td = Diag(tD1);
HDebug.AssertTolerance(double.Epsilon, td - td1);
}
HDebug.Assert(D.ColSize == D.RowSize);
int size = D.ColSize;
Vector d = new double[size];
for(int i=0; i<size; i++)
d[i] = D[i,i];
return d;
}
static bool DV_SelfTest1 = HDebug.IsDebuggerAttached;
public static Vector DV(Matrix D, Vector V, bool assertDiag = true)
{
if(DV_SelfTest1)
{
DV_SelfTest1 = false;
MatrixByArr tD = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector tV = new double[3] { 1, 2, 3 };
Vector tDV = new double[3] { 1, 4, 9 };
// [1 0 0] [1] [1]
// [0 2 0] * [2] = [4]
// [0 0 3] [3] [9]
HDebug.AssertTolerance(double.Epsilon, DV(tD, tV) - tDV);
}
// D is the diagonal matrix
HDebug.Assert(D.ColSize == D.RowSize);
if(assertDiag) // check diagonal matrix
HDebug.AssertToleranceMatrix(double.Epsilon, D - Diag(Diag(D)));
HDebug.Assert(D.ColSize == V.Size);
Vector diagD = Diag(D);
Vector diagDV = DV(diagD, V);
return diagDV;
}
static bool DV_SelfTest2 = HDebug.IsDebuggerAttached;
public static Vector DV(Vector D, Vector V, bool assertDiag = true)
{
if(DV_SelfTest2)
{
DV_SelfTest2 = false;
Vector tD = new double[3] { 1, 2, 3 };
Vector tV = new double[3] { 1, 2, 3 };
Vector tDV = new double[3] { 1, 4, 9 };
// [1 0 0] [1] [1]
// [0 2 0] * [2] = [4]
// [0 0 3] [3] [9]
HDebug.AssertTolerance(double.Epsilon, DV(tD, tV) - tDV);
}
// D is the diagonal matrix
HDebug.Assert(D.Size == V.Size);
int size = V.Size;
Vector dv = new double[size];
for(int i=0; i < size; i++)
dv[i] = D[i] * V[i];
return dv;
}
static bool MD_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr MD(MatrixByArr M, Vector D)
{ // M * Diag(D)
if(MD_SelfTest)
{
MD_SelfTest = false;
MatrixByArr tM = new double[3, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 } };
Vector tD = new double[3] { 1, 2, 3 };
MatrixByArr tMD0 = new double[3, 3] { { 1, 4, 9 }
, { 4, 10, 18 }
, { 7, 16, 27 } };
MatrixByArr tMD1 = MD(tM, tD);
MatrixByArr dtMD = tMD0 - tMD1;
double maxAbsDtMD = dtMD.ToArray().HAbs().HMax();
Debug.Assert(maxAbsDtMD == 0);
}
HDebug.Assert(M.RowSize == D.Size);
MatrixByArr lMD = new double[M.ColSize, M.RowSize];
for(int c=0; c<lMD.ColSize; c++)
for(int r=0; r<lMD.RowSize; r++)
lMD[c, r] = M[c, r] * D[r];
return lMD;
}
static bool MV_SelfTest = HDebug.IsDebuggerAttached;
static bool MV_SelfTest_lmat_rvec = HDebug.IsDebuggerAttached;
public static Vector MV<MATRIX>(MATRIX lmat, Vector rvec, string options="")
where MATRIX : IMatrix<double>
{
Vector result = new Vector(lmat.ColSize);
MV(lmat, rvec, result, options);
if(MV_SelfTest_lmat_rvec)
{
MV_SelfTest_lmat_rvec = false;
HDebug.Assert(lmat.RowSize == rvec.Size);
Vector lresult = new Vector(lmat.ColSize);
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
lresult[c] += lmat[c, r] * rvec[r];
HDebug.AssertTolerance(double.Epsilon, lresult-result);
}
return result;
}
public static void MV<MATRIX>(MATRIX lmat, Vector rvec, Vector result, string options="")
where MATRIX : IMatrix<double>
{
if(MV_SelfTest)
{
MV_SelfTest = false;
MatrixByArr tM = new double[4, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 }
, { 10, 11, 12 } };
Vector tV = new double[3] { 1, 2, 3 };
Vector tMV0 = new double[4] { 14, 32, 50, 68 };
Vector tMV1 = MV(tM, tV);
double err = (tMV0 - tMV1).ToArray().HAbs().Max();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.RowSize == rvec.Size);
HDebug.Assert(lmat.ColSize == result.Size);
if(options.Split(';').Contains("parallel") == false)
{
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
result[c] += lmat[c, r] * rvec[r];
}
else
{
System.Threading.Tasks.Parallel.For(0, lmat.ColSize, delegate(int c)
{
for(int r=0; r<lmat.RowSize; r++)
result[c] += lmat[c, r] * rvec[r];
});
}
}
//static bool MtM_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix MtM(Matrix lmat, Matrix rmat)
{
bool MtM_SelfTest = false;//HDebug.IsDebuggerAttached;
if(MtM_SelfTest)
{
MtM_SelfTest = false;
/// >> A=[ 1,5 ; 2,6 ; 3,7 ; 4,8 ];
/// >> B=[ 1,2,3 ; 3,4,5 ; 5,6,7 ; 7,8,9 ];
/// >> A'*B
/// ans =
/// 50 60 70
/// 114 140 166
Matrix _A = new double[4, 2] {{ 1,5 },{ 2,6 },{ 3,7 },{ 4,8 }};
Matrix _B = new double[4, 3] {{ 1,2,3 },{ 3,4,5 },{ 5,6,7 },{ 7,8,9 }};
Matrix _AtB = MtM(_A, _B);
Matrix _AtB_sol = new double[2,3]
{ { 50, 60, 70 }
, { 114, 140, 166 } };
double err = (_AtB - _AtB_sol).HAbsMax();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.ColSize == rmat.ColSize);
int size1 = lmat.RowSize;
int size2 = rmat.ColSize;
int size3 = rmat.RowSize;
Matrix result = Matrix.Zeros(size1, size3);
for(int c=0; c<size1; c++)
for(int r=0; r<size3; r++)
{
double sum = 0;
for(int i=0; i<size2; i++)
// tr(lmat[c,i]) * rmat[i,r] => lmat[i,c] * rmat[i,r]
sum += lmat[i,c] * rmat[i,r];
result[c, r] = sum;
}
return result;
}
//static bool MMt_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix MMt(Matrix lmat, Matrix rmat)
{
bool MMt_SelfTest = false;//HDebug.IsDebuggerAttached;
if(MMt_SelfTest)
{
MMt_SelfTest = false;
/// >> A=[ 1,2,3,4 ; 5,6,7,8 ];
/// >> B=[ 1,3,5,7 ; 2,4,6,8 ; 3,5,7,9 ];
/// >> A*B'
/// ans =
/// 50 60 70
/// 114 140 166
Matrix _A = new double[2, 4]
{ { 1, 2, 3, 4 }
, { 5, 6, 7, 8 } };
Matrix _B = new double[3, 4]
{ { 1, 3, 5, 7 }
, { 2, 4, 6, 8 }
, { 3, 5, 7, 9 } };
Matrix _AtB = MMt(_A, _B);
Matrix _AtB_sol = new double[2,3]
{ { 50, 60, 70 }
, { 114, 140, 166 } };
double err = (_AtB - _AtB_sol).HAbsMax();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.RowSize == rmat.RowSize);
int size1 = lmat.ColSize;
int size2 = lmat.RowSize;
int size3 = rmat.ColSize;
Matrix result = Matrix.Zeros(size1, size3);
for(int c=0; c<size1; c++)
for(int r=0; r<size3; r++)
{
double sum = 0;
for(int i=0; i<size2; i++)
// lmat[c,i] * tr(rmat[i,r]) => lmat[c,i] * rmat[r,i]
sum += lmat[c,i] * rmat[r,i];
result[c, r] = sum;
}
return result;
}
static bool MtV_SelfTest = HDebug.IsDebuggerAttached;
public static Vector MtV(Matrix lmat, Vector rvec)
{
if(MtV_SelfTest)
{
MtV_SelfTest = false;
/// >> A = [ 1,2,3 ; 4,5,6 ; 7,8,9 ; 10,11,12 ];
/// >> B = [ 1; 2; 3; 4 ];
/// >> A'*B
/// ans =
/// 70
/// 80
/// 90
MatrixByArr tM = new double[4, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 }
, { 10, 11, 12 } };
Vector tV = new double[4] { 1, 2, 3, 4 };
Vector tMtV0 = new double[3] { 70, 80, 90 };
Vector tMtV1 = MtV(tM, tV);
double err = (tMtV0 - tMtV1).ToArray().HAbs().Max();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.ColSize == rvec.Size);
Vector result = new Vector(lmat.RowSize);
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
result[r] += lmat[c, r] * rvec[c];
return result;
}
public static bool V1tD2V3_SelfTest = HDebug.IsDebuggerAttached;
public static double V1tD2V3(Vector V1, Matrix D2, Vector V3, bool assertDiag=true)
{
if(V1tD2V3_SelfTest)
{
V1tD2V3_SelfTest = false;
Vector tV1 = new double[3] { 1, 2, 3 };
MatrixByArr tD2 = new double[3, 3] { { 2, 0, 0 }, { 0, 3, 0 }, { 0, 0, 4 } };
Vector tV3 = new double[3] { 3, 4, 5 };
// [2 ] [3] [ 6]
// [1 2 3] * [ 3 ] * [4] = [1 2 3] * [12] = 6+24+60 = 90
// [ 4] [5] [20]
double tV1tD2V3 = 90;
HDebug.AssertTolerance(double.Epsilon, tV1tD2V3 - V1tD2V3(tV1, tD2, tV3));
}
if(assertDiag) // check diagonal matrix
HDebug.AssertToleranceMatrix(double.Epsilon, D2 - Diag(Diag(D2)));
HDebug.Assert(V1.Size == D2.ColSize);
HDebug.Assert(D2.RowSize == V3.Size );
Vector lD2V3 = DV(D2, V3, assertDiag);
double lV1tD2V3 = VtV(V1, lD2V3);
return lV1tD2V3;
}
public static MatrixByArr VVt(Vector lvec, Vector rvec)
{
MatrixByArr outmat = new MatrixByArr(lvec.Size, rvec.Size);
VVt(lvec, rvec, outmat);
return outmat;
}
public static void VVt(Vector lvec, Vector rvec, MatrixByArr outmat)
{
HDebug.Exception(outmat.ColSize == lvec.Size);
HDebug.Exception(outmat.RowSize == rvec.Size);
MatrixByArr mat = new MatrixByArr(lvec.Size, rvec.Size);
for(int c = 0; c < lvec.Size; c++)
for(int r = 0; r < rvec.Size; r++)
outmat[c, r] = lvec[c] * rvec[r];
}
public static bool DMD_selftest = HDebug.IsDebuggerAttached;
public static Matrix DMD(Vector diagmat1, Matrix mat,Vector diagmat2)
{
if(DMD_selftest)
#region selftest
{
HDebug.ToDo("check");
DMD_selftest = false;
Vector td1 = new double[] { 1, 2, 3 };
Vector td2 = new double[] { 4, 5, 6 };
Matrix tm = new double[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Matrix dmd0 = LinAlg.Diag(td1) * tm * LinAlg.Diag(td2);
Matrix dmd1 = LinAlg.DMD(td1, tm, td2);
double err = (dmd0 - dmd1).HAbsMax();
HDebug.Assert(err == 0);
}
#endregion
Matrix DMD = mat.Clone();
for(int c=0; c<mat.ColSize; c++)
for(int r=0; r<mat.RowSize; r++)
{
double v0 = mat[c, r];
double v1 = diagmat1[c] * v0 * diagmat2[r];
if(v0 == v1) continue;
DMD[c, r] = v1;
}
return DMD;
}
public static double VtMV(Vector lvec, Matrix mat, Vector rvec, string options="")
{
Vector MV = LinAlg.MV(mat, rvec, options);
double VMV = LinAlg.VtV(lvec, MV);
//Debug.AssertToleranceIf(lvec.Size<100, 0.00000001, Vector.VtV(lvec, Vector.MV(mat, rvec)) - VMV);
return VMV;
}
public static MatrixByArr M_Mt(MatrixByArr lmat, MatrixByArr rmat)
{
// M + Mt
HDebug.Assert(lmat.ColSize == rmat.RowSize);
HDebug.Assert(lmat.RowSize == rmat.ColSize);
MatrixByArr MMt = lmat.CloneT();
for(int c = 0; c < MMt.ColSize; c++)
for(int r = 0; r < MMt.RowSize; r++)
MMt[c, r] += rmat[r, c];
return MMt;
}
public static double VtV(Vector l, Vector r)
{
HDebug.Assert(l.Size == r.Size);
int size = l.Size;
double result = 0;
for(int i=0; i < size; i++)
result += l[i] * r[i];
return result;
}
public static double[] ListVtV(Vector l, IList<Vector> rs)
{
double[] listvtv = new double[rs.Count];
for(int i=0; i<rs.Count; i++)
listvtv[i] = VtV(l, rs[i]);
return listvtv;
}
public static double VtV(Vector l, Vector r, IList<int> idxsele)
{
HDebug.Assert(l.Size == r.Size);
Vector ls = l.ToArray().HSelectByIndex(idxsele);
Vector rs = r.ToArray().HSelectByIndex(idxsele);
return VtV(ls, rs);
}
public static Vector VtMM(Vector v1, Matrix m2, Matrix m3)
{
Vector v12 = VtM(v1, m2);
return VtM(v12, m3);
}
public static class AddToM
{
public static void VVt(Matrix M, Vector V)
{
HDebug.Assert(M.ColSize == V.Size);
HDebug.Assert(M.RowSize == V.Size);
int size = V.Size;
for(int c=0; c<size; c++)
for(int r=0; r<size; r++)
M[c, r] += V[c] * V[r];
}
}
public static Vector VtM<MATRIX>(Vector lvec, MATRIX rmat)
where MATRIX : IMatrix<double>
{
HDebug.Assert(lvec.Size == rmat.ColSize);
Vector result = new Vector(rmat.RowSize);
for(int c=0; c<rmat.ColSize; c++)
for(int r=0; r<rmat.RowSize; r++)
result[r] += lvec[c] * rmat[c, r];
return result;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: The core libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/17/2008 11:20:29 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using DotSpatial.NTSExtension;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
public class ShadedRelief : Descriptor, IShadedRelief
{
#region Events
/// <summary>
/// Occurs when the shading for this object has been altered.
/// </summary>
public event EventHandler ShadingChanged;
#endregion
#region Private Variables
float _ambientIntensity;
float _elevationFactor;
float _extrusion;
bool _hasChanged; // set to true when a property changes, and false again when the raster symbolizer calculates the HillShadeMap
bool _isUsed;
private double _lightDirection;
float _lightIntensity;
private double _zenithAngle;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the ShadedRelief preset for elevation in feet and coordinates in decimal degrees
/// </summary>
public ShadedRelief()
: this(ElevationScenario.ElevationFeet_ProjectionDegrees)
{
}
/// <summary>
/// Creates a new instance of ShadedRelief based on some more common
/// elevation to goegraphic coordinate sysetem scenarios
/// </summary>
public ShadedRelief(ElevationScenario scenario)
{
// These scenarios just give a quick approximate calc for the elevation factor
switch (scenario)
{
case ElevationScenario.ElevationCentiMeters_ProjectionDegrees:
_elevationFactor = 1F / (160934.4F * 69F);
break;
case ElevationScenario.ElevationCentiMeters_ProjectionFeet:
_elevationFactor = 0.0328084F;
break;
case ElevationScenario.ElevationCentiMeters_ProjectionMeters:
_elevationFactor = 1F / 100F;
break;
case ElevationScenario.ElevationFeet_ProjectionDegrees:
_elevationFactor = 1F / (5280F * 69F);
break;
case ElevationScenario.ElevationFeet_ProjectionFeet:
_elevationFactor = 1F;
break;
case ElevationScenario.ElevationFeet_ProjectionMeters:
_elevationFactor = 1F / 3.28F;
break;
case ElevationScenario.ElevationMeters_ProjectionDegrees:
_elevationFactor = 1F / (1609F * 69F);
break;
case ElevationScenario.ElevationMeters_ProjectionFeet:
_elevationFactor = 1F * 3.28F;
break;
case ElevationScenario.ElevationMeters_ProjectionMeters:
_elevationFactor = 1F;
break;
}
// Light direction is SouthEast at about 45 degrees up
_zenithAngle = 45;
_lightDirection = 45;
_lightIntensity = .7F;
_ambientIntensity = .8F;
_extrusion = 5;
//_elevationFactor = 0.0000027F;
_isUsed = false;
_hasChanged = false;
}
#endregion
#region Methods
/// <summary>
/// Returns a normalized vector in 3 dimensions representing the angle
/// of the light source.
/// </summary>
/// <returns></returns>
public FloatVector3 GetLightDirection()
{
double angle = LightDirection * Math.PI / 180;
double zAngle = ZenithAngle * Math.PI / 180;
double x = Math.Sin(angle) * Math.Cos(zAngle);
double y = Math.Cos(angle) * Math.Cos(zAngle);
double z = Math.Sin(zAngle);
return new FloatVector3((float)x, (float)y, (float)z);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a float specifying how strong the ambient directional light is. This should probably be about 1.
/// </summary>
[Category("Shaded Relief"), Description("Gets or sets a float specifying how strong the ambient directional light is. This should probably be about 1."),
Serialize("AmbientIntensity")]
public float AmbientIntensity
{
get { return _ambientIntensity; }
set
{
_ambientIntensity = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// This is kept separate from extrusion to reduce confusion. This is a conversion factor that will
/// convert the units of elevation into the same units that the latitude and longitude are stored in.
/// To convert feet to decimal degrees is around a factor of .00000274
/// </summary>
[Category("Shaded Relief"), Description("This is kept separate from extrusion to reduce confusion. This is a conversion factor that will convert the units of elevation into the same units that the latitude and longitude are stored in. To convert feet to decimal degrees is around a factor of .00000274"),
Serialize("ElevationFactor")]
public float ElevationFactor
{
get { return _elevationFactor; }
set
{
_elevationFactor = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// A float value expression that modifies the "height" of the apparent shaded relief. A value
/// of 1 should show the mountains at their true elevations, presuming the ElevationFactor is
/// correct. A value of 0 would be totally flat, while 2 would be twice the value.
/// </summary>
[Category("Shaded Relief"), Serialize("Extrusion"),
Description("A float value expression that modifies the height of the apparent shaded relief. A value of 1 should show the mountains at their true elevations, presuming the ElevationFactor is correct. A value of 0 would be totally flat, while 2 would be twice the value.")]
public float Extrusion
{
get { return _extrusion; }
set
{
_extrusion = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a boolean value indicating whether the ShadedRelief should be used or not.
/// </summary>
[Category("Shaded Relief"), Serialize("IsUsed"),
Description("Gets or sets a boolean value indicating whether the ShadedRelief should be used or not.")]
public bool IsUsed
{
get { return _isUsed; }
set
{
_isUsed = value;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets the zenith angle for the light direction in degrees from 0 (at the horizon) to 90 (straight up).
/// </summary>
[Category("Shaded Relief"), Serialize("ZenithAngle"),
//Editor(typeof(ZenithEditor), typeof(UITypeEditor)),
Description("Gets or sets the zenith angle for the light direction in degrees from 0 (at the horizon) to 90 (straight up).")]
public double ZenithAngle
{
get { return _zenithAngle; }
set
{
_zenithAngle = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a double that represents the light direction in degrees clockwise from North
/// </summary>
[Category("Shaded Relief"),
//Editor(typeof(AzimuthAngleEditor), typeof(UITypeEditor)), Serialize("LightDirection"),
Description("The azimuth angle in degrees for the light direction. The angle is measured clockwise from North.")]
public double LightDirection
{
get { return _lightDirection; }
set
{
_lightDirection = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// This specifies a float that should probably be around 1, which controls the light intensity.
/// </summary>
[Category("Shaded Relief"), Serialize("LightIntensity"),
Description("This specifies a float that should probably be around 1, which controls the light intensity.")]
public float LightIntensity
{
get { return _lightIntensity; }
set
{
_lightIntensity = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets whether or not the values have been changed on this ShadedRelief more recently than
/// a HillShade map has been calculated from it.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool HasChanged
{
get { return _hasChanged; }
set
{
_hasChanged = value;
OnShadingChanged();
}
}
#endregion
/// <summary>
/// Fires the ShadingChanged event
/// </summary>
protected virtual void OnShadingChanged()
{
if (ShadingChanged != null) ShadingChanged(this, EventArgs.Empty);
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Editors;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.PublishedCache;
using Umbraco.Cms.Core.Routing;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.PropertyEditors
{
public class MultiUrlPickerValueEditor : DataValueEditor, IDataValueReference
{
private readonly IEntityService _entityService;
private readonly ILogger<MultiUrlPickerValueEditor> _logger;
private readonly IPublishedUrlProvider _publishedUrlProvider;
private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor;
public MultiUrlPickerValueEditor(
IEntityService entityService,
IPublishedSnapshotAccessor publishedSnapshotAccessor,
ILogger<MultiUrlPickerValueEditor> logger,
ILocalizedTextService localizedTextService,
IShortStringHelper shortStringHelper,
DataEditorAttribute attribute,
IPublishedUrlProvider publishedUrlProvider,
IJsonSerializer jsonSerializer,
IIOHelper ioHelper)
: base(localizedTextService, shortStringHelper, jsonSerializer, ioHelper, attribute)
{
_entityService = entityService ?? throw new ArgumentNullException(nameof(entityService));
_publishedSnapshotAccessor = publishedSnapshotAccessor ?? throw new ArgumentNullException(nameof(publishedSnapshotAccessor));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_publishedUrlProvider = publishedUrlProvider;
}
public override object ToEditor(IProperty property, string culture = null, string segment = null)
{
var value = property.GetValue(culture, segment)?.ToString();
if (string.IsNullOrEmpty(value))
{
return Enumerable.Empty<object>();
}
try
{
var links = JsonConvert.DeserializeObject<List<LinkDto>>(value);
var documentLinks = links.FindAll(link => link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Document);
var mediaLinks = links.FindAll(link => link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Media);
var entities = new List<IEntitySlim>();
if (documentLinks.Count > 0)
{
entities.AddRange(
_entityService.GetAll(UmbracoObjectTypes.Document, documentLinks.Select(link => link.Udi.Guid).ToArray())
);
}
if (mediaLinks.Count > 0)
{
entities.AddRange(
_entityService.GetAll(UmbracoObjectTypes.Media, mediaLinks.Select(link => link.Udi.Guid).ToArray())
);
}
var result = new List<LinkDisplay>();
foreach (var dto in links)
{
GuidUdi udi = null;
var icon = "icon-link";
var published = true;
var trashed = false;
var url = dto.Url;
if (dto.Udi != null)
{
IUmbracoEntity entity = entities.Find(e => e.Key == dto.Udi.Guid);
if (entity == null)
{
continue;
}
var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
if (entity is IDocumentEntitySlim documentEntity)
{
icon = documentEntity.ContentTypeIcon;
published = culture == null ? documentEntity.Published : documentEntity.PublishedCultures.Contains(culture);
udi = new GuidUdi(Constants.UdiEntityType.Document, documentEntity.Key);
url = publishedSnapshot.Content.GetById(entity.Key)?.Url(_publishedUrlProvider) ?? "#";
trashed = documentEntity.Trashed;
}
else if(entity is IContentEntitySlim contentEntity)
{
icon = contentEntity.ContentTypeIcon;
published = !contentEntity.Trashed;
udi = new GuidUdi(Constants.UdiEntityType.Media, contentEntity.Key);
url = publishedSnapshot.Media.GetById(entity.Key)?.Url(_publishedUrlProvider) ?? "#";
trashed = contentEntity.Trashed;
}
else
{
// Not supported
continue;
}
}
result.Add(new LinkDisplay
{
Icon = icon,
Name = dto.Name,
Target = dto.Target,
Trashed = trashed,
Published = published,
QueryString = dto.QueryString,
Udi = udi,
Url = url ?? ""
});
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting links");
}
return base.ToEditor(property, culture, segment);
}
private static readonly JsonSerializerSettings LinkDisplayJsonSerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore
};
public override object FromEditor(ContentPropertyData editorValue, object currentValue)
{
var value = editorValue.Value?.ToString();
if (string.IsNullOrEmpty(value))
{
return null;
}
try
{
var links = JsonConvert.DeserializeObject<List<LinkDisplay>>(value);
if (links.Count == 0)
{
return null;
}
return JsonConvert.SerializeObject(
from link in links
select new LinkDto
{
Name = link.Name,
QueryString = link.QueryString,
Target = link.Target,
Udi = link.Udi,
Url = link.Udi == null ? link.Url : null, // only save the URL for external links
},
LinkDisplayJsonSerializerSettings);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error saving links");
}
return base.FromEditor(editorValue, currentValue);
}
[DataContract]
public class LinkDto
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "target")]
public string Target { get; set; }
[DataMember(Name = "udi")]
public GuidUdi Udi { get; set; }
[DataMember(Name = "url")]
public string Url { get; set; }
[DataMember(Name = "queryString")]
public string QueryString { get; set; }
}
public IEnumerable<UmbracoEntityReference> GetReferences(object value)
{
var asString = value == null ? string.Empty : value is string str ? str : value.ToString();
if (string.IsNullOrEmpty(asString)) yield break;
var links = JsonConvert.DeserializeObject<List<LinkDto>>(asString);
foreach (var link in links)
{
if (link.Udi != null) // Links can be absolute links without a Udi
{
yield return new UmbracoEntityReference(link.Udi);
}
}
}
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator 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.
//
#endregion
using System;
using System.Linq;
using FluentMigrator.Runner.Generators;
using FluentMigrator.Runner.Generators.DB2;
using FluentMigrator.Runner.Generators.DB2.iSeries;
using Microsoft.Extensions.Options;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.Db2
{
[TestFixture]
public class Db2ColumnTests : BaseColumnTests
{
public Db2Generator Generator
{
get; set;
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD COLUMN TestColumn1 MyDomainType DEFAULT");
}
[Test]
public override void CanCreateNullableColumnWithCustomDomainTypeAndDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpressionWithNullableCustomType();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD COLUMN TestColumn1 MyDomainType DEFAULT");
}
[Test]
public override void CanAlterColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.Column.IsNullable = null;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ALTER COLUMN TestColumn1 SET DATA TYPE VARGRAPHIC(20) CCSID 1200 NOT NULL");
}
[Test]
public override void CanAlterColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnExpression();
expression.Column.IsNullable = null;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ALTER COLUMN TestColumn1 SET DATA TYPE VARGRAPHIC(20) CCSID 1200 NOT NULL");
}
[Test]
public override void CanCreateAutoIncrementColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe(string.Empty);
}
[Test]
public override void CanCreateAutoIncrementColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetAlterColumnAddAutoIncrementExpression();
var result = Generator.Generate(expression);
result.ShouldBe(string.Empty);
}
[Test]
public override void CanCreateColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD COLUMN TestColumn1 VARGRAPHIC(5) CCSID 1200 NOT NULL DEFAULT");
}
[Test]
public override void CanCreateColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD COLUMN TestColumn1 VARGRAPHIC(5) CCSID 1200 NOT NULL DEFAULT");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndCustomSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression("TestSchema");
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE TestSchema.TestTable1 ADD COLUMN TestColumn1 TIMESTAMP DEFAULT" + Environment.NewLine +
@"UPDATE TestSchema.TestTable1 SET TestColumn1 = CURRENT_TIMESTAMP");
}
[Test]
public override void CanCreateColumnWithSystemMethodAndDefaultSchema()
{
var expressions = GeneratorTestHelper.GetCreateColumnWithSystemMethodExpression();
var result = string.Join(Environment.NewLine, expressions.Select(x => (string)Generator.Generate((dynamic)x)));
result.ShouldBe(
@"ALTER TABLE TestTable1 ADD COLUMN TestColumn1 TIMESTAMP DEFAULT" + Environment.NewLine +
@"UPDATE TestTable1 SET TestColumn1 = CURRENT_TIMESTAMP");
}
[Test]
public override void CanCreateDecimalColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD COLUMN TestColumn1 DECIMAL(19,2) NOT NULL DEFAULT");
}
[Test]
public override void CanCreateDecimalColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateDecimalColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD COLUMN TestColumn1 DECIMAL(19,2) NOT NULL DEFAULT");
}
[Test]
public override void CanDropColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP COLUMN TestColumn1");
}
[Test]
public override void CanDropColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP COLUMN TestColumn1");
}
[Test]
public override void CanDropMultipleColumnsWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "TestColumn1", "TestColumn2" });
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP COLUMN TestColumn1 DROP COLUMN TestColumn2");
}
[Test]
public override void CanDropMultipleColumnsWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteColumnExpression(new[] { "TestColumn1", "TestColumn2" });
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP COLUMN TestColumn1 DROP COLUMN TestColumn2");
}
[Test]
public override void CanRenameColumnWithCustomSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe(string.Empty);
}
[Test]
public override void CanRenameColumnWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetRenameColumnExpression();
var result = Generator.Generate(expression);
result.ShouldBe(string.Empty);
}
[SetUp]
public void SetUp()
{
var generatorOptions = new OptionsWrapper<GeneratorOptions>(new GeneratorOptions());
Generator = new Db2Generator(new Db2ISeriesQuoter(), generatorOptions);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Timerial.Areas.HelpPage.ModelDescriptions;
using Timerial.Areas.HelpPage.Models;
namespace Timerial.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using OpenTK.Graphics.OpenGL;
using nzy3D.Colors;
using nzy3D.Maths;
using nzy3D.Plot3D.Primitives.Axes.Layout;
using nzy3D.Plot3D.Rendering.Canvas;
using nzy3D.Plot3D.Rendering.View;
using nzy3D.Plot3D.Text;
using nzy3D.Plot3D.Text.Align;
using nzy3D.Plot3D.Text.Renderers;
namespace nzy3D.Plot3D.Primitives.Axes
{
/// <summary>
/// The AxeBox displays a box with front face invisible and ticks labels.
/// @author Martin Pernollet
/// </summary>
public class AxeBox : IAxe
{
public enum AxeDirection
{
AxeX,
AxeY,
AxeZ
}
static internal int PRECISION = 6;
internal View _view;
// use this text renderer to get occupied volume by text
internal ITextRenderer _txt = new TextBitmapRenderer();
//Friend TextOverlay txtRenderer; ' keep it null in order to not use it
//'Friend TextBillboard txt = new TextBillboard();
internal IAxeLayout _layout;
internal BoundingBox3d _boxBounds;
internal BoundingBox3d _wholeBounds;
internal Coord3d _center;
internal Coord3d _scale;
internal float _xrange;
internal float _yrange;
internal float _zrange;
internal float[,] _quadx;
internal float[,] _quady;
internal float[,] _quadz;
internal float[] _normx;
internal float[] _normy;
internal float[] _normz;
internal float[,] _axeXx;
internal float[,] _axeXy;
internal float[,] _axeXz;
internal float[,] _axeYx;
internal float[,] _axeYy;
internal float[,] _axeYz;
internal float[,] _axeZx;
internal float[,] _axeZy;
internal float[,] _axeZz;
internal int[,] _axeXquads;
internal int[,] _axeYquads;
internal int[,] _axeZquads;
internal bool[] _quadIsHidden;
public AxeBox(BoundingBox3d bbox) : this(bbox, new AxeBoxLayout())
{
}
public AxeBox(BoundingBox3d bbox, IAxeLayout layout)
{
_layout = layout;
if (bbox.valid()) {
setAxe(bbox);
} else {
setAxe(new BoundingBox3d(-1, 1, -1, 1, -1, 1));
}
_wholeBounds = new BoundingBox3d();
Init();
}
public void Init()
{
this.Scale = new Coord3d(1, 1, 1);
}
public void Dispose()
{
//If Not IsNothing(_txtRenderer) Then
// _txtRenderer.Dispose()
//End If
}
public ITextRenderer TextRenderer {
get { return _txt; }
set { _txt = value; }
}
public View View {
get { return _view; }
set { _view = value; }
}
public IAxeLayout Layout {
get { return _layout; }
}
public void Draw(Rendering.View.Camera camera)
{
// Set scaling
GL.LoadIdentity();
GL.Scale(_scale.x, _scale.y, _scale.z);
// Set culling
GL.Enable(EnableCap.CullFace);
GL.FrontFace(FrontFaceDirection.Ccw);
GL.CullFace(CullFaceMode.Front);
// Draw cube in feedback buffer for computing hidden quads
_quadIsHidden = getHiddenQuads(camera);
// Plain part of quad making the surrounding box
if (_layout.FaceDisplayed) {
Color quadcolor = _layout.QuadColor;
GL.PolygonMode(MaterialFace.Back, PolygonMode.Fill);
GL.Color4(quadcolor.r, quadcolor.g, quadcolor.b, quadcolor.a);
GL.LineWidth(1);
GL.Enable(EnableCap.PolygonOffsetFill);
GL.PolygonOffset(1, 1);
// handle stippling
drawCube(OpenTK.Graphics.RenderingMode.Render);
GL.Disable(EnableCap.PolygonOffsetFill);
}
// Edge part of quads making the surrounding box
Color gridcolor = _layout.GridColor;
GL.PolygonMode(MaterialFace.Back, PolygonMode.Line);
GL.Color4(gridcolor.r, gridcolor.g, gridcolor.b, gridcolor.a);
GL.LineWidth(1);
drawCube(OpenTK.Graphics.RenderingMode.Render);
// Draw grids on non hidden quads
GL.PolygonMode(MaterialFace.Back, PolygonMode.Line);
GL.Color4(gridcolor.r, gridcolor.g, gridcolor.b, gridcolor.a);
GL.LineWidth(1);
GL.LineStipple(1, 0xaaaa);
GL.Enable(EnableCap.LineStipple);
for (int quad = 0; quad <= 5; quad++) {
if ((!_quadIsHidden[quad])) {
drawGridOnQuad(quad);
}
}
GL.Disable(EnableCap.LineStipple);
// Draw ticks on the closest axes
_wholeBounds.reset();
_wholeBounds.Add(_boxBounds);
//gl.glPolygonMode(GL2.GL_FRONT_AND_BACK, GL2.GL_LINE);
// Display x axis ticks
if ((_xrange > 0 & _layout.XTickLabelDisplayed)) {
// If we are on top, we make direct axe placement
if ((((_view != null) && _view.ViewMode == nzy3D.Plot3D.Rendering.View.Modes.ViewPositionMode.TOP))) {
BoundingBox3d bbox = drawTicks(camera, 1, AxeDirection.AxeX, _layout.XTickColor, Halign.LEFT, Valign.TOP);
// setup tick labels for X on the bottom
_wholeBounds.Add(bbox);
} else {
// otherwise computed placement
int xselect = findClosestXaxe(camera);
if ((xselect >= 0)) {
BoundingBox3d bbox = drawTicks(camera, xselect, AxeDirection.AxeX, _layout.XTickColor);
_wholeBounds.Add(bbox);
} else {
//System.err.println("no x axe selected: " + Arrays.toString(quadIsHidden));
// HACK: handles "on top" view, when all face of cube are drawn, which forbid to select an axe automatically
BoundingBox3d bbox = drawTicks(camera, 2, AxeDirection.AxeX, _layout.XTickColor, Halign.CENTER, Valign.TOP);
_wholeBounds.Add(bbox);
}
}
}
// Display y axis ticks
if ((_yrange > 0 & _layout.YTickLabelDisplayed)) {
if ((((_view != null)) && _view.ViewMode == nzy3D.Plot3D.Rendering.View.Modes.ViewPositionMode.TOP)) {
BoundingBox3d bbox = drawTicks(camera, 2, AxeDirection.AxeY, _layout.YTickColor, Halign.LEFT, Valign.GROUND);
// setup tick labels for Y on the left
_wholeBounds.Add(bbox);
} else {
int yselect = findClosestYaxe(camera);
if ((yselect >= 0)) {
BoundingBox3d bbox = drawTicks(camera, yselect, AxeDirection.AxeY, _layout.YTickColor);
_wholeBounds.Add(bbox);
} else {
//System.err.println("no y axe selected: " + Arrays.toString(quadIsHidden));
// HACK: handles "on top" view, when all face of cube are drawn, which forbid to select an axe automatically
BoundingBox3d bbox = drawTicks(camera, 1, AxeDirection.AxeY, _layout.YTickColor, Halign.RIGHT, Valign.GROUND);
_wholeBounds.Add(bbox);
}
}
}
// Display z axis ticks
if ((_zrange > 0 & _layout.ZTickLabelDisplayed)) {
if ((((_view != null)) && _view.ViewMode == nzy3D.Plot3D.Rendering.View.Modes.ViewPositionMode.TOP)) {
} else {
int zselect = findClosestZaxe(camera);
if ((zselect >= 0)) {
BoundingBox3d bbox = drawTicks(camera, zselect, AxeDirection.AxeZ, _layout.ZTickColor);
_wholeBounds.Add(bbox);
}
}
}
// Unset culling
GL.Disable(EnableCap.CullFace);
}
internal void setAxeBox(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
// Compute center
_center = new Coord3d((xmax + xmin) / 2, (ymax + ymin) / 2, (zmax + zmin) / 2);
_xrange = xmax - xmin;
_yrange = ymax - ymin;
_zrange = zmax - zmin;
// Define configuration of 6 quads (faces of the box)
_quadx = new float[6, 4];
_quady = new float[6, 4];
_quadz = new float[6, 4];
// x near
_quadx[0, 0] = xmax;
_quady[0, 0] = ymin;
_quadz[0, 0] = zmax;
_quadx[0, 1] = xmax;
_quady[0, 1] = ymin;
_quadz[0, 1] = zmin;
_quadx[0, 2] = xmax;
_quady[0, 2] = ymax;
_quadz[0, 2] = zmin;
_quadx[0, 3] = xmax;
_quady[0, 3] = ymax;
_quadz[0, 3] = zmax;
// x far
_quadx[1, 0] = xmin;
_quady[1, 0] = ymax;
_quadz[1, 0] = zmax;
_quadx[1, 1] = xmin;
_quady[1, 1] = ymax;
_quadz[1, 1] = zmin;
_quadx[1, 2] = xmin;
_quady[1, 2] = ymin;
_quadz[1, 2] = zmin;
_quadx[1, 3] = xmin;
_quady[1, 3] = ymin;
_quadz[1, 3] = zmax;
// y near
_quadx[2, 0] = xmax;
_quady[2, 0] = ymax;
_quadz[2, 0] = zmax;
_quadx[2, 1] = xmax;
_quady[2, 1] = ymax;
_quadz[2, 1] = zmin;
_quadx[2, 2] = xmin;
_quady[2, 2] = ymax;
_quadz[2, 2] = zmin;
_quadx[2, 3] = xmin;
_quady[2, 3] = ymax;
_quadz[2, 3] = zmax;
// y far
_quadx[3, 0] = xmin;
_quady[3, 0] = ymin;
_quadz[3, 0] = zmax;
_quadx[3, 1] = xmin;
_quady[3, 1] = ymin;
_quadz[3, 1] = zmin;
_quadx[3, 2] = xmax;
_quady[3, 2] = ymin;
_quadz[3, 2] = zmin;
_quadx[3, 3] = xmax;
_quady[3, 3] = ymin;
_quadz[3, 3] = zmax;
// z top
_quadx[4, 0] = xmin;
_quady[4, 0] = ymin;
_quadz[4, 0] = zmax;
_quadx[4, 1] = xmax;
_quady[4, 1] = ymin;
_quadz[4, 1] = zmax;
_quadx[4, 2] = xmax;
_quady[4, 2] = ymax;
_quadz[4, 2] = zmax;
_quadx[4, 3] = xmin;
_quady[4, 3] = ymax;
_quadz[4, 3] = zmax;
// z down
_quadx[5, 0] = xmax;
_quady[5, 0] = ymin;
_quadz[5, 0] = zmin;
_quadx[5, 1] = xmin;
_quady[5, 1] = ymin;
_quadz[5, 1] = zmin;
_quadx[5, 2] = xmin;
_quady[5, 2] = ymax;
_quadz[5, 2] = zmin;
_quadx[5, 3] = xmax;
_quady[5, 3] = ymax;
_quadz[5, 3] = zmin;
// Define configuration of each quad's normal
_normx = new float[6];
_normy = new float[6];
_normz = new float[6];
_normx[0] = xmax;
_normy[0] = 0;
_normz[0] = 0;
_normx[1] = xmin;
_normy[1] = 0;
_normz[1] = 0;
_normx[2] = 0;
_normy[2] = ymax;
_normz[2] = 0;
_normx[3] = 0;
_normy[3] = ymin;
_normz[3] = 0;
_normx[4] = 0;
_normy[4] = 0;
_normz[4] = zmax;
_normx[5] = 0;
_normy[5] = 0;
_normz[5] = zmin;
// Define quad intersections that generate an axe
// axe{A}quads[i][q]
// A = axe direction (X, Y, or Z)
// i = axe id (0 to 4)
// q = quad id (0 to 1: an intersection is made of two quads)
int na = 4;
// n axes per dimension
int np = 2;
// n points for an axe
int nq = 2;
int i = 0;
// axe id
_axeXquads = new int[na, nq];
_axeYquads = new int[na, nq];
_axeZquads = new int[na, nq];
// quads making axe x0
i = 0;
_axeXquads[i, 0] = 4;
_axeXquads[i, 1] = 3;
// quads making axe x1
i = 1;
_axeXquads[i, 0] = 3;
_axeXquads[i, 1] = 5;
// quads making axe x2
i = 2;
_axeXquads[i, 0] = 5;
_axeXquads[i, 1] = 2;
// quads making axe x3
i = 3;
_axeXquads[i, 0] = 2;
_axeXquads[i, 1] = 4;
// quads making axe y0
i = 0;
_axeYquads[i, 0] = 4;
_axeYquads[i, 1] = 0;
// quads making axe y1
i = 1;
_axeYquads[i, 0] = 0;
_axeYquads[i, 1] = 5;
// quads making axe y2
i = 2;
_axeYquads[i, 0] = 5;
_axeYquads[i, 1] = 1;
// quads making axe y3
i = 3;
_axeYquads[i, 0] = 1;
_axeYquads[i, 1] = 4;
// quads making axe z0
i = 0;
_axeZquads[i, 0] = 3;
_axeZquads[i, 1] = 0;
// quads making axe z1
i = 1;
_axeZquads[i, 0] = 0;
_axeZquads[i, 1] = 2;
// quads making axe z2
i = 2;
_axeZquads[i, 0] = 2;
_axeZquads[i, 1] = 1;
// quads making axe z3
i = 3;
_axeZquads[i, 0] = 1;
_axeZquads[i, 1] = 3;
// Define configuration of 4 axe per dimension:
// axe{A}d[i][p], where
//
// A = axe direction (X, Y, or Z)
// d = dimension (x coordinate, y coordinate or z coordinate)
// i = axe id (0 to 4)
// p = point id (0 to 1)
//
// Note: the points making an axe are from - to +
// (i.e. direction is given by p0->p1)
_axeXx = new float[na, np];
_axeXy = new float[na, np];
_axeXz = new float[na, np];
_axeYx = new float[na, np];
_axeYy = new float[na, np];
_axeYz = new float[na, np];
_axeZx = new float[na, np];
_axeZy = new float[na, np];
_axeZz = new float[na, np];
i = 0;
// axe x0
_axeXx[i, 0] = xmin;
_axeXy[i, 0] = ymin;
_axeXz[i, 0] = zmax;
_axeXx[i, 1] = xmax;
_axeXy[i, 1] = ymin;
_axeXz[i, 1] = zmax;
i = 1;
// axe x1
_axeXx[i, 0] = xmin;
_axeXy[i, 0] = ymin;
_axeXz[i, 0] = zmin;
_axeXx[i, 1] = xmax;
_axeXy[i, 1] = ymin;
_axeXz[i, 1] = zmin;
i = 2;
// axe x2
_axeXx[i, 0] = xmin;
_axeXy[i, 0] = ymax;
_axeXz[i, 0] = zmin;
_axeXx[i, 1] = xmax;
_axeXy[i, 1] = ymax;
_axeXz[i, 1] = zmin;
i = 3;
// axe x3
_axeXx[i, 0] = xmin;
_axeXy[i, 0] = ymax;
_axeXz[i, 0] = zmax;
_axeXx[i, 1] = xmax;
_axeXy[i, 1] = ymax;
_axeXz[i, 1] = zmax;
i = 0;
// axe y0
_axeYx[i, 0] = xmax;
_axeYy[i, 0] = ymin;
_axeYz[i, 0] = zmax;
_axeYx[i, 1] = xmax;
_axeYy[i, 1] = ymax;
_axeYz[i, 1] = zmax;
i = 1;
// axe y1
_axeYx[i, 0] = xmax;
_axeYy[i, 0] = ymin;
_axeYz[i, 0] = zmin;
_axeYx[i, 1] = xmax;
_axeYy[i, 1] = ymax;
_axeYz[i, 1] = zmin;
i = 2;
// axe y2
_axeYx[i, 0] = xmin;
_axeYy[i, 0] = ymin;
_axeYz[i, 0] = zmin;
_axeYx[i, 1] = xmin;
_axeYy[i, 1] = ymax;
_axeYz[i, 1] = zmin;
i = 3;
// axe y3
_axeYx[i, 0] = xmin;
_axeYy[i, 0] = ymin;
_axeYz[i, 0] = zmax;
_axeYx[i, 1] = xmin;
_axeYy[i, 1] = ymax;
_axeYz[i, 1] = zmax;
i = 0;
// axe z0
_axeZx[i, 0] = xmax;
_axeZy[i, 0] = ymin;
_axeZz[i, 0] = zmin;
_axeZx[i, 1] = xmax;
_axeZy[i, 1] = ymin;
_axeZz[i, 1] = zmax;
i = 1;
// axe z1
_axeZx[i, 0] = xmax;
_axeZy[i, 0] = ymax;
_axeZz[i, 0] = zmin;
_axeZx[i, 1] = xmax;
_axeZy[i, 1] = ymax;
_axeZz[i, 1] = zmax;
i = 2;
// axe z2
_axeZx[i, 0] = xmin;
_axeZy[i, 0] = ymax;
_axeZz[i, 0] = zmin;
_axeZx[i, 1] = xmin;
_axeZy[i, 1] = ymax;
_axeZz[i, 1] = zmax;
i = 3;
// axe z3
_axeZx[i, 0] = xmin;
_axeZy[i, 0] = ymin;
_axeZz[i, 0] = zmin;
_axeZx[i, 1] = xmin;
_axeZy[i, 1] = ymin;
_axeZz[i, 1] = zmax;
_layout.XTicks(xmin, xmax);
// prepare ticks to display in the layout tick buffer
_layout.YTicks(ymin, ymax);
_layout.ZTicks(zmin, zmax);
//setXTickMode(TICK_REGULAR, 3);5
//setYTickMode(TICK_REGULAR, 3);5
//setZTickMode(TICK_REGULAR, 5);6
}
/// <summary>
/// Make all GL2 calls allowing to build a cube with 6 separate quads.
/// Each quad is indexed from 0.0f to 5.0f using glPassThrough,
/// and may be traced in feedback mode when mode=<see cref="OpenTK.Graphics.RenderingMode.Feedback"/>
/// </summary>
public void drawCube(OpenTK.Graphics.RenderingMode mode)
{
for (int q = 0; q <= 5; q++) {
if (mode == OpenTK.Graphics.RenderingMode.Feedback) {
GL.PassThrough(q);
}
GL.Begin(BeginMode.Quads);
for (int v = 0; v <= 3; v++) {
GL.Vertex3(_quadx[q, v], _quady[q, v], _quadz[q, v]);
}
GL.End();
}
}
/// <summary>
/// Draw a grid on the desired quad.
/// </summary>
/// <param name="quad">Quad number, from 0 to 5</param>
internal void drawGridOnQuad(int quad)
{
// Draw X grid along X axis
if (((quad != 0) & (quad != 1))) {
float[] xticks = _layout.XTicks();
for (int t = 0; t <= xticks.Length - 1; t++) {
GL.Begin(BeginMode.Lines);
GL.Vertex3(xticks[t], _quady[quad, 0], _quadz[quad, 0]);
GL.Vertex3(xticks[t], _quady[quad, 2], _quadz[quad, 2]);
GL.End();
}
}
// Draw Y grid along Y axis
if (((quad != 2) & (quad != 3))) {
float[] yticks = _layout.YTicks();
for (int t = 0; t <= yticks.Length - 1; t++) {
GL.Begin(BeginMode.Lines);
GL.Vertex3(_quadx[quad, 0], yticks[t], _quadz[quad, 0]);
GL.Vertex3(_quadx[quad, 2], yticks[t], _quadz[quad, 2]);
GL.End();
}
}
// Draw Z grid along Z axis
if (((quad != 4) & (quad != 5))) {
float[] zticks = _layout.ZTicks();
if ((zticks != null)) {
for (int t = 0; t <= zticks.Length - 1; t++) {
GL.Begin(BeginMode.Lines);
GL.Vertex3(_quadx[quad, 0], _quady[quad, 0], zticks[t]);
GL.Vertex3(_quadx[quad, 2], _quady[quad, 2], zticks[t]);
GL.End();
}
}
}
}
internal BoundingBox3d drawTicks(Camera cam, int axis, AxeDirection direction, Color color)
{
return drawTicks(cam, axis, direction, color, Halign.DEFAULT, Valign.DEFAULT);
}
internal BoundingBox3d drawTicks(Camera cam, int axis, AxeDirection direction, Color color, Halign hal, Valign val)
{
int quad_0 = 0;
int quad_1 = 0;
float tickLength = 20.0f; // with respect to range
float axeLabelDist = 2.5f;
BoundingBox3d ticksTxtBounds = new BoundingBox3d();
// Retrieve the quads that intersect and create the selected axe
switch (direction) {
case AxeDirection.AxeX:
quad_0 = _axeXquads[axis, 0];
quad_1 = _axeXquads[axis, 1];
break;
case AxeDirection.AxeY:
quad_0 = _axeYquads[axis, 0];
quad_1 = _axeYquads[axis, 1];
break;
case AxeDirection.AxeZ:
quad_0 = _axeZquads[axis, 0];
quad_1 = _axeZquads[axis, 1];
break;
default:
throw new Exception("Unsupported axe direction");
}
// Computes PoSition of ticks lying on the selected axe
// (i.e. 1st point of the tick line)
float xpos = _normx[quad_0] + _normx[quad_1];
float ypos = _normy[quad_0] + _normy[quad_1];
float zpos = _normz[quad_0] + _normz[quad_1];
// Computes the DIRection of the ticks
// assuming initial vector point is the center
float xdir = (float)((_normx[quad_0] + _normx[quad_1]) - _center.x);
float ydir = (float)((_normy[quad_0] + _normy[quad_1]) - _center.y);
float zdir = (float)((_normz[quad_0] + _normz[quad_1]) - _center.z);
xdir = (xdir == 0 ? 0 : xdir / Math.Abs(xdir)); // so that direction as length 1
ydir = (ydir == 0 ? 0 : ydir / Math.Abs(ydir));
zdir = (zdir == 0 ? 0 : zdir / Math.Abs(zdir));
// Variables for storing the position of the Label position
// (2nd point on the tick line)
float xlab = 0;
float ylab = 0;
float zlab = 0;
// Draw the label for axis
string axeLabel = null;
int dist = 1;
switch (direction) {
case AxeDirection.AxeX:
xlab = (float)_center.x;
ylab = axeLabelDist * (_yrange / tickLength) * dist * ydir + ypos;
zlab = axeLabelDist * (_zrange / tickLength) * dist * zdir + zpos;
axeLabel = _layout.XAxeLabel;
break;
case AxeDirection.AxeY:
xlab = axeLabelDist * (_xrange / tickLength) * dist * xdir + xpos;
ylab = (float)_center.y;
zlab = axeLabelDist * (_zrange / tickLength) * dist * zdir + zpos;
axeLabel = _layout.YAxeLabel;
break;
case AxeDirection.AxeZ:
xlab = axeLabelDist * (_xrange / tickLength) * dist * xdir + xpos;
ylab = axeLabelDist * (_yrange / tickLength) * dist * ydir + ypos;
zlab = (float)_center.z;
axeLabel = _layout.ZAxeLabel;
break;
default:
throw new Exception("Unsupported axe direction");
}
drawAxisLabel(cam, direction, color, ticksTxtBounds, xlab, ylab, zlab, axeLabel);
drawAxisTicks(cam, direction, color, hal, val, tickLength, ticksTxtBounds, xpos, ypos, zpos, xdir, ydir, zdir, getAxisTicks(direction));
return ticksTxtBounds;
}
public void drawAxisLabel(Camera cam, AxeDirection direction, Color color, BoundingBox3d ticksTxtBounds, double xlab, double ylab, double zlab, String axeLabel)
{
if ((direction == AxeDirection.AxeX && _layout.XAxeLabelDisplayed)
|| (direction == AxeDirection.AxeY && _layout.YAxeLabelDisplayed)
|| (direction == AxeDirection.AxeZ && _layout.ZAxeLabelDisplayed))
{
Coord3d labelPosition = new Coord3d(xlab, ylab, zlab);
BoundingBox3d labelBounds = _txt.drawText(cam, axeLabel, labelPosition, Halign.CENTER, Valign.CENTER, color);
if (labelBounds != null)
ticksTxtBounds.Add(labelBounds);
}
}
public float[] getAxisTicks(AxeDirection direction)
{
float[] ticks;
switch (direction)
{
case AxeDirection.AxeX:
ticks = _layout.XTicks();
break;
case AxeDirection.AxeY:
ticks = _layout.YTicks();
break;
case AxeDirection.AxeZ:
ticks = _layout.ZTicks();
break;
default:
throw new Exception("Unsupported axe direction");
}
return ticks;
}
public void drawAxisTicks(Camera cam, AxeDirection direction, Color color, Halign hal, Valign val, float tickLength, BoundingBox3d ticksTxtBounds, float xpos,
float ypos, float zpos, float xdir, float ydir, float zdir, float[] ticks)
{
double xlab;
double ylab;
double zlab;
String tickLabel = "";
for (int t = 0; t < ticks.Length; t++)
{
// Shift the tick vector along the selected axis
// and set the tick length
switch (direction)
{
case AxeDirection.AxeX:
xpos = ticks[t];
xlab = xpos;
ylab = (_yrange / tickLength) * ydir + ypos;
zlab = (_zrange / tickLength) * zdir + zpos;
tickLabel = _layout.XTickRenderer.Format(xpos);
break;
case AxeDirection.AxeY:
ypos = ticks[t];
xlab = (_xrange / tickLength) * xdir + xpos;
ylab = ypos;
zlab = (_zrange / tickLength) * zdir + zpos;
tickLabel = _layout.YTickRenderer.Format(ypos);
break;
case AxeDirection.AxeZ:
zpos = ticks[t];
xlab = (_xrange / tickLength) * xdir + xpos;
ylab = (_yrange / tickLength) * ydir + ypos;
zlab = zpos;
tickLabel = _layout.ZTickRenderer.Format(zpos);
break;
default:
throw new Exception("Unsupported axe direction");
}
Coord3d tickPosition = new Coord3d(xlab, ylab, zlab);
if (_layout.TickLineDisplayed)
{
drawTickLine(color, xpos, ypos, zpos, xlab, ylab, zlab);
}
// Select the alignement of the tick label
Halign hAlign = layoutHorizontal(direction, cam, hal, tickPosition);
Valign vAlign = layoutVertical(direction, val, zdir);
// Draw the text label of the current tick
drawAxisTickNumericLabel(direction, cam, color, hAlign, vAlign, ticksTxtBounds, tickLabel, tickPosition);
}
}
public void drawAxisTickNumericLabel(AxeDirection direction, Camera cam, Color color, Halign hAlign, Valign vAlign, BoundingBox3d ticksTxtBounds, String tickLabel,
Coord3d tickPosition)
{
GL.LoadIdentity();
GL.Scale(_scale.x, _scale.y, _scale.z);
BoundingBox3d tickBounds = _txt.drawText(cam, tickLabel, tickPosition, hAlign, vAlign, color);
if (tickBounds != null)
ticksTxtBounds.Add(tickBounds);
}
public Valign layoutVertical(AxeDirection direction, Valign val, float zdir)
{
Valign vAlign;
if (val == null || val == Valign.DEFAULT)
{
if (direction == AxeDirection.AxeZ)
vAlign = Valign.CENTER;
else
{
if (zdir > 0)
vAlign = Valign.TOP;
else
vAlign = Valign.BOTTOM;
}
}
else
vAlign = val;
return vAlign;
}
public Halign layoutHorizontal(AxeDirection direction, Camera cam, Halign hal, Coord3d tickPosition)
{
Halign hAlign;
if (hal == null || hal == Halign.DEFAULT)
hAlign = cam.side(tickPosition) ? Halign.LEFT : Halign.RIGHT;
else
hAlign = hal;
return hAlign;
}
public void drawTickLine(Color color, double xpos, double ypos, double zpos, double xlab, double ylab, double zlab)
{
GL.Color3(color.r, color.g, color.b);
GL.LineWidth(1);
// Draw the tick line
GL.Begin(BeginMode.Lines);
GL.Vertex3(xpos, ypos, zpos);
GL.Vertex3(xlab, ylab, zlab);
GL.End();
}
/// <summary>
/// Selects the closest displayable X axe from camera
/// </summary>
internal int findClosestXaxe(Camera cam)
{
int na = 4;
double[] distAxeX = new double[na];
// keeps axes that are not at intersection of 2 quads
for (int a = 0; a <= na - 1; a++) {
if ((_quadIsHidden[_axeXquads[a, 0]] ^ _quadIsHidden[_axeXquads[a, 1]])) {
distAxeX[a] = new Vector3d(_axeXx[a, 0], _axeXy[a, 0], _axeXz[a, 0], _axeXx[a, 1], _axeXy[a, 1], _axeXz[a, 1]).distance(cam.Eye);
} else {
distAxeX[a] = double.MaxValue;
}
}
// prefers the lower one
for (int a = 0; a <= na - 1; a++) {
if ((distAxeX[a] < double.MaxValue)) {
if ((Center.z > (_axeXz[a, 0] + _axeXz[a, 1]) / 2)) {
distAxeX[a] *= -1;
}
}
}
return min(distAxeX);
}
/// <summary>
/// Selects the closest displayable Y axe from camera
/// </summary>
internal int findClosestYaxe(Camera cam)
{
int na = 4;
double[] distAxeY = new double[na];
// keeps axes that are not at intersection of 2 quads
for (int a = 0; a <= na - 1; a++) {
if ((_quadIsHidden[_axeYquads[a, 0]] ^ _quadIsHidden[_axeYquads[a, 1]])) {
distAxeY[a] = new Vector3d(_axeYx[a, 0], _axeYy[a, 0], _axeYz[a, 0], _axeYx[a, 1], _axeYy[a, 1], _axeYz[a, 1]).distance(cam.Eye);
} else {
distAxeY[a] = double.MaxValue;
}
}
// prefers the lower one
for (int a = 0; a <= na - 1; a++) {
if ((distAxeY[a] < double.MaxValue)) {
if ((Center.z > (_axeYz[a, 0] + _axeYz[a, 1]) / 2)) {
distAxeY[a] *= -1;
}
}
}
return min(distAxeY);
}
/// <summary>
/// Selects the closest displayable Z axe from camera
/// </summary>
internal int findClosestZaxe(Camera cam)
{
int na = 4;
double[] distAxeZ = new double[na];
// keeps axes that are not at intersection of 2 quads
for (int a = 0; a <= na - 1; a++) {
if ((_quadIsHidden[_axeZquads[a, 0]] ^ _quadIsHidden[_axeZquads[a, 1]])) {
distAxeZ[a] = new Vector3d(_axeZx[a, 0], _axeZy[a, 0], _axeZz[a, 0], _axeZx[a, 1], _axeZy[a, 1], _axeZz[a, 1]).distance(cam.Eye);
} else {
distAxeZ[a] = double.MaxValue;
}
}
// prefers the lower one
for (int a = 0; a <= na - 1; a++) {
if ((distAxeZ[a] < double.MaxValue)) {
Coord3d axeCEnter = new Coord3d((_axeZx[a, 0] + _axeZx[a, 1]) / 2, (_axeZy[a, 0] + _axeZy[a, 1]) / 2, (_axeZz[a, 0] + _axeZz[a, 1]) / 2);
if (!cam.side(axeCEnter)) {
distAxeZ[a] *= -1;
}
}
}
return min(distAxeZ);
}
protected int min(double[] values)
{
double minv = double.MaxValue;
int index = -1;
for (int i = 0; i <= values.Length - 1; i++) {
if (values[i] < minv) {
minv = values[i];
index = i;
}
}
return index;
}
/// <summary>
/// Computes the visibility of each cube face.
/// </summary>
internal bool[] getHiddenQuads(Camera cam)
{
bool[] status = new bool[6];
Coord3d se = cam.Eye.divide(_scale);
if (se.x <= _center.x) {
status[0] = false;
status[1] = true;
} else {
status[0] = true;
status[1] = false;
}
if (se.y <= _center.y) {
status[2] = false;
status[3] = true;
} else {
status[2] = true;
status[3] = false;
}
if (se.z <= _center.z) {
status[4] = false;
status[5] = true;
} else {
status[4] = true;
status[5] = false;
}
return status;
}
/// <summary>
/// Print out parameters of a gl call in 3dColor mode
/// </summary>
internal int print3DcolorVertex(int size, int count, float[] buffer)
{
int id = size - count;
int veclength = 7;
Console.WriteLine(" [" + id + "]");
for (int i = 0; i <= veclength - 1; i++) {
Console.WriteLine(" " + buffer[size - count]);
count = count - 1;
}
Console.WriteLine();
return count;
}
internal void printHiddenQuads()
{
for (int t = 0; t <= _quadIsHidden.Length - 1; t++) {
if (_quadIsHidden[t]) {
Console.WriteLine("Quad[" + t + "] is not displayed");
} else {
Console.WriteLine("Quad[" + t + "] is displayed");
}
}
}
public Maths.BoundingBox3d getBoxBounds()
{
return _boxBounds;
}
public Maths.Coord3d getCenter()
{
return this.Center;
}
public Layout.IAxeLayout getLayout()
{
return _layout;
}
public void setAxe(Maths.BoundingBox3d box)
{
_boxBounds = box;
setAxeBox((float)box.xmin, (float)box.xmax, (float)box.ymin, (float)box.ymax, (float)box.zmin, (float)box.zmax);
}
public BoundingBox3d WholeBounds {
get { return _wholeBounds; }
}
public Coord3d Center {
get { return _center; }
}
public Coord3d Scale {
set { _scale = value; }
}
public void setScale(Maths.Coord3d scale)
{
this.Scale = scale;
}
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================
| |
// 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 ConvertToVector128Int64UInt16()
{
var test = new SimpleUnaryOpTest__ConvertToVector128Int64UInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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 (Sse2.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 SimpleUnaryOpTest__ConvertToVector128Int64UInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt16);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector128<UInt16> _clsVar;
private Vector128<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<Int64, UInt16> _dataTable;
static SimpleUnaryOpTest__ConvertToVector128Int64UInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ConvertToVector128Int64UInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, UInt16>(_data, new Int64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.ConvertToVector128Int64(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.ConvertToVector128Int64(
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.ConvertToVector128Int64(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.ConvertToVector128Int64(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr);
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector128Int64UInt16();
var result = Sse41.ConvertToVector128Int64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.ConvertToVector128Int64(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
if (result[0] != firstOp[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.ConvertToVector128Int64)}<Int64>(Vector128<UInt16>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright 2018 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 Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ArcGISRuntime.Samples.SketchOnMap
{
[Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Sketch on map",
category: "GraphicsOverlay",
description: "Use the Sketch Editor to edit or sketch a new point, line, or polygon geometry on to a map.",
instructions: "Choose which geometry type to sketch from one of the available buttons. Choose from points, multipoints, polylines, polygons, freehand polylines, and freehand polygons.",
tags: new[] { "draw", "edit" })]
public class SketchOnMap : Activity
{
// Hold a reference to the map view
private MapView _myMapView;
// Dictionary to hold sketch mode enum names and values
private Dictionary<string, int> _sketchModeDictionary;
// Graphics overlay to host sketch graphics
private GraphicsOverlay _sketchOverlay;
// Buttons for interacting with the SketchEditor
private Button _editButton;
private Button _undoButton;
private Button _redoButton;
private Button _doneButton;
private Button _clearButton;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Sketch on map";
// Create the UI
CreateLayout();
// Initialize controls, set up event handlers, etc.
Initialize();
}
private void Initialize()
{
// Create a light gray canvas map
Map myMap = new Map(BasemapStyle.ArcGISLightGray);
// Create graphics overlay to display sketch geometry
_sketchOverlay = new GraphicsOverlay();
_myMapView.GraphicsOverlays.Add(_sketchOverlay);
// Assign the map to the MapView
_myMapView.Map = myMap;
// Listen to the sketch editor tools CanExecuteChange so controls can be enabled/disabled
_myMapView.SketchEditor.UndoCommand.CanExecuteChanged += CanExecuteChanged;
_myMapView.SketchEditor.RedoCommand.CanExecuteChanged += CanExecuteChanged;
_myMapView.SketchEditor.CompleteCommand.CanExecuteChanged += CanExecuteChanged;
// Listen to collection changed event on the graphics overlay to enable/disable controls that require a graphic
_sketchOverlay.Graphics.CollectionChanged += GraphicsChanged;
}
private void CreateLayout()
{
// Create horizontal layouts for the buttons at the top
LinearLayout buttonLayoutOne = new LinearLayout(this) { Orientation = Orientation.Horizontal };
LinearLayout buttonLayoutTwo = new LinearLayout(this) { Orientation = Orientation.Horizontal };
// Parameters for all of the buttons. Used to set buttons height and width.
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.MatchParent,
1.0f
);
// Button to sketch a selected geometry type on the map view
Button sketchButton = new Button(this)
{
Text = "Sketch",
LayoutParameters = param
};
sketchButton.Click += OnSketchClicked;
// Button to edit an existing graphic's geometry
_editButton = new Button(this)
{
Text = "Edit",
LayoutParameters = param
};
_editButton.Click += OnEditClicked;
_editButton.Enabled = false;
// Buttons to Undo/Redo sketch and edit operations
_undoButton = new Button(this)
{
Text = "Undo",
LayoutParameters = param
};
_undoButton.Click += OnUndoClicked;
_undoButton.Enabled = false;
_redoButton = new Button(this)
{
Text = "Redo",
LayoutParameters = param
};
_redoButton.Click += OnRedoClicked;
_redoButton.Enabled = false;
// Button to complete the sketch or edit
_doneButton = new Button(this)
{
Text = "Done",
LayoutParameters = param
};
_doneButton.Click += OnCompleteClicked;
_doneButton.Enabled = false;
// Button to clear all graphics and sketches
_clearButton = new Button(this)
{
Text = "Clear",
LayoutParameters = param
};
_clearButton.Click += OnClearClicked;
_clearButton.Enabled = false;
// Add all sketch controls (buttons) to the button bars
buttonLayoutOne.AddView(sketchButton);
buttonLayoutOne.AddView(_editButton);
buttonLayoutOne.AddView(_clearButton);
// Second button bar
buttonLayoutTwo.AddView(_undoButton);
buttonLayoutTwo.AddView(_redoButton);
buttonLayoutTwo.AddView(_doneButton);
// Create a new vertical layout for the app (buttons followed by map view)
LinearLayout mainLayout = new LinearLayout(this) { Orientation = Orientation.Vertical };
// Add the button layouts
mainLayout.AddView(buttonLayoutOne);
mainLayout.AddView(buttonLayoutTwo);
// Add the map view to the layout
_myMapView = new MapView(this);
mainLayout.AddView(_myMapView);
// Show the layout in the app
SetContentView(mainLayout);
}
private void OnSketchClicked(object sender, EventArgs e)
{
Button sketchButton = (Button)sender;
// Create a dictionary of enum names and values
IEnumerable<int> enumValues = Enum.GetValues(typeof(SketchCreationMode)).Cast<int>();
_sketchModeDictionary = enumValues.ToDictionary(v => Enum.GetName(typeof(SketchCreationMode), v), v => v);
// Create a menu to show sketch modes
PopupMenu sketchModesMenu = new PopupMenu(sketchButton.Context, sketchButton);
sketchModesMenu.MenuItemClick += OnSketchModeItemClicked;
// Create a menu option for each basemap type
foreach (string mode in _sketchModeDictionary.Keys)
{
sketchModesMenu.Menu.Add(mode);
}
// Show menu in the view
sketchModesMenu.Show();
}
private async void OnSketchModeItemClicked(object sender, PopupMenu.MenuItemClickEventArgs e)
{
try
{
// Get the title of the selected menu item (sketch mode)
string sketchModeName = e.Item.TitleCondensedFormatted.ToString();
// Let the user draw on the map view using the chosen sketch mode
SketchCreationMode creationMode = (SketchCreationMode)_sketchModeDictionary[sketchModeName];
Geometry geometry = await _myMapView.SketchEditor.StartAsync(creationMode, true);
// Create and add a graphic from the geometry the user drew
Graphic graphic = CreateGraphic(geometry);
_sketchOverlay.Graphics.Add(graphic);
}
catch (TaskCanceledException)
{
// Ignore ... let the user cancel drawing
}
catch (Exception ex)
{
// Report exceptions
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.SetTitle("Error drawing graphic shape");
alertBuilder.SetMessage(ex.Message);
alertBuilder.Show();
}
}
private async void OnEditClicked(object sender, EventArgs e)
{
try
{
// Allow the user to select a graphic
Graphic editGraphic = await GetGraphicAsync();
if (editGraphic == null) { return; }
// Let the user make changes to the graphic's geometry, await the result (updated geometry)
Geometry newGeometry = await _myMapView.SketchEditor.StartAsync(editGraphic.Geometry);
// Display the updated geometry in the graphic
editGraphic.Geometry = newGeometry;
}
catch (TaskCanceledException)
{
// Ignore ... let the user cancel editing
}
catch (Exception ex)
{
// Report exceptions
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.SetTitle("Error editing shape");
alertBuilder.SetMessage(ex.Message);
alertBuilder.Show();
}
}
private void OnClearClicked(object sender, EventArgs e)
{
// Remove all graphics from the graphics overlay
_sketchOverlay.Graphics.Clear();
// Cancel any uncompleted sketch
if (_myMapView.SketchEditor.CancelCommand.CanExecute(null))
{
_myMapView.SketchEditor.CancelCommand.Execute(null);
}
}
private void OnCompleteClicked(object sender, EventArgs e)
{
// Execute the CompleteCommand on the sketch editor
if (_myMapView.SketchEditor.CompleteCommand.CanExecute(null))
{
_myMapView.SketchEditor.CompleteCommand.Execute(null);
}
}
private void OnRedoClicked(object sender, EventArgs e)
{
// Execute the RedoCommand on the sketch editor
if (_myMapView.SketchEditor.RedoCommand.CanExecute(null))
{
_myMapView.SketchEditor.RedoCommand.Execute(null);
}
}
private void OnUndoClicked(object sender, EventArgs e)
{
// Execute the UndoCommand on the sketch editor
if (_myMapView.SketchEditor.UndoCommand.CanExecute(null))
{
_myMapView.SketchEditor.UndoCommand.Execute(null);
}
}
private void GraphicsChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// Enable or disable the clear and edit buttons depending on whether or not graphics exist
bool haveGraphics = _sketchOverlay.Graphics.Count > 0;
_editButton.Enabled = haveGraphics;
_clearButton.Enabled = haveGraphics;
}
private void CanExecuteChanged(object sender, EventArgs e)
{
// Enable or disable the corresponding command for the sketch editor
ICommand command = (ICommand)sender;
if (command == _myMapView.SketchEditor.UndoCommand)
{
_undoButton.Enabled = command.CanExecute(null);
}
else if (command == _myMapView.SketchEditor.RedoCommand)
{
_redoButton.Enabled = command.CanExecute(null);
}
else if (command == _myMapView.SketchEditor.CompleteCommand)
{
_doneButton.Enabled = command.CanExecute(null);
}
}
#region Graphic and symbol helpers
private Graphic CreateGraphic(Geometry geometry)
{
// Create a graphic to display the specified geometry
Symbol symbol = null;
switch (geometry.GeometryType)
{
// Symbolize with a fill symbol
case GeometryType.Envelope:
case GeometryType.Polygon:
{
symbol = new SimpleFillSymbol()
{
Color = Color.Red,
Style = SimpleFillSymbolStyle.Solid
};
break;
}
// Symbolize with a line symbol
case GeometryType.Polyline:
{
symbol = new SimpleLineSymbol()
{
Color = Color.Red,
Style = SimpleLineSymbolStyle.Solid,
Width = 5d
};
break;
}
// Symbolize with a marker symbol
case GeometryType.Point:
case GeometryType.Multipoint:
{
symbol = new SimpleMarkerSymbol()
{
Color = Color.Red,
Style = SimpleMarkerSymbolStyle.Circle,
Size = 15d
};
break;
}
}
// pass back a new graphic with the appropriate symbol
return new Graphic(geometry, symbol);
}
private async Task<Graphic> GetGraphicAsync()
{
// Wait for the user to click a location on the map
Geometry mapPoint = await _myMapView.SketchEditor.StartAsync(SketchCreationMode.Point, false);
// Convert the map point to a screen point
Android.Graphics.PointF screenCoordinate = _myMapView.LocationToScreen((MapPoint)mapPoint);
// Identify graphics in the graphics overlay using the point
IReadOnlyList<IdentifyGraphicsOverlayResult> results = await _myMapView.IdentifyGraphicsOverlaysAsync(screenCoordinate, 2, false);
// If results were found, get the first graphic
Graphic graphic = null;
IdentifyGraphicsOverlayResult idResult = results.FirstOrDefault();
if (idResult != null && idResult.Graphics.Count > 0)
{
graphic = idResult.Graphics.FirstOrDefault();
}
// Return the graphic (or null if none were found)
return graphic;
}
#endregion Graphic and symbol helpers
private async void SketchGeometry(string sketchModeName)
{
try
{
// Let the user draw on the map view using the chosen sketch mode
SketchCreationMode creationMode = (SketchCreationMode)_sketchModeDictionary[sketchModeName];
Geometry geometry = await _myMapView.SketchEditor.StartAsync(creationMode, true);
// Create and add a graphic from the geometry the user drew
Graphic graphic = CreateGraphic(geometry);
_sketchOverlay.Graphics.Add(graphic);
}
catch (TaskCanceledException)
{
// Ignore ... let the user cancel drawing
}
catch (Exception ex)
{
// Report exceptions
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.SetTitle("Error drawing graphic shape");
alertBuilder.SetMessage(ex.Message);
alertBuilder.Show();
}
}
private async void EditGraphic()
{
try
{
// Allow the user to select a graphic
Graphic editGraphic = await GetGraphicAsync();
if (editGraphic == null) { return; }
// Let the user make changes to the graphic's geometry, await the result (updated geometry)
Geometry newGeometry = await _myMapView.SketchEditor.StartAsync(editGraphic.Geometry);
// Display the updated geometry in the graphic
editGraphic.Geometry = newGeometry;
}
catch (TaskCanceledException)
{
// Ignore ... let the user cancel editing
}
catch (Exception ex)
{
// Report exceptions
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.SetTitle("Error editing shape");
alertBuilder.SetMessage(ex.Message);
alertBuilder.Show();
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the s3-2006-03-01.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.S3.Model;
namespace Amazon.S3
{
/// <summary>
/// Interface for accessing S3
///
///
/// </summary>
public partial interface IAmazonS3 : IDisposable
{
#region AbortMultipartUpload
/// <summary>
/// Initiates the asynchronous execution of the AbortMultipartUpload operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AbortMultipartUpload operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<AbortMultipartUploadResponse> AbortMultipartUploadAsync(AbortMultipartUploadRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CompleteMultipartUpload
/// <summary>
/// Initiates the asynchronous execution of the CompleteMultipartUpload operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CompleteMultipartUpload operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CompleteMultipartUploadResponse> CompleteMultipartUploadAsync(CompleteMultipartUploadRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CopyObject
/// <summary>
/// Initiates the asynchronous execution of the CopyObject operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CopyObject operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CopyObjectResponse> CopyObjectAsync(CopyObjectRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CopyPart
/// <summary>
/// Initiates the asynchronous execution of the CopyPart operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CopyPart operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CopyPartResponse> CopyPartAsync(CopyPartRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteBucket
/// <summary>
/// Initiates the asynchronous execution of the DeleteBucket operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteBucket operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteBucketResponse> DeleteBucketAsync(DeleteBucketRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteBucketPolicy
/// <summary>
/// Initiates the asynchronous execution of the DeleteBucketPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteBucketPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteBucketPolicyResponse> DeleteBucketPolicyAsync(DeleteBucketPolicyRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteBucketTagging
/// <summary>
/// Initiates the asynchronous execution of the DeleteBucketTagging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteBucketTagging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteBucketTaggingResponse> DeleteBucketTaggingAsync(DeleteBucketTaggingRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteBucketWebsite
/// <summary>
/// Initiates the asynchronous execution of the DeleteBucketWebsite operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteBucketWebsite operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteBucketWebsiteResponse> DeleteBucketWebsiteAsync(DeleteBucketWebsiteRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteCORSConfiguration
/// <summary>
/// Initiates the asynchronous execution of the DeleteCORSConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteCORSConfiguration operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteCORSConfigurationResponse> DeleteCORSConfigurationAsync(DeleteCORSConfigurationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteLifecycleConfiguration
/// <summary>
/// Initiates the asynchronous execution of the DeleteLifecycleConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteLifecycleConfiguration operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteLifecycleConfigurationResponse> DeleteLifecycleConfigurationAsync(DeleteLifecycleConfigurationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteObject
/// <summary>
/// Initiates the asynchronous execution of the DeleteObject operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteObject operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteObjectResponse> DeleteObjectAsync(DeleteObjectRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteObjects
/// <summary>
/// Initiates the asynchronous execution of the DeleteObjects operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteObjects operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteObjectsResponse> DeleteObjectsAsync(DeleteObjectsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetACL
/// <summary>
/// Initiates the asynchronous execution of the GetACL operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetACL operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetACLResponse> GetACLAsync(GetACLRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetBucketLocation
/// <summary>
/// Initiates the asynchronous execution of the GetBucketLocation operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBucketLocation operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetBucketLocationResponse> GetBucketLocationAsync(GetBucketLocationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetBucketLogging
/// <summary>
/// Initiates the asynchronous execution of the GetBucketLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBucketLogging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetBucketLoggingResponse> GetBucketLoggingAsync(GetBucketLoggingRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetBucketNotification
/// <summary>
/// Initiates the asynchronous execution of the GetBucketNotification operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBucketNotification operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetBucketNotificationResponse> GetBucketNotificationAsync(GetBucketNotificationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetBucketPolicy
/// <summary>
/// Initiates the asynchronous execution of the GetBucketPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBucketPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetBucketPolicyResponse> GetBucketPolicyAsync(GetBucketPolicyRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetBucketRequestPayment
/// <summary>
/// Initiates the asynchronous execution of the GetBucketRequestPayment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBucketRequestPayment operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetBucketRequestPaymentResponse> GetBucketRequestPaymentAsync(GetBucketRequestPaymentRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetBucketTagging
/// <summary>
/// Initiates the asynchronous execution of the GetBucketTagging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBucketTagging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetBucketTaggingResponse> GetBucketTaggingAsync(GetBucketTaggingRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetBucketVersioning
/// <summary>
/// Initiates the asynchronous execution of the GetBucketVersioning operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBucketVersioning operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetBucketVersioningResponse> GetBucketVersioningAsync(GetBucketVersioningRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetBucketWebsite
/// <summary>
/// Initiates the asynchronous execution of the GetBucketWebsite operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetBucketWebsite operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetBucketWebsiteResponse> GetBucketWebsiteAsync(GetBucketWebsiteRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetCORSConfiguration
/// <summary>
/// Initiates the asynchronous execution of the GetCORSConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetCORSConfiguration operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetCORSConfigurationResponse> GetCORSConfigurationAsync(GetCORSConfigurationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetLifecycleConfiguration
/// <summary>
/// Initiates the asynchronous execution of the GetLifecycleConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetLifecycleConfiguration operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetLifecycleConfigurationResponse> GetLifecycleConfigurationAsync(GetLifecycleConfigurationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetObject
/// <summary>
/// Initiates the asynchronous execution of the GetObject operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetObject operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetObjectResponse> GetObjectAsync(GetObjectRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetObjectMetadata
/// <summary>
/// Initiates the asynchronous execution of the GetObjectMetadata operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetObjectMetadata operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetObjectMetadataResponse> GetObjectMetadataAsync(GetObjectMetadataRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetObjectTorrent
/// <summary>
/// Initiates the asynchronous execution of the GetObjectTorrent operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetObjectTorrent operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetObjectTorrentResponse> GetObjectTorrentAsync(GetObjectTorrentRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region InitiateMultipartUpload
/// <summary>
/// Initiates the asynchronous execution of the InitiateMultipartUpload operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the InitiateMultipartUpload operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<InitiateMultipartUploadResponse> InitiateMultipartUploadAsync(InitiateMultipartUploadRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListBuckets
/// <summary>
/// Initiates the asynchronous execution of the ListBuckets operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListBuckets operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListBucketsResponse> ListBucketsAsync(ListBucketsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListMultipartUploads
/// <summary>
/// Initiates the asynchronous execution of the ListMultipartUploads operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListMultipartUploads operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListMultipartUploadsResponse> ListMultipartUploadsAsync(ListMultipartUploadsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListObjects
/// <summary>
/// Initiates the asynchronous execution of the ListObjects operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListObjects operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListObjectsResponse> ListObjectsAsync(ListObjectsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListParts
/// <summary>
/// Initiates the asynchronous execution of the ListParts operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListParts operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListPartsResponse> ListPartsAsync(ListPartsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListVersions
/// <summary>
/// Initiates the asynchronous execution of the ListVersions operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListVersions operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListVersionsResponse> ListVersionsAsync(ListVersionsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutACL
/// <summary>
/// Initiates the asynchronous execution of the PutACL operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutACL operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutACLResponse> PutACLAsync(PutACLRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutBucket
/// <summary>
/// Initiates the asynchronous execution of the PutBucket operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutBucket operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutBucketResponse> PutBucketAsync(PutBucketRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutBucketLogging
/// <summary>
/// Initiates the asynchronous execution of the PutBucketLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutBucketLogging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutBucketLoggingResponse> PutBucketLoggingAsync(PutBucketLoggingRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutBucketNotification
/// <summary>
/// Initiates the asynchronous execution of the PutBucketNotification operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutBucketNotification operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutBucketNotificationResponse> PutBucketNotificationAsync(PutBucketNotificationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutBucketPolicy
/// <summary>
/// Initiates the asynchronous execution of the PutBucketPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutBucketPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutBucketPolicyResponse> PutBucketPolicyAsync(PutBucketPolicyRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutBucketRequestPayment
/// <summary>
/// Initiates the asynchronous execution of the PutBucketRequestPayment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutBucketRequestPayment operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutBucketRequestPaymentResponse> PutBucketRequestPaymentAsync(PutBucketRequestPaymentRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutBucketTagging
/// <summary>
/// Initiates the asynchronous execution of the PutBucketTagging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutBucketTagging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutBucketTaggingResponse> PutBucketTaggingAsync(PutBucketTaggingRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutBucketVersioning
/// <summary>
/// Initiates the asynchronous execution of the PutBucketVersioning operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutBucketVersioning operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutBucketVersioningResponse> PutBucketVersioningAsync(PutBucketVersioningRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutBucketWebsite
/// <summary>
/// Initiates the asynchronous execution of the PutBucketWebsite operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutBucketWebsite operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutBucketWebsiteResponse> PutBucketWebsiteAsync(PutBucketWebsiteRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutCORSConfiguration
/// <summary>
/// Initiates the asynchronous execution of the PutCORSConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutCORSConfiguration operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutCORSConfigurationResponse> PutCORSConfigurationAsync(PutCORSConfigurationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutLifecycleConfiguration
/// <summary>
/// Initiates the asynchronous execution of the PutLifecycleConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutLifecycleConfiguration operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutLifecycleConfigurationResponse> PutLifecycleConfigurationAsync(PutLifecycleConfigurationRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutObject
/// <summary>
/// Initiates the asynchronous execution of the PutObject operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutObject operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<PutObjectResponse> PutObjectAsync(PutObjectRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RestoreObject
/// <summary>
/// Initiates the asynchronous execution of the RestoreObject operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RestoreObject operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<RestoreObjectResponse> RestoreObjectAsync(RestoreObjectRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UploadPart
/// <summary>
/// Initiates the asynchronous execution of the UploadPart operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UploadPart operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UploadPartResponse> UploadPartAsync(UploadPartRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
}
| |
using UnityEngine;
namespace Chronos
{
public class RigidbodyTimeline3D : RigidbodyTimeline<Rigidbody, RigidbodyTimeline3D.Snapshot>
{
// Scale is disabled by default because it usually doesn't change and
// would otherwise take more memory. Feel free to uncomment the lines
// below if you need to record it.
public struct Snapshot
{
public Vector3 position;
public Quaternion rotation;
// public Vector3 scale;
public Vector3 velocity;
public Vector3 angularVelocity;
public float lastPositiveTimeScale;
public static Snapshot Lerp(Snapshot from, Snapshot to, float t)
{
return new Snapshot()
{
position = Vector3.Lerp(from.position, to.position, t),
rotation = Quaternion.Lerp(from.rotation, to.rotation, t),
// scale = Vector3.Lerp(from.scale, to.scale, t),
velocity = Vector3.Lerp(from.velocity, to.velocity, t),
angularVelocity = Vector3.Lerp(from.angularVelocity, to.angularVelocity, t),
lastPositiveTimeScale = Mathf.Lerp(from.lastPositiveTimeScale, to.lastPositiveTimeScale, t),
};
}
}
public RigidbodyTimeline3D(Timeline timeline) : base(timeline) { }
public override void CopyProperties(Rigidbody source)
{
isKinematic = source.isKinematic;
useGravity = source.useGravity;
source.useGravity = false;
}
public override void FixedUpdate()
{
if (useGravity && !component.isKinematic && timeline.timeScale > 0)
{
velocity += (Physics.gravity * timeline.fixedDeltaTime);
}
}
public bool shouldSleep;
#region Snapshots
protected override Snapshot LerpSnapshots(Snapshot from, Snapshot to, float t)
{
return Snapshot.Lerp(from, to, t);
}
protected override Snapshot CopySnapshot()
{
return new Snapshot()
{
position = component.transform.position,
rotation = component.transform.rotation,
// scale = component.transform.localScale,
velocity = component.velocity,
angularVelocity = component.angularVelocity,
lastPositiveTimeScale = lastPositiveTimeScale
};
}
protected override void ApplySnapshot(Snapshot snapshot)
{
component.transform.position = snapshot.position;
component.transform.rotation = snapshot.rotation;
// component.transform.localScale = snapshot.scale;
if (timeline.timeScale > 0)
{
component.velocity = snapshot.velocity;
component.angularVelocity = snapshot.angularVelocity;
}
lastPositiveTimeScale = snapshot.lastPositiveTimeScale;
}
#endregion
#region Components
protected bool bodyUseGravity
{
get { return component.useGravity; }
set { component.useGravity = value; }
}
protected override bool bodyIsKinematic
{
get { return component.isKinematic; }
set { component.isKinematic = value; }
}
protected override float bodyMass
{
get { return component.mass; }
set { component.mass = value; }
}
protected override Vector3 bodyVelocity
{
get { return component.velocity; }
set { component.velocity = value; }
}
protected override Vector3 bodyAngularVelocity
{
get { return component.angularVelocity; }
set { component.angularVelocity = value; }
}
protected override float bodyDrag
{
get { return component.drag; }
set { component.drag = value; }
}
protected override float bodyAngularDrag
{
get { return component.angularDrag; }
set { component.angularDrag = value; }
}
protected override void WakeUp()
{
component.WakeUp();
}
protected override bool IsSleeping()
{
return component.IsSleeping();
}
/// <summary>
/// Determines whether the rigidbody uses gravity. Use this property instead of Rigidbody.useGravity, which will be overwritten by the physics timer at runtime.
/// </summary>
public bool useGravity { get; set; }
/// <summary>
/// The velocity of the rigidbody before time effects. Use this property instead of Rigidbody.velocity, which will be overwritten by the physics timer at runtime.
/// </summary>
public Vector3 velocity
{
get { return bodyVelocity / timeline.timeScale; }
set { if (AssertForwardProperty("velocity", Severity.Ignore)) bodyVelocity = value * timeline.timeScale; }
}
/// <summary>
/// The angular velocity of the rigidbody before time effects. Use this property instead of Rigidbody.angularVelocity, which will be overwritten by the physics timer at runtime.
/// </summary>
public Vector3 angularVelocity
{
get { return bodyAngularVelocity / timeline.timeScale; }
set { if (AssertForwardProperty("angularVelocity", Severity.Ignore)) bodyAngularVelocity = value * timeline.timeScale; }
}
/// <summary>
/// The equivalent of Rigidbody.AddForce adjusted for time effects.
/// </summary>
public void AddForce(Vector3 force, ForceMode mode = ForceMode.Force)
{
if (AssertForwardForce(Severity.Ignore))
component.AddForce(AdjustForce(force), mode);
}
/// <summary>
/// The equivalent of Rigidbody.AddRelativeForce adjusted for time effects.
/// </summary>
public void AddRelativeForce(Vector3 force, ForceMode mode = ForceMode.Force)
{
if (AssertForwardForce(Severity.Ignore))
component.AddRelativeForce(AdjustForce(force), mode);
}
/// <summary>
/// The equivalent of Rigidbody.AddForceAtPosition adjusted for time effects.
/// </summary>
public void AddForceAtPosition(Vector3 force, Vector3 position, ForceMode mode = ForceMode.Force)
{
if (AssertForwardForce(Severity.Ignore))
component.AddForceAtPosition(AdjustForce(force), position, mode);
}
/// <summary>
/// The equivalent of Rigidbody.AddRelativeForce adjusted for time effects.
/// </summary>
public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius,
float upwardsModifier = 0, ForceMode mode = ForceMode.Force)
{
if (AssertForwardForce(Severity.Ignore))
component.AddExplosionForce(AdjustForce(explosionForce), explosionPosition, explosionRadius, upwardsModifier, mode);
}
/// <summary>
/// The equivalent of Rigidbody.AddTorque adjusted for time effects.
/// </summary>
public void AddTorque(Vector3 torque, ForceMode mode = ForceMode.Force)
{
if (AssertForwardForce(Severity.Ignore))
component.AddTorque(AdjustForce(torque), mode);
}
/// <summary>
/// The equivalent of Rigidbody.AddRelativeTorque adjusted for time effects.
/// </summary>
public void AddRelativeTorque(Vector3 torque, ForceMode mode = ForceMode.Force)
{
if (AssertForwardForce(Severity.Ignore))
component.AddRelativeTorque(AdjustForce(torque), mode);
}
#endregion
}
}
| |
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NuGet.Test.Mocks;
namespace NuGet.Test {
[TestClass]
public class PackageRepositoryTest {
[TestMethod]
public void FindByIdReturnsPackage() {
// Arrange
var repo = GetLocalRepository();
// Act
var package = repo.FindPackage(packageId: "A");
// Assert
Assert.IsNotNull(package);
Assert.AreEqual("A", package.Id);
}
[TestMethod]
public void FindByIdReturnsNullWhenPackageNotFound() {
// Arrange
var repo = GetLocalRepository();
// Act
var package = repo.FindPackage(packageId: "X");
// Assert
Assert.IsNull(package);
}
[TestMethod]
public void FindByIdAndVersionReturnsPackage() {
// Arrange
var repo = GetRemoteRepository();
// Act
var package = repo.FindPackage(packageId: "A", version: Version.Parse("1.0"));
// Assert
Assert.IsNotNull(package);
Assert.AreEqual("A", package.Id);
Assert.AreEqual(Version.Parse("1.0"), package.Version);
}
[TestMethod]
public void FindByIdAndVersionReturnsNullWhenPackageNotFound() {
// Arrange
var repo = GetLocalRepository();
// Act
var package1 = repo.FindPackage(packageId: "X", version: Version.Parse("1.0"));
var package2 = repo.FindPackage(packageId: "A", version: Version.Parse("1.1"));
// Assert
Assert.IsNull(package1 ?? package2);
}
[TestMethod]
public void FindByIdAndVersionRangeReturnsPackage() {
// Arrange
var repo = GetRemoteRepository();
// Act
var package = repo.FindPackage("A", "[0.9, 1.1]");
// Assert
Assert.IsNotNull(package);
Assert.AreEqual("A", package.Id);
Assert.AreEqual(Version.Parse("1.0"), package.Version);
}
[TestMethod]
public void FindByIdAndVersionRangeReturnsNullWhenPackageNotFound() {
// Arrange
var repo = GetLocalRepository();
// Act
var package1 = repo.FindPackage("X", "[0.9, 1.1]");
var package2 = repo.FindPackage("A", "[1.4, 1.5]");
// Assert
Assert.IsNull(package1 ?? package2);
}
[TestMethod]
public void FindPackageByIdVersionAndVersionRangesUsesRangeIfExactVersionIsNull() {
// Arrange
var repo = GetRemoteRepository();
// Act
var package = repo.FindPackage("A", "[0.6, 1.1.5]");
// Assert
Assert.IsNotNull(package);
Assert.AreEqual("A", package.Id);
Assert.AreEqual(Version.Parse("1.0"), package.Version);
}
[TestMethod]
public void FindPackagesReturnsPackagesWithTermInPackageTagOrDescriptionOrId() {
// Arrange
var term = "TAG";
var repo = new MockPackageRepository();
repo.Add(CreateMockPackage("A", "1.0", "Description", " TAG "));
repo.Add(CreateMockPackage("B", "2.0", "Description", "Tags"));
repo.Add(CreateMockPackage("C", "1.0", "This description has tags in it"));
repo.Add(CreateMockPackage("D", "1.0", "Description"));
repo.Add(CreateMockPackage("TagCloud", "1.0", "Description"));
// Act
var packages = repo.GetPackages().Find(term.Split()).ToList();
// Assert
Assert.AreEqual(3, packages.Count);
Assert.AreEqual("A", packages[0].Id);
Assert.AreEqual("C", packages[1].Id);
Assert.AreEqual("TagCloud", packages[2].Id);
}
[TestMethod]
public void FindPackagesReturnsPackagesWithTerm() {
// Arrange
var term = "B xaml";
var repo = GetRemoteRepository();
// Act
var packages = repo.GetPackages().Find(term.Split());
// Assert
Assert.AreEqual(packages.Count(), 2);
packages = packages.OrderBy(p => p.Id);
Assert.AreEqual(packages.ElementAt(0).Id, "B");
Assert.AreEqual(packages.ElementAt(1).Id, "C");
}
[TestMethod]
public void FindPackagesReturnsEmptyCollectionWhenNoPackageContainsTerm() {
// Arrange
var term = "does-not-exist";
var repo = GetRemoteRepository();
// Act
var packages = repo.GetPackages().Find(term.Split());
// Assert
Assert.IsFalse(packages.Any());
}
[TestMethod]
public void FindPackagesReturnsAllPackagesWhenSearchTermIsNullOrEmpty() {
// Arrange
var repo = GetLocalRepository();
// Act
var packages1 = repo.GetPackages().Find(String.Empty);
var packages2 = repo.GetPackages().Find(null);
var packages3 = repo.GetPackages();
// Assert
CollectionAssert.AreEqual(packages1.ToList(), packages2.ToList());
CollectionAssert.AreEqual(packages2.ToList(), packages3.ToList());
}
[TestMethod]
public void GetUpdatesReturnsPackagesWithUpdates() {
// Arrange
var localRepo = GetLocalRepository();
var remoteRepo = GetRemoteRepository();
// Act
var packages = remoteRepo.GetUpdates(localRepo.GetPackages());
// Assert
Assert.IsTrue(packages.Any());
Assert.AreEqual(packages.First().Id, "A");
Assert.AreEqual(packages.First().Version, Version.Parse("1.2"));
}
[TestMethod]
public void GetUpdatesReturnsEmptyCollectionWhenSourceRepositoryIsEmpty() {
// Arrange
var localRepo = GetLocalRepository();
var remoteRepo = GetEmptyRepository();
// Act
var packages = remoteRepo.GetUpdates(localRepo.GetPackages());
// Assert
Assert.IsFalse(packages.Any());
}
[TestMethod]
public void FindDependencyPicksHighestVersionIfNotSpecified() {
// Arrange
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0"),
PackageUtility.CreatePackage("B", "1.0"),
PackageUtility.CreatePackage("B", "1.0.1"),
PackageUtility.CreatePackage("B", "1.0.9"),
PackageUtility.CreatePackage("B", "1.1")
};
var dependency = new PackageDependency("B");
// Act
IPackage package = repository.FindDependency(dependency);
// Assert
Assert.AreEqual("B", package.Id);
Assert.AreEqual(new Version("2.0"), package.Version);
}
[TestMethod]
public void FindDependencyPicksLowestMajorAndMinorVersionButHighestBuildAndRevision() {
// Arrange
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0"),
PackageUtility.CreatePackage("B", "1.0"),
PackageUtility.CreatePackage("B", "1.0.1"),
PackageUtility.CreatePackage("B", "1.0.9"),
PackageUtility.CreatePackage("B", "1.1")
};
// B >= 1.0
PackageDependency dependency1 = PackageDependency.CreateDependency("B", "1.0");
// B >= 1.0.0
PackageDependency dependency2 = PackageDependency.CreateDependency("B", "1.0.0");
// B >= 1.0.0.0
PackageDependency dependency3 = PackageDependency.CreateDependency("B", "1.0.0.0");
// B = 1.0
PackageDependency dependency4 = PackageDependency.CreateDependency("B", "[1.0]");
// B >= 1.0.0 && <= 1.0.8
PackageDependency dependency5 = PackageDependency.CreateDependency("B", "[1.0.0, 1.0.8]");
// Act
IPackage package1 = repository.FindDependency(dependency1);
IPackage package2 = repository.FindDependency(dependency2);
IPackage package3 = repository.FindDependency(dependency3);
IPackage package4 = repository.FindDependency(dependency4);
IPackage package5 = repository.FindDependency(dependency5);
// Assert
Assert.AreEqual("B", package1.Id);
Assert.AreEqual(new Version("1.0.9"), package1.Version);
Assert.AreEqual("B", package2.Id);
Assert.AreEqual(new Version("1.0.9"), package2.Version);
Assert.AreEqual("B", package3.Id);
Assert.AreEqual(new Version("1.0.9"), package3.Version);
Assert.AreEqual("B", package4.Id);
Assert.AreEqual(new Version("1.0"), package4.Version);
Assert.AreEqual("B", package5.Id);
Assert.AreEqual(new Version("1.0.1"), package5.Version);
}
private static IPackageRepository GetEmptyRepository() {
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
repository.Setup(c => c.GetPackages()).Returns(() => Enumerable.Empty<IPackage>().AsQueryable());
return repository.Object;
}
private static IPackageRepository GetRemoteRepository() {
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
var packages = new[] { CreateMockPackage("A", "1.0", "scripts style"),
CreateMockPackage("B", "1.0", "testing"),
CreateMockPackage("C", "2.0", "xaml"),
CreateMockPackage("A", "1.2", "a updated desc") };
repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable());
return repository.Object;
}
private static IPackageRepository GetLocalRepository() {
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
var packages = new[] { CreateMockPackage("A", "1.0"), CreateMockPackage("B", "1.0") };
repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable());
return repository.Object;
}
private static IPackage CreateMockPackage(string name, string version, string desc = null, string tags = null) {
Mock<IPackage> package = new Mock<IPackage>();
package.SetupGet(p => p.Id).Returns(name);
package.SetupGet(p => p.Version).Returns(Version.Parse(version));
package.SetupGet(p => p.Description).Returns(desc);
package.SetupGet(p => p.Tags).Returns(tags);
return package.Object;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Management.Automation;
using System.Management.Automation.SecurityAccountsManager;
using System.Management.Automation.SecurityAccountsManager.Extensions;
using Microsoft.PowerShell.LocalAccounts;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The Remove-LocalGroup cmdlet deletes a security group from the Windows
/// Security Accounts manager.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "LocalGroup",
SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717975")]
[Alias("rlg")]
public class RemoveLocalGroupCommand : Cmdlet
{
#region Instance Data
private Sam sam = null;
#endregion Instance Data
#region Parameter Properties
/// <summary>
/// The following is the definition of the input parameter "InputObject".
/// Specifies security groups from the local Security Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "InputObject")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Microsoft.PowerShell.Commands.LocalGroup[] InputObject
{
get { return this.inputobject; }
set { this.inputobject = value; }
}
private Microsoft.PowerShell.Commands.LocalGroup[] inputobject;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// Specifies the local groups to be deleted from the local Security Accounts
/// Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "Default")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return this.name; }
set { this.name = value; }
}
private string[] name;
/// <summary>
/// The following is the definition of the input parameter "SID".
/// Specifies the LocalGroup accounts to remove by
/// System.Security.Principal.SecurityIdentifier.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SecurityIdentifier")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public System.Security.Principal.SecurityIdentifier[] SID
{
get { return this.sid; }
set { this.sid = value; }
}
private System.Security.Principal.SecurityIdentifier[] sid;
#endregion Parameter Properties
#region Cmdlet Overrides
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
sam = new Sam();
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
try
{
ProcessGroups();
ProcessNames();
ProcessSids();
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
if (sam != null)
{
sam.Dispose();
sam = null;
}
}
#endregion Cmdlet Overrides
#region Private Methods
/// <summary>
/// Process groups requested by -Name.
/// </summary>
/// <remarks>
/// All arguments to -Name will be treated as names,
/// even if a name looks like a SID.
/// </remarks>
private void ProcessNames()
{
if (Name != null)
{
foreach (var name in Name)
{
try
{
if (CheckShouldProcess(name))
sam.RemoveLocalGroup(sam.GetLocalGroup(name));
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
/// <summary>
/// Process groups requested by -SID.
/// </summary>
private void ProcessSids()
{
if (SID != null)
{
foreach (var sid in SID)
{
try
{
if (CheckShouldProcess(sid.ToString()))
sam.RemoveLocalGroup(sid);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
/// <summary>
/// Process groups given through -InputObject.
/// </summary>
private void ProcessGroups()
{
if (InputObject != null)
{
foreach (var group in InputObject)
{
try
{
if (CheckShouldProcess(group.Name))
sam.RemoveLocalGroup(group);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
}
private bool CheckShouldProcess(string target)
{
return ShouldProcess(target, Strings.ActionRemoveGroup);
}
#endregion Private Methods
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Cookie.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Cookie
{
/// <summary>
/// <para>This cookie comparator can be used to compare identity of cookies.</para><para>Cookies are considered identical if their names are equal and their domain attributes match ignoring case. </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieIdentityComparator
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieIdentityComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" +
"okie/Cookie;>;")]
public partial class CookieIdentityComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie>
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookieIdentityComparator() /* MethodBuilder.Create */
{
}
/// <java-name>
/// compare
/// </java-name>
[Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)]
public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)]
public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SM
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ISMConstants
/* scope: __dot42__ */
{
/// <java-name>
/// COOKIE
/// </java-name>
[Dot42.DexImport("COOKIE", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE = "Cookie";
/// <java-name>
/// COOKIE2
/// </java-name>
[Dot42.DexImport("COOKIE2", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE2 = "Cookie2";
/// <java-name>
/// SET_COOKIE
/// </java-name>
[Dot42.DexImport("SET_COOKIE", "Ljava/lang/String;", AccessFlags = 25)]
public const string SET_COOKIE = "Set-Cookie";
/// <java-name>
/// SET_COOKIE2
/// </java-name>
[Dot42.DexImport("SET_COOKIE2", "Ljava/lang/String;", AccessFlags = 25)]
public const string SET_COOKIE2 = "Set-Cookie2";
}
/// <summary>
/// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SM
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537)]
public partial interface ISM
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/Cookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/Cookie", AccessFlags = 1537)]
public partial interface ICookie
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the name.</para><para></para>
/// </summary>
/// <returns>
/// <para>String name The name </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetName() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the value.</para><para></para>
/// </summary>
/// <returns>
/// <para>String value The current value. </para>
/// </returns>
/// <java-name>
/// getValue
/// </java-name>
[Dot42.DexImport("getValue", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetValue() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the comment describing the purpose of this cookie, or <code>null</code> if no such comment has been defined.</para><para></para>
/// </summary>
/// <returns>
/// <para>comment </para>
/// </returns>
/// <java-name>
/// getComment
/// </java-name>
[Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetComment() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para>
/// </summary>
/// <java-name>
/// getCommentURL
/// </java-name>
[Dot42.DexImport("getCommentURL", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetCommentURL() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the expiration Date of the cookie, or <code>null</code> if none exists. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril. </para><para></para>
/// </summary>
/// <returns>
/// <para>Expiration Date, or <code>null</code>. </para>
/// </returns>
/// <java-name>
/// getExpiryDate
/// </java-name>
[Dot42.DexImport("getExpiryDate", "()Ljava/util/Date;", AccessFlags = 1025)]
global::Java.Util.Date GetExpiryDate() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise </para>
/// </returns>
/// <java-name>
/// isPersistent
/// </java-name>
[Dot42.DexImport("isPersistent", "()Z", AccessFlags = 1025)]
bool IsPersistent() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns domain attribute of the cookie.</para><para></para>
/// </summary>
/// <returns>
/// <para>the value of the domain attribute </para>
/// </returns>
/// <java-name>
/// getDomain
/// </java-name>
[Dot42.DexImport("getDomain", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetDomain() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the path attribute of the cookie</para><para></para>
/// </summary>
/// <returns>
/// <para>The value of the path attribute. </para>
/// </returns>
/// <java-name>
/// getPath
/// </java-name>
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetPath() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Get the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para>
/// </summary>
/// <java-name>
/// getPorts
/// </java-name>
[Dot42.DexImport("getPorts", "()[I", AccessFlags = 1025)]
int[] GetPorts() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Indicates whether this cookie requires a secure connection.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if this cookie should only be sent over secure connections, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1025)]
bool IsSecure() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the version of the cookie specification to which this cookie conforms.</para><para></para>
/// </summary>
/// <returns>
/// <para>the version of the cookie. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns true if this cookie has expired. </para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the cookie has expired. </para>
/// </returns>
/// <java-name>
/// isExpired
/// </java-name>
[Dot42.DexImport("isExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)]
bool IsExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>This interface represents a <code>SetCookie</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SetCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SetCookie", AccessFlags = 1537)]
public partial interface ISetCookie : global::Org.Apache.Http.Cookie.ICookie
/* scope: __dot42__ */
{
/// <java-name>
/// setValue
/// </java-name>
[Dot42.DexImport("setValue", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetValue(string value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.</para><para><para>getComment() </para></para>
/// </summary>
/// <java-name>
/// setComment
/// </java-name>
[Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetComment(string comment) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets expiration date. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril.</para><para><para>Cookie::getExpiryDate </para></para>
/// </summary>
/// <java-name>
/// setExpiryDate
/// </java-name>
[Dot42.DexImport("setExpiryDate", "(Ljava/util/Date;)V", AccessFlags = 1025)]
void SetExpiryDate(global::Java.Util.Date expiryDate) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the domain attribute.</para><para><para>Cookie::getDomain </para></para>
/// </summary>
/// <java-name>
/// setDomain
/// </java-name>
[Dot42.DexImport("setDomain", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetDomain(string domain) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the path attribute.</para><para><para>Cookie::getPath </para></para>
/// </summary>
/// <java-name>
/// setPath
/// </java-name>
[Dot42.DexImport("setPath", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetPath(string path) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the secure attribute of the cookie. </para><para>When <code>true</code> the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.</para><para><para>isSecure() </para></para>
/// </summary>
/// <java-name>
/// setSecure
/// </java-name>
[Dot42.DexImport("setSecure", "(Z)V", AccessFlags = 1025)]
void SetSecure(bool secure) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the version of the cookie specification to which this cookie conforms.</para><para><para>Cookie::getVersion </para></para>
/// </summary>
/// <java-name>
/// setVersion
/// </java-name>
[Dot42.DexImport("setVersion", "(I)V", AccessFlags = 1025)]
void SetVersion(int version) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Defines the cookie management specification. </para><para>Cookie management specification must define <ul><li><para>rules of parsing "Set-Cookie" header </para></li><li><para>rules of validation of parsed cookies </para></li><li><para>formatting of "Cookie" header </para></li></ul>for a given host, port and path of origin</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpec
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpec", AccessFlags = 1537)]
public partial interface ICookieSpec
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns version of the state management this cookie specification conforms to.</para><para></para>
/// </summary>
/// <returns>
/// <para>version of the state management specification </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Parse the <code>"Set-Cookie"</code> Header into an array of Cookies.</para><para>This method will not perform the validation of the resultant Cookies</para><para><para>validate</para></para>
/// </summary>
/// <returns>
/// <para>an array of <code>Cookie</code>s parsed from the header </para>
/// </returns>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List<Lo" +
"rg/apache/http/cookie/Cookie;>;")]
global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> Parse(global::Org.Apache.Http.IHeader header, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Validate the cookie according to validation rules defined by the cookie specification.</para><para></para>
/// </summary>
/// <java-name>
/// validate
/// </java-name>
[Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)]
void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Determines if a Cookie matches the target location.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the cookie should be submitted with a request with given attributes, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// match
/// </java-name>
[Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)]
bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create <code>"Cookie"</code> headers for an array of Cookies.</para><para></para>
/// </summary>
/// <returns>
/// <para>a Header for the given Cookies. </para>
/// </returns>
/// <java-name>
/// formatCookies
/// </java-name>
[Dot42.DexImport("formatCookies", "(Ljava/util/List;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;)Ljava/util/List<Lorg/apache/ht" +
"tp/Header;>;")]
global::Java.Util.IList<global::Org.Apache.Http.IHeader> FormatCookies(global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> cookies) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a request header identifying what version of the state management specification is understood. May be <code>null</code> if the cookie specification does not support <code>Cookie2</code> header. </para>
/// </summary>
/// <java-name>
/// getVersionHeader
/// </java-name>
[Dot42.DexImport("getVersionHeader", "()Lorg/apache/http/Header;", AccessFlags = 1025)]
global::Org.Apache.Http.IHeader GetVersionHeader() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.</para><para>Different cookie specifications can provide a specific implementation for this class based on their cookie handling rules.</para><para><para> (Samit Jain)</para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieAttributeHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieAttributeHandler", AccessFlags = 1537)]
public partial interface ICookieAttributeHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>Parse the given cookie attribute value and update the corresponding org.apache.http.cookie.Cookie property.</para><para></para>
/// </summary>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/cookie/SetCookie;Ljava/lang/String;)V", AccessFlags = 1025)]
void Parse(global::Org.Apache.Http.Cookie.ISetCookie cookie, string value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Peforms cookie validation for the given attribute value.</para><para></para>
/// </summary>
/// <java-name>
/// validate
/// </java-name>
[Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)]
void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the match is successful; <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// match
/// </java-name>
[Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)]
bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/ClientCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IClientCookieConstants
/* scope: __dot42__ */
{
/// <java-name>
/// VERSION_ATTR
/// </java-name>
[Dot42.DexImport("VERSION_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string VERSION_ATTR = "version";
/// <java-name>
/// PATH_ATTR
/// </java-name>
[Dot42.DexImport("PATH_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string PATH_ATTR = "path";
/// <java-name>
/// DOMAIN_ATTR
/// </java-name>
[Dot42.DexImport("DOMAIN_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string DOMAIN_ATTR = "domain";
/// <java-name>
/// MAX_AGE_ATTR
/// </java-name>
[Dot42.DexImport("MAX_AGE_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_AGE_ATTR = "max-age";
/// <java-name>
/// SECURE_ATTR
/// </java-name>
[Dot42.DexImport("SECURE_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string SECURE_ATTR = "secure";
/// <java-name>
/// COMMENT_ATTR
/// </java-name>
[Dot42.DexImport("COMMENT_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string COMMENT_ATTR = "comment";
/// <java-name>
/// EXPIRES_ATTR
/// </java-name>
[Dot42.DexImport("EXPIRES_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string EXPIRES_ATTR = "expires";
/// <java-name>
/// PORT_ATTR
/// </java-name>
[Dot42.DexImport("PORT_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string PORT_ATTR = "port";
/// <java-name>
/// COMMENTURL_ATTR
/// </java-name>
[Dot42.DexImport("COMMENTURL_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string COMMENTURL_ATTR = "commenturl";
/// <java-name>
/// DISCARD_ATTR
/// </java-name>
[Dot42.DexImport("DISCARD_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string DISCARD_ATTR = "discard";
}
/// <summary>
/// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/ClientCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537)]
public partial interface IClientCookie : global::Org.Apache.Http.Cookie.ICookie
/* scope: __dot42__ */
{
/// <java-name>
/// getAttribute
/// </java-name>
[Dot42.DexImport("getAttribute", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GetAttribute(string name) /* MethodBuilder.Create */ ;
/// <java-name>
/// containsAttribute
/// </java-name>
[Dot42.DexImport("containsAttribute", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool ContainsAttribute(string name) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals that a cookie is in some way invalid or illegal in a given context</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/MalformedCookieException
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/MalformedCookieException", AccessFlags = 33)]
public partial class MalformedCookieException : global::Org.Apache.Http.ProtocolException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new MalformedCookieException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public MalformedCookieException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new MalformedCookieException with a specified message string.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public MalformedCookieException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new MalformedCookieException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public MalformedCookieException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieOrigin
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieOrigin", AccessFlags = 49)]
public sealed partial class CookieOrigin
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;ILjava/lang/String;Z)V", AccessFlags = 1)]
public CookieOrigin(string host, int port, string path, bool secure) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getHost
/// </java-name>
[Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetHost() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPath
/// </java-name>
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetPath() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPort
/// </java-name>
[Dot42.DexImport("getPort", "()I", AccessFlags = 1)]
public int GetPort() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1)]
public bool IsSecure() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal CookieOrigin() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getHost
/// </java-name>
public string Host
{
[Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetHost(); }
}
/// <java-name>
/// getPath
/// </java-name>
public string Path
{
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPath(); }
}
/// <java-name>
/// getPort
/// </java-name>
public int Port
{
[Dot42.DexImport("getPort", "()I", AccessFlags = 1)]
get{ return GetPort(); }
}
}
/// <summary>
/// <para>This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the <code>Cookie</code> header such that those with more specific Path attributes precede those with less specific.</para><para>This comparator assumes that Path attributes of two cookies path-match a commmon request-URI. Otherwise, the result of the comparison is undefined. </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookiePathComparator
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookiePathComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" +
"okie/Cookie;>;")]
public partial class CookiePathComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie>
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookiePathComparator() /* MethodBuilder.Create */
{
}
/// <java-name>
/// compare
/// </java-name>
[Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)]
public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)]
public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>Cookie specification registry that can be used to obtain the corresponding cookie specification implementation for a given type of type or version of cookie.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpecRegistry
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpecRegistry", AccessFlags = 49)]
public sealed partial class CookieSpecRegistry
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookieSpecRegistry() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Registers a CookieSpecFactory with the given identifier. If a specification with the given name already exists it will be overridden. This nameis the same one used to retrieve the CookieSpecFactory from getCookieSpec(String).</para><para><para>#getCookieSpec(String) </para></para>
/// </summary>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;)V", AccessFlags = 33)]
public void Register(string name, global::Org.Apache.Http.Cookie.ICookieSpecFactory factory) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unregisters the CookieSpecFactory with the given ID.</para><para></para>
/// </summary>
/// <java-name>
/// unregister
/// </java-name>
[Dot42.DexImport("unregister", "(Ljava/lang/String;)V", AccessFlags = 33)]
public void Unregister(string id) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the cookie specification with the given ID.</para><para></para>
/// </summary>
/// <returns>
/// <para>cookie specification</para>
/// </returns>
/// <java-name>
/// getCookieSpec
/// </java-name>
[Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/Co" +
"okieSpec;", AccessFlags = 33)]
public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Cookie.ICookieSpec);
}
/// <summary>
/// <para>Gets the cookie specification with the given name.</para><para></para>
/// </summary>
/// <returns>
/// <para>cookie specification</para>
/// </returns>
/// <java-name>
/// getCookieSpec
/// </java-name>
[Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 33)]
public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Cookie.ICookieSpec);
}
/// <summary>
/// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para>
/// </summary>
/// <returns>
/// <para>list of registered cookie spec names </para>
/// </returns>
/// <java-name>
/// getSpecNames
/// </java-name>
[Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
public global::Java.Util.IList<string> GetSpecNames() /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<string>);
}
/// <summary>
/// <para>Populates the internal collection of registered cookie specs with the content of the map passed as a parameter.</para><para></para>
/// </summary>
/// <java-name>
/// setItems
/// </java-name>
[Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;>;)V")]
public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Cookie.ICookieSpecFactory> map) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para>
/// </summary>
/// <returns>
/// <para>list of registered cookie spec names </para>
/// </returns>
/// <java-name>
/// getSpecNames
/// </java-name>
public global::Java.Util.IList<string> SpecNames
{
[Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
get{ return GetSpecNames(); }
}
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpecFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpecFactory", AccessFlags = 1537)]
public partial interface ICookieSpecFactory
/* scope: __dot42__ */
{
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 1025)]
global::Org.Apache.Http.Cookie.ICookieSpec NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>This interface represents a <code>SetCookie2</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SetCookie2
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SetCookie2", AccessFlags = 1537)]
public partial interface ISetCookie2 : global::Org.Apache.Http.Cookie.ISetCookie
/* scope: __dot42__ */
{
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para>
/// </summary>
/// <java-name>
/// setCommentURL
/// </java-name>
[Dot42.DexImport("setCommentURL", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetCommentURL(string commentURL) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para>
/// </summary>
/// <java-name>
/// setPorts
/// </java-name>
[Dot42.DexImport("setPorts", "([I)V", AccessFlags = 1025)]
void SetPorts(int[] ports) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Set the Discard attribute.</para><para>Note: <code>Discard</code> attribute overrides <code>Max-age</code>.</para><para><para>isPersistent() </para></para>
/// </summary>
/// <java-name>
/// setDiscard
/// </java-name>
[Dot42.DexImport("setDiscard", "(Z)V", AccessFlags = 1025)]
void SetDiscard(bool discard) /* MethodBuilder.Create */ ;
}
}
| |
namespace Goldenacre.Extensions
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
public static class StringExtensions
{
private const string SingleSpace = " ";
private const string DoubleSpace = " ";
public static bool IsNullOrWhiteSpace(this string @this)
{
return string.IsNullOrWhiteSpace(@this);
}
// ReSharper disable once InconsistentNaming
public static bool EqualsAnyCS(this string @this, params string[] input)
{
return input.Any(s => s.Equals(@this, StringComparison.Ordinal));
}
// ReSharper disable once InconsistentNaming
public static bool EqualsAnyCS(this string @this, IEnumerable<string> input)
{
return input.Any(s => s.Equals(@this, StringComparison.Ordinal));
}
// ReSharper disable once InconsistentNaming
public static bool EqualsAnyCI(this string @this, params string[] input)
{
return input.Any(s => s.Equals(@this, StringComparison.OrdinalIgnoreCase));
}
// ReSharper disable once InconsistentNaming
public static bool EqualsCI(this string @this, IEnumerable<string> input)
{
return input.Any(s => s.Equals(@this, StringComparison.OrdinalIgnoreCase));
}
// ReSharper disable once InconsistentNaming
public static bool EqualsCI(this string @this, string value2)
{
return @this.Equals(value2, StringComparison.OrdinalIgnoreCase);
}
// ReSharper disable once InconsistentNaming
public static bool EqualsCS(this string @this, string value2)
{
return @this.Equals(value2, StringComparison.Ordinal);
}
public static bool ContainsAll(this string @this, params string[] values)
{
return values.All(one => @this.ToLowerInvariant().Contains(one.ToLowerInvariant()));
}
public static bool IsNumeric(this string @this)
{
if (!string.IsNullOrEmpty(@this))
{
decimal num;
return decimal.TryParse(@this, NumberStyles.Any, CultureInfo.CurrentCulture, out num);
}
return false;
}
public static bool IsDate(this string @this)
{
if (!string.IsNullOrEmpty(@this))
{
DateTime dt;
return DateTime.TryParse(@this, out dt);
}
return false;
}
public static bool IsGuid(this string @this)
{
if (@this == null)
{
throw new ArgumentNullException();
}
var format =
new Regex(
"^[A-Fa-f0-9]{32}$|" + "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
"^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$");
var match = format.Match(@this);
return match.Success;
}
public static string SubstringToIndexOf(this string @this, string value,
StringComparison comparison = StringComparison.CurrentCulture)
{
var idx = @this.IndexOf(value, comparison);
if (idx > 0)
{
return @this.Substring(0, idx);
}
if (idx == 0)
{
return string.Empty;
}
return @this;
}
/// <summary>
/// Parses a string into an Enum
/// </summary>
/// <typeparam name="T">The type of the Enum</typeparam>
/// <param name="this">String value to parse</param>
/// <returns>The Enum corresponding to the stringExtensions</returns>
public static T ToEnum<T>(this string @this)
{
return ToEnum<T>(@this, false);
}
/// <summary>
/// Parses a string into an Enum
/// </summary>
/// <typeparam name="T">The type of the Enum</typeparam>
/// <param name="this">String value to parse</param>
/// <param name="ignorecase">Ignore the case of the string being parsed</param>
/// <returns>The Enum corresponding to the stringExtensions</returns>
public static T ToEnum<T>(this string @this, bool ignorecase)
{
if (string.IsNullOrWhiteSpace(@this))
{
throw new ArgumentException(default(string), "@this");
}
@this = @this.Trim();
var t = typeof(T);
if (!t.IsEnum)
{
throw new ArgumentException(null);
}
return (T)Enum.Parse(t, @this, ignorecase);
}
public static int NthIndexOf(this string @this, string match, int occurrence)
{
var i = 1;
var index = 0;
while (i <= occurrence && (index =
@this.IndexOf(match, index + 1, StringComparison.InvariantCultureIgnoreCase)) != -1)
{
if (i == occurrence)
{
return index;
}
i++;
}
return -1;
}
public static string RemoveAllWhitespace(this string @this)
{
if (@this == null)
{
throw new ArgumentNullException(null, "@this");
}
@this = @this.Replace("\t", string.Empty);
while (@this.Contains(SingleSpace))
{
@this = @this.Replace(SingleSpace, string.Empty);
}
return @this;
}
public static string TrimAndRemoveConsecutiveWhitespace(this string @this)
{
if (@this == null)
{
throw new ArgumentNullException(null, "@this");
}
@this = @this.Replace("\t", SingleSpace).Trim();
while (@this.Contains(DoubleSpace))
{
@this = @this.Replace(DoubleSpace, SingleSpace);
}
return @this;
}
public static string SplitOnCapitals(string @this)
{
var result = new StringBuilder(@this.Length);
var countSinceLastSpace = 0;
for (var i = 0; i < @this.Length - 1; i++)
{
result.Append(@this[i]);
if (countSinceLastSpace > 2 && @this[i] != ' ' && @this[i] != '-' &&
(char.IsUpper(@this[i + 1]) || !char.IsDigit(@this[i]) && char.IsDigit(@this[i + 1])))
{
result.Append(' ');
countSinceLastSpace = 0;
}
countSinceLastSpace++;
}
result.Append(@this[@this.Length - 1]);
return result.ToString();
}
public static string ToTitleCase(this string @this)
{
var textInfo = CultureInfo.CurrentCulture.TextInfo;
return textInfo.ToTitleCase(@this);
}
/// <summary>
/// Converts the first letter of each word in a
/// space delimited sentence into uppercase
/// and converts all others into lowercase.
/// </summary>
/// <param name="this">The sentence to convert.</param>
/// <param name="ignore">A list of words to ignore. Useful for abbreviations etc.</param>
/// <returns>Pascal cased sentence.</returns>
public static string ToPascalCase(this string @this, params string[] ignore)
{
if (@this == null)
{
throw new ArgumentNullException();
}
var strReturn = string.Empty;
if (@this.Trim().Length > 0)
{
var objSb = new StringBuilder();
var leftSpace = new string(@this.TakeWhile(c => c == ' ').ToArray());
var rightSpace = new string(@this.Reverse().TakeWhile(c => c == ' ').ToArray());
var arrWords = @this.Trim().Split(new[] { ' ' }, StringSplitOptions.None);
foreach (var word in arrWords)
{
if (word != string.Empty && !ignore.Contains(word.ToAlphaNumeric()))
{
if (word.Length > 1 && word[0] == '\'' || word[0] == '"' || word[0] == '(' || word[0] == '[')
{
objSb.Append(char.ToUpperInvariant(word[0]));
objSb.Append(char.ToUpperInvariant(word[1]));
objSb.Append(word.Substring(2).ToLowerInvariant()); // Convert rest of word to LOWERCASE
}
else
{
objSb.Append(char.ToUpperInvariant(word[0])); // Convert 1st char to UPPERCASE
objSb.Append(word.Substring(1).ToLowerInvariant()); // Convert rest of word to LOWERCASE
}
objSb.Append(" ");
}
else
{
objSb.Append(word).Append(" ");
}
}
strReturn = leftSpace + objSb.ToString().Replace(" The ", " the ").Replace(" And ", " and ")
.Replace(" A ", " a ").Replace(" To ", " to ").Trim() + rightSpace;
}
return strReturn;
}
public static string ToAlphaNumeric(this string @this)
{
return new string(@this.Where(char.IsLetterOrDigit).ToArray());
}
/// <summary>
/// Encodes the specified string to a HEX encoded MD5Hash.
/// </summary>
/// <param name="this">The string to encode.</param>
/// <returns>The encoded string.</returns>
public static string ToHexMd5Hash(this string @this)
{
if (@this == null)
{
throw new ArgumentNullException();
}
var md5Hasher = new MD5CryptoServiceProvider();
var hashedDataBytes = md5Hasher.ComputeHash(Encoding.Default.GetBytes(@this));
// step 2, convert byte array to hex string
var sb = new StringBuilder();
foreach (var t in hashedDataBytes)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Encodes the specified string to a Base64 encoded MD5Hash.
/// </summary>
/// <param name="this">The string to encode.</param>
/// <returns>The encoded string.</returns>
public static string ToBase64Md5Hash(this string @this)
{
if (@this == null)
{
throw new ArgumentNullException(null, "@this");
}
var md5Hasher = new MD5CryptoServiceProvider();
var hashedDataBytes = md5Hasher.ComputeHash(Encoding.Default.GetBytes(@this));
return Convert.ToBase64String(hashedDataBytes);
}
public static string ToAspNetPasswordHash(string @this)
{
if (@this == null)
{
throw new ArgumentNullException(null, "@this");
}
byte[] salt;
byte[] bytes;
using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(@this, 16, 1000))
{
salt = rfc2898DeriveBytes.Salt;
bytes = rfc2898DeriveBytes.GetBytes(32);
}
var inArray = new byte[49];
Buffer.BlockCopy(salt, 0, inArray, 1, 16);
Buffer.BlockCopy(bytes, 0, inArray, 17, 32);
return Convert.ToBase64String(inArray);
}
public static string Truncate(this string @this, int maxLength, bool appendEllipsis)
{
if (@this == null)
{
throw new ArgumentNullException(null, "@this");
}
if (appendEllipsis)
{
maxLength = Math.Max(0, maxLength - 3);
return string.Concat(@this.Substring(0, maxLength), "...");
}
return @this.Substring(0, maxLength);
}
public static byte[] ToByteArray(this string @this)
{
if (@this == null)
{
throw new ArgumentNullException(null, "@this");
}
return @this.Select(Convert.ToByte).ToArray();
}
}
}
| |
namespace TypeVisualiser.Model
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using StructureMap;
using TypeVisualiser.ILAnalyser;
using TypeVisualiser.Model.Persistence;
using TypeVisualiser.Properties;
public class VisualisableTypeWithAssociations : VisualisableType, IVisualisableTypeWithAssociations
{
private const int DepthLimit = 2;
/// <summary>
/// A temporary cache for storing unrefined data during consumption discovery.
/// Tuple.Item1 = used by method name, Item2 = the type associated to
/// </summary>
private readonly List<Tuple<string, Type>> allConsumptionUsage = new List<Tuple<string, Type>>();
/// <summary>
/// A temporary cache for storing unrefined data during consumption discovery.
/// Tuple.Item1 = used by method name, Item2 = the type associated to
/// </summary>
private readonly List<Tuple<string, Type>> allStaticUsage = new List<Tuple<string, Type>>();
private readonly object associationsSyncRoot = new object();
private List<FieldAssociation> associations = new List<FieldAssociation>();
/// <summary>
/// Depth of the diagram, the number of hops to the main subject of the diagram. Used to prevent walking the entire dot net framework.
/// </summary>
private int depth;
private Func<ITrivialFilter> getTrivialFilter;
private AssociationLoadStatus loadStatus = AssociationLoadStatus.ConstructedOnly;
public VisualisableTypeWithAssociations(Type type)
: this(type, 0)
{
}
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Reviewed, ok here")]
public VisualisableTypeWithAssociations(Type type, int depth)
: base(type, new VisualisableTypeSubjectData(), depth == 0 ? SubjectOrAssociate.Subject : SubjectOrAssociate.Associate)
{
this.ConstructorSharedLogic(type, depth);
}
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Reviewed, ok here")]
public VisualisableTypeWithAssociations(Type type, int depth, IContainer factory)
: base(factory, type, new VisualisableTypeSubjectData(), depth == 0 ? SubjectOrAssociate.Subject : SubjectOrAssociate.Associate)
{
this.ConstructorSharedLogic(type, depth);
}
/// <summary>
/// Gets all associations. This is an unfiltered list of all associations. It does not take into account the
/// <see cref="TrivialFilter"/>. IT ALSO DOES NOT INCLUDE THE SUPERCLASS OR INTERFACES.
/// </summary>
/// <value>All associations.</value>
public IEnumerable<FieldAssociation> AllAssociations
{
get
{
return this.associations;
}
}
/// <summary>
/// Gets the consumes associations. This is a subset of <see cref="FilteredAssociations"/>.
/// This collection takes into account the <see cref="TrivialFilter"/>.
/// This collection includes the sub-classes of <see cref="ConsumeAssociation"/>, such as
/// <see cref="StaticAssociation"/>.
/// </summary>
/// <value>The consume associations.</value>
public IEnumerable<ConsumeAssociation> Consumes
{
get
{
ITrivialFilter trivialFilter = this.getTrivialFilter();
if (trivialFilter.HideTrivialTypes)
{
return this.associations.OfType<ConsumeAssociation>().Where(x => !trivialFilter.IsTrivialType(x.AssociatedTo.NamespaceQualifiedName));
}
return this.associations.OfType<ConsumeAssociation>();
}
}
/// <summary>
/// Gets just the field associations. This is a subset of <see cref="FilteredAssociations"/>.
/// This collection takes into account the <see cref="TrivialFilter"/>.
/// This collection does NOT include the sub-classes of <see cref="FieldAssociation"/>.
/// </summary>
/// <value>The field associations.</value>
public IEnumerable<FieldAssociation> Fields
{
get
{
ITrivialFilter trivialFilter = this.getTrivialFilter();
if (trivialFilter.HideTrivialTypes)
{
return this.associations.Where(x => x.GetType() == typeof(FieldAssociation) && !trivialFilter.IsTrivialType(x.AssociatedTo.NamespaceQualifiedName));
}
return this.associations.Where(x => x.GetType() == typeof(FieldAssociation));
}
}
/// <summary>
/// Gets all associations while taking into account the <see cref="TrivialFilter"/>.
/// This collection includes the sub-classes of <see cref="FieldAssociation"/>, such as
/// <see cref="ConsumeAssociation"/> and others.
/// </summary>
/// <value>All associations.</value>
public IEnumerable<FieldAssociation> FilteredAssociations
{
get
{
ITrivialFilter trivialFilter = this.getTrivialFilter();
if (trivialFilter.HideTrivialTypes)
{
return this.associations.Where(x => !trivialFilter.IsTrivialType(x.AssociatedTo.NamespaceQualifiedName));
}
return this.associations;
}
}
/// <summary>
/// Gets the number of nontrivial dependencies. This is the number of associations that are
/// classified as non-trivial by the <see cref="TrivialFilter"/> and associates that are interfaces
/// enumerations or value types.
/// </summary>
/// <value>The nontrivial dependencies.</value>
public int NontrivialDependencies
{
get
{
IEnumerable<FieldAssociation> nontrivialDependencies = this.associations.Where(x => !x.IsTrivialAssociation());
return nontrivialDependencies.Count() + (this.Parent == null ? 0 : this.Parent.IsTrivialAssociation() ? 0 : 1);
}
}
/// <summary>
/// Gets the parent of this subject.
/// </summary>
/// <value>The parent.</value>
public ParentAssociation Parent { get; private set; }
/// <summary>
/// Gets all the interfaces this subject implements. This list is not affected by
/// the <see cref="TrivialFilter"/>.
/// </summary>
/// <value>The interfaces this subject implements.</value>
public IEnumerable<ParentAssociation> ThisTypeImplements { get; private set; }
/// <summary>
/// Gets the number of nontrivial dependencies. This is the number of associations that are
/// classified as trivial by the <see cref="TrivialFilter"/> and associates that are interfaces
/// enumerations or value types.
/// </summary>
/// <value>The nontrivial dependencies.</value>
public int TrivialDependencies
{
get
{
IEnumerable<FieldAssociation> result = this.associations.Where(x => x.IsTrivialAssociation());
return result.Count() + this.ThisTypeImplements.Count() + (this.Parent == null ? 0 : this.Parent.IsTrivialAssociation() ? 1 : 0);
}
}
/// <summary>
/// Discovers the relationships between associations. This is an interim step to find only associations that are not already modeled.
/// This should only be called on the main subject of the diagram. Call this for multiple types will result in unnecessary duplicated processing.
/// For example: Subject will be excluded and its associations also.
/// </summary>
public void DiscoverSecondaryAssociationsInModel()
{
// Now examine all assoications and see if any of them relate to each other. (Up to this point only relationships back to this subject have been created).
List<IVisualisableType> allAssociations =
this.associations.Cast<Association>().Union(this.ThisTypeImplements).Union(new[] { this.Parent }).Where(x => x != null).Select(x => x.AssociatedTo).ToList();
foreach (IVisualisableType visualisableType in allAssociations.ToList())
{
var fullyExpandedTypeModel = visualisableType as VisualisableTypeWithAssociations;
if (fullyExpandedTypeModel == null)
{
throw new InvalidOperationException("Code Error: Must be of type Visualisable Type Subject");
}
// Discover relationships from current loop variable to others fields
IEnumerable<FieldInfo> fields = this.GetAllFieldsInThisType(fullyExpandedTypeModel.NetType);
// Resulting list should exclude the main subject, its associations have already been drawn.
IVisualisableType copyOfVisualisableType = visualisableType;
// Not equal to current loop variable
IEnumerable<FieldInfo> includeTheseFields = fields.Where(f => new TypeDescriptorHelper(f.FieldType).GenerateId() != copyOfVisualisableType.Id).Join(
allAssociations, fieldInfo => new TypeDescriptorHelper(fieldInfo.FieldType).GenerateId(), association => association.Id, (fieldInfo, association) => fieldInfo);
// Do I have the associated field on my diagram already? If so include otherwise omit.
fullyExpandedTypeModel.AddToAssociationsCollection(this.InitialiseFieldAssociations(includeTheseFields));
}
}
public override VisualisableTypeData ExtractPersistentData()
{
return new VisualisableTypeWithAssociationsDataAdaptor(this.AllAssociations, this.ThisTypeImplements, this.Parent, this.PersistentDataField).Adapt();
}
/// <summary>
/// This method is called when an instance is reused from the cache.
/// </summary>
/// <param name="newDepth">
/// The new Depth.
/// </param>
public void InitialiseForReuseFromCache(int newDepth)
{
if (newDepth > 0)
{
return;
}
this.depth = 0;
if (this.loadStatus == AssociationLoadStatus.FullyLoaded)
{
return;
}
this.Initialise(this.NetType);
}
/// <summary>
/// This virtual is to allow isolation of the parent relationship.
/// </summary>
/// <param name="mainSubjectType">
/// The main Subject Type.
/// </param>
protected virtual void InitialiseParentTypeRelationship(Type mainSubjectType)
{
if (mainSubjectType == null)
{
throw new ArgumentNullResourceException(Resources.General_Given_Parameter_Cannot_Be_Null, "mainSubjectType");
}
if (mainSubjectType.BaseType != null && mainSubjectType.BaseType != typeof(object))
{
this.Parent = this.Factory.GetInstance<ParentAssociation>().Initialise(mainSubjectType.BaseType, this);
}
}
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Validated in base")]
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Justification = "Validated in base")]
protected override void SetConsumes(MethodBase method, IMethodBodyReader reader)
{
base.SetConsumes(method, reader);
foreach (ILInstruction instruction in reader.Instructions.Where(i => i.Operand != null))
{
var externalMethodCall = instruction.Operand as MethodBase;
if (externalMethodCall != null)
{
Type declaringType = externalMethodCall.DeclaringType;
if ((externalMethodCall.Attributes & MethodAttributes.Static) == MethodAttributes.Static)
{
// Statics discovered elsewhere
continue;
}
if (method.DeclaringType != null)
{
if (method.IsConstructor && (declaringType == method.DeclaringType || declaringType == method.DeclaringType.BaseType))
{
// Calling another constructor in same class.
continue;
}
}
if (declaringType == null || TypeDescriptorHelper.AreEqual(declaringType, this.Id))
{
// Don't bother counting "self-consumption" calls.
continue;
}
this.allConsumptionUsage.Add(new Tuple<string, Type>(method.Name, declaringType));
}
}
}
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Justification = "Validated in base")]
protected override void SetStaticAssociations(MethodBase consumedStatics, IMethodBodyReader reader)
{
base.SetStaticAssociations(consumedStatics, reader);
IQueryable<Tuple<string, Type>> statics = from staticMethod in reader.Instructions.Select(instruction => instruction.Operand).OfType<MethodInfo>()
where (staticMethod.Attributes & MethodAttributes.Static) == MethodAttributes.Static
select new Tuple<string, Type>(consumedStatics.Name, staticMethod.DeclaringType);
this.allStaticUsage.AddRange(statics);
}
private static void MergeConsumeCollectionIntoAssociations(List<FieldAssociation> existingAssociations, IEnumerable<FieldAssociation> consumeCollection)
{
List<FieldAssociation> consumeList = consumeCollection.ToList();
// Find intersection between consumes collection and associations. What do we already have in the main association collection.
FieldAssociation[] overlapCollection = existingAssociations.Join(consumeList, a => a.AssociatedTo.AssemblyQualifiedName, c => c.AssociatedTo.AssemblyQualifiedName, (a, c) => c).ToArray();
IEnumerable<string> duplicates = existingAssociations.GroupBy(i => i.AssociatedTo.AssemblyQualifiedName).Where(g => g.Count() > 1).Select(g => g.Key);
if (duplicates.Any())
{
throw new DuplicateNameException("Code bug: Association list contains duplicates.");
}
// Remove consumes relationship if also is a strong association already.
foreach (FieldAssociation associationAndConsumerOf in overlapCollection)
{
consumeList.Remove(associationAndConsumerOf);
FieldAssociation trumpAssociation = existingAssociations.Single(x => x.AssociatedTo.AssemblyQualifiedName == associationAndConsumerOf.AssociatedTo.AssemblyQualifiedName);
if (trumpAssociation != null)
{
trumpAssociation.Merge(associationAndConsumerOf);
}
}
List<FieldAssociation> exceptList = consumeList.Except(overlapCollection).ToList();
existingAssociations.AddRange(exceptList);
}
/// <summary>
/// Adding to the associations collection must be done using this method. There are two sources to add to the associations, <see cref="Initialise"/>
/// and <see cref="DiscoverSecondaryAssociationsInModel"/>.
/// </summary>
/// <param name="fields">
/// The fields to be added to the <see cref="associations"/> collection.
/// </param>
private void AddToAssociationsCollection(IEnumerable<FieldAssociation> fields)
{
lock (this.associationsSyncRoot)
{
IEnumerable<FieldAssociation> duplicateFiltered = this.DuplicateCheck(fields.ToList());
this.associations.AddRange(duplicateFiltered);
}
}
private void AggregateRawConsumeCollection(
IList<ConsumeAssociation> rawConsumeList, Func<Type, int, IEnumerable<AssociationUsageDescriptor>, ConsumeAssociation> ctor, IList<Tuple<string, Type>> allUsageList)
{
var usageGroup = new Tuple<string, Type>(null, null);
var callerMethodList = new List<AssociationUsageDescriptor>();
int count = 0;
if (allUsageList.Any(x => x.Item2 == null))
{
// todo sometimes getting null ref here on x.Item2 == null
// I suspect these might be win32 C++ types that do not have a correspnding type. These need to be specially dealt with.
// Debugger.Break();
allUsageList = allUsageList.Where(x => x.Item2 != null).ToList();
}
foreach (var usage in allUsageList.OrderBy(x => x.Item2.FullName))
{
if (new TypeDescriptorHelper(usage.Item2).GenerateId() == this.Id)
{
// filter out associations to itself.
continue;
}
if (usageGroup.Item2 != usage.Item2)
{
if (usageGroup.Item2 != null)
{
rawConsumeList.Add(ctor(usageGroup.Item2, count, callerMethodList));
}
usageGroup = usage;
count = 0;
callerMethodList = new List<AssociationUsageDescriptor>();
}
count++;
callerMethodList.Add(AssociationUsageDescriptor.CreateMethodUsage(usage.Item1));
}
if (callerMethodList.Any())
{
rawConsumeList.Add(ctor(usageGroup.Item2, count, callerMethodList));
}
}
private void ConstructorSharedLogic(Type type, int depthFromSubject)
{
this.getTrivialFilter = this.GetTrivialFilterImplementation;
this.depth = depthFromSubject;
this.ThisTypeImplements = new List<ParentAssociation>();
if (this.LinesOfCodeTask != null)
{
if (this.LinesOfCodeTask.IsCompleted)
{
this.Initialise(type);
}
else
{
this.LinesOfCodeTask.ContinueWith(t => this.Initialise(type));
}
}
else
{
this.Initialise(type);
}
}
private IEnumerable<FieldAssociation> DuplicateCheck(IList<FieldAssociation> addRange)
{
if (!addRange.Any() || !this.associations.Any())
{
return addRange;
}
IEnumerable<FieldAssociation> d = addRange.Except(this.associations.Intersect(addRange));
return d;
}
private IEnumerable<FieldInfo> GetAllFieldsInThisType(Type type)
{
if (type == null)
{
throw new InvalidOperationException("Code Error: type should never be null here.");
}
IOrderedEnumerable<FieldInfo> allFields = from field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
where !TypeDescriptorHelper.AreEqual(field.FieldType, this.Id)
// Do not want to include "this" type in list
orderby field.FieldType.FullName
select field;
return allFields;
}
private ITrivialFilter GetTrivialFilterImplementation()
{
return this.Factory.TryGetInstance<ITrivialFilter>();
}
private void Initialise(Type type)
{
if (this.loadStatus == AssociationLoadStatus.FullyLoaded)
{
return;
}
if (this.depth >= DepthLimit)
{
this.loadStatus = AssociationLoadStatus.NotLoaded;
return;
}
this.loadStatus = AssociationLoadStatus.FullyLoaded;
this.InitialiseParentTypeRelationship(type);
IEnumerable<FieldAssociation> fields = this.InitialiseFieldAssociations(this.GetAllFieldsInThisType(type));
this.AddToAssociationsCollection(fields);
// Consumes
this.InitialiseConsumesCollection();
// Implements
List<Type> allInterfaces = type.GetInterfaces().ToList();
if (type.BaseType != null && type.BaseType != typeof(object))
{
allInterfaces.Add(type.BaseType);
}
IEnumerable<Type> interfaces = allInterfaces.Except(allInterfaces.SelectMany(t => t.GetInterfaces())).Where(t => t.IsInterface);
this.ThisTypeImplements = interfaces.Select(i => this.Factory.GetInstance<ParentAssociation>().Initialise(i, this));
// Put all associations excluding parents into a list.
this.associations = this.associations.OrderBy(x => x.AssociatedTo.Name).ToList();
}
private void InitialiseConsumesCollection()
{
// Field Consumes
var rawConsumeList = new List<ConsumeAssociation>();
var ctor = new Func<Type, int, IEnumerable<AssociationUsageDescriptor>, ConsumeAssociation>((t, i, l) => this.Factory.GetInstance<ConsumeAssociation>().Initialise(t, i, l, this.depth + 1));
this.AggregateRawConsumeCollection(rawConsumeList, ctor, this.allConsumptionUsage);
MergeConsumeCollectionIntoAssociations(this.associations, rawConsumeList);
// Static Consumes
rawConsumeList.Clear();
ctor = (t, i, l) => this.Factory.GetInstance<StaticAssociation>().Initialise(t, i, l, this.depth + 1);
this.AggregateRawConsumeCollection(rawConsumeList, ctor, this.allStaticUsage);
MergeConsumeCollectionIntoAssociations(this.associations, rawConsumeList);
}
private IEnumerable<FieldAssociation> InitialiseFieldAssociations(IEnumerable<FieldInfo> fields)
{
int fieldUsageCount = 0;
Type groupType = null;
var fieldNameList = new List<AssociationUsageDescriptor>();
var fieldAssociations = new List<FieldAssociation>();
foreach (FieldInfo field in fields)
{
if (groupType == field.FieldType)
{
fieldUsageCount++;
fieldNameList.Add(AssociationUsageDescriptor.CreateFieldUsage(field.Name));
}
else
{
if (fieldUsageCount > 0)
{
fieldAssociations.Add(this.Factory.GetInstance<FieldAssociation>().Initialise(groupType, fieldUsageCount, fieldNameList, this.depth + 1));
}
fieldUsageCount = 1;
fieldNameList = new List<AssociationUsageDescriptor> { AssociationUsageDescriptor.CreateFieldUsage(field.Name) };
groupType = field.FieldType;
}
}
if (fieldUsageCount > 0)
{
fieldAssociations.Add(this.Factory.GetInstance<FieldAssociation>().Initialise(groupType, fieldUsageCount, fieldNameList, this.depth + 1));
}
return fieldAssociations;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
using Content = Umbraco.Core.Models.Content;
namespace Umbraco.Tests.Persistence.Repositories
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture]
public class PublicAccessRepositoryTest : BaseDatabaseFactoryTest
{
[Test]
public void Can_Delete()
{
var content = CreateTestData(3).ToArray();
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
{
var entry = new PublicAccessEntry(content[0], content[1], content[2], new[]
{
new PublicAccessRule
{
RuleValue = "test",
RuleType = "RoleName"
},
});
repo.AddOrUpdate(entry);
unitOfWork.Commit();
repo.Delete(entry);
unitOfWork.Commit();
entry = repo.Get(entry.Key);
Assert.IsNull(entry);
}
}
[Test]
public void Can_Add()
{
var content = CreateTestData(3).ToArray();
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
{
var entry = new PublicAccessEntry(content[0], content[1], content[2], new[]
{
new PublicAccessRule
{
RuleValue = "test",
RuleType = "RoleName"
},
});
repo.AddOrUpdate(entry);
unitOfWork.Commit();
var found = repo.GetAll().ToArray();
Assert.AreEqual(1, found.Count());
Assert.AreEqual(content[0].Id, found[0].ProtectedNodeId);
Assert.AreEqual(content[1].Id, found[0].LoginNodeId);
Assert.AreEqual(content[2].Id, found[0].NoAccessNodeId);
Assert.IsTrue(found[0].HasIdentity);
Assert.AreNotEqual(default(DateTime), found[0].CreateDate);
Assert.AreNotEqual(default(DateTime), found[0].UpdateDate);
Assert.AreEqual(1, found[0].Rules.Count());
Assert.AreEqual("test", found[0].Rules.First().RuleValue);
Assert.AreEqual("RoleName", found[0].Rules.First().RuleType);
Assert.AreNotEqual(default(DateTime), found[0].Rules.First().CreateDate);
Assert.AreNotEqual(default(DateTime), found[0].Rules.First().UpdateDate);
Assert.IsTrue(found[0].Rules.First().HasIdentity);
}
}
[Test]
public void Can_Update()
{
var content = CreateTestData(3).ToArray();
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
{
var entry = new PublicAccessEntry(content[0], content[1], content[2], new[]
{
new PublicAccessRule
{
RuleValue = "test",
RuleType = "RoleName"
},
});
repo.AddOrUpdate(entry);
unitOfWork.Commit();
//re-get
entry = repo.Get(entry.Key);
entry.Rules.First().RuleValue = "blah";
entry.Rules.First().RuleType = "asdf";
repo.AddOrUpdate(entry);
unitOfWork.Commit();
//re-get
entry = repo.Get(entry.Key);
Assert.AreEqual("blah", entry.Rules.First().RuleValue);
Assert.AreEqual("asdf", entry.Rules.First().RuleType);
}
}
[Test]
public void Get_By_Id()
{
var content = CreateTestData(3).ToArray();
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
{
var entry = new PublicAccessEntry(content[0], content[1], content[2], new[]
{
new PublicAccessRule
{
RuleValue = "test",
RuleType = "RoleName"
},
});
repo.AddOrUpdate(entry);
unitOfWork.Commit();
//re-get
entry = repo.Get(entry.Key);
Assert.IsNotNull(entry);
}
}
[Test]
public void Get_All()
{
var content = CreateTestData(3).ToArray();
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
{
var entry1 = new PublicAccessEntry(content[0], content[1], content[2], new[]
{
new PublicAccessRule
{
RuleValue = "test",
RuleType = "RoleName"
},
});
repo.AddOrUpdate(entry1);
var entry2 = new PublicAccessEntry(content[1], content[0], content[2], new[]
{
new PublicAccessRule
{
RuleValue = "test",
RuleType = "RoleName"
},
});
repo.AddOrUpdate(entry2);
unitOfWork.Commit();
var found = repo.GetAll().ToArray();
Assert.AreEqual(2, found.Count());
}
}
[Test]
public void Get_All_With_Id()
{
var content = CreateTestData(3).ToArray();
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax))
{
var entry1 = new PublicAccessEntry(content[0], content[1], content[2], new[]
{
new PublicAccessRule
{
RuleValue = "test",
RuleType = "RoleName"
},
});
repo.AddOrUpdate(entry1);
var entry2 = new PublicAccessEntry(content[1], content[0], content[2], new[]
{
new PublicAccessRule
{
RuleValue = "test",
RuleType = "RoleName"
},
});
repo.AddOrUpdate(entry2);
unitOfWork.Commit();
var found = repo.GetAll(entry1.Key).ToArray();
Assert.AreEqual(1, found.Count());
}
}
private ContentRepository CreateRepository(IDatabaseUnitOfWork unitOfWork, out ContentTypeRepository contentTypeRepository)
{
var templateRepository = new TemplateRepository(unitOfWork, CacheHelper, Logger, SqlSyntax, Mock.Of<IFileSystem>(), Mock.Of<IFileSystem>(), Mock.Of<ITemplatesSection>());
var tagRepository = new TagRepository(unitOfWork, CacheHelper, Logger, SqlSyntax);
contentTypeRepository = new ContentTypeRepository(unitOfWork, CacheHelper, Logger, SqlSyntax, templateRepository);
var repository = new ContentRepository(unitOfWork, CacheHelper, Logger, SqlSyntax, contentTypeRepository, templateRepository, tagRepository);
return repository;
}
private IEnumerable<IContent> CreateTestData(int count)
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentTypeRepository ctRepo;
using (var repo = CreateRepository(unitOfWork, out ctRepo))
{
var ct = MockedContentTypes.CreateBasicContentType("testing");
ctRepo.AddOrUpdate(ct);
unitOfWork.Commit();
var result = new List<IContent>();
for (int i = 0; i < count; i++)
{
var c = new Content("test" + i, -1, ct);
repo.AddOrUpdate(c);
result.Add(c);
}
unitOfWork.Commit();
return result;
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Intellisense;
namespace Microsoft.PythonTools.Interpreter.Default {
class CPythonModule : IPythonModule, IProjectEntry, ILocatedMember {
private readonly string _modName;
private readonly string _dbFile;
private readonly ITypeDatabaseReader _typeDb;
private readonly bool _isBuiltin;
internal readonly Dictionary<string, IMember> _members = new Dictionary<string, IMember>();
private Dictionary<object, object> _properties;
internal Dictionary<string, IMember> _hiddenMembers;
private string _docString, _filename;
private List<object> _children;
private enum LoadState {
NotLoaded,
Loading,
Loaded
}
private LoadState _loadState;
public CPythonModule(ITypeDatabaseReader typeDb, string moduleName, string databaseFilename, bool isBuiltin) {
_modName = moduleName;
_dbFile = databaseFilename;
_typeDb = typeDb;
_isBuiltin = isBuiltin;
}
internal void EnsureLoaded() {
// If we're fully loaded, just return.
if (_loadState == LoadState.Loaded) {
return;
}
// If we're loading or not loaded, we need to take this lock.
if (!_typeDb.BeginModuleLoad(this, 10000)) {
Debug.Fail(string.Format("Timeout loading {0}", _modName));
//throw new InvalidOperationException("Cannot load module at this time");
return;
}
try {
// Ensure we haven't started/finished loading while waiting
if (_loadState != LoadState.NotLoaded) {
return;
}
// Mark as loading now (before it completes), if we have circular
// references we'll fix them up after loading
// completes.
_loadState = LoadState.Loading;
// Will be set to true if we should delete this file and then
// trigger a corruption notification.
bool deleteFile = false;
using (var stream = new FileStream(_dbFile, FileMode.Open, FileAccess.Read, FileShare.Read)) {
Dictionary<string, object> contents = null;
try {
contents = (Dictionary<string, object>)Unpickle.Load(stream);
} catch (ArgumentException) {
_typeDb.OnDatabaseCorrupt();
} catch (InvalidOperationException) {
// Bug 511 - http://pytools.codeplex.com/workitem/511
// Ignore a corrupt database file.
_typeDb.OnDatabaseCorrupt();
}
if (contents != null) {
object obj;
string filename;
if (contents.TryGetValue("filename", out obj)) {
filename = obj as string;
if (!string.IsNullOrEmpty(filename) && !File.Exists(filename)) {
// Issue 2358 - must refresh DB after it moves
// on disk.
deleteFile = true;
}
}
LoadModule(contents);
}
}
if (deleteFile) {
// Only notify if we actually remove the file
try {
File.Delete(_dbFile);
_typeDb.OnDatabaseCorrupt();
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
}
} catch (FileNotFoundException) {
// if the file got deleted before we've loaded it don't crash...
} catch (IOException) {
// or if someone has locked the file for some reason, also don't crash...
} finally {
// Regardless of how we finish, mark us as loaded so we don't
// try again.
_loadState = LoadState.Loaded;
_typeDb.EndModuleLoad(this);
}
}
private void LoadModule(Dictionary<string, object> data) {
object membersValue;
if (data.TryGetValue("members", out membersValue)) {
var dataVal = (Dictionary<string, object>)membersValue;
if (dataVal != null) {
LoadMembers(dataVal);
}
}
object doc;
if (data.TryGetValue("doc", out doc)) {
_docString = doc as string;
}
object filename;
if (data.TryGetValue("filename", out filename)) {
_filename = filename as string;
}
object children;
if (data.TryGetValue("children", out children)) {
_children = children as List<object>;
if (_children == null) {
var asArray = children as object[];
if (asArray != null) {
_children = new List<object>(asArray);
}
}
}
}
private void LoadMembers(Dictionary<string, object> membersTable) {
foreach (var dataInfo in membersTable) {
var memberName = dataInfo.Key;
var memberTable = (Dictionary<string, object>)dataInfo.Value;
if (memberTable != null) {
_typeDb.ReadMember(memberName, memberTable, StoreMember, this);
}
}
}
private void StoreMember(string memberName, IMember value) {
CPythonType type = value as CPythonType;
if (type != null && !type.IncludeInModule) {
if (_hiddenMembers == null) {
_hiddenMembers = new Dictionary<string, IMember>();
}
_hiddenMembers[memberName] = type;
} else {
lock (_members) {
_members[memberName] = value;
}
}
}
internal ITypeDatabaseReader TypeDb {
get {
return _typeDb;
}
}
#region IPythonModule Members
public IEnumerable<string> GetChildrenModules() {
if (_children != null) {
foreach (var child in _children) {
yield return (string)child;
}
}
}
public string Name {
get { return _modName; }
}
public void Imported(IModuleContext context) {
EnsureLoaded();
}
public string Documentation {
get { return _docString; }
}
#endregion
#region IMemberContainer Members
public IMember GetMember(IModuleContext context, string name) {
if (_loadState != LoadState.Loaded) {
// avoid deserializing all of the member list if we're just checking if
// a member exists.
lock (_members) {
if (_members.Count > 0 || File.Exists(_dbFile + ".$memlist")) {
if (_members.Count == 0) {
// populate members dict w/ list of members
foreach (var line in File.ReadLines(_dbFile + ".$memlist")) {
_members[line] = null;
}
}
if (!_members.ContainsKey(name)) {
// the member doesn't exist, no need to load all of the data
return null;
}
}
}
// the member exists, or we don't have a $memlist file, read everything.
EnsureLoaded();
}
Debug.Assert(_loadState == LoadState.Loaded);
IMember res;
lock (_members) {
if (_members.TryGetValue(name, out res)) {
return res;
}
}
return null;
}
public IEnumerable<string> GetMemberNames(IModuleContext moduleContext) {
EnsureLoaded();
Debug.Assert(_loadState == LoadState.Loaded);
lock (_members) {
return _members.Keys.ToList();
}
}
#endregion
#region IMember Members
public PythonMemberType MemberType {
get { return PythonMemberType.Module; }
}
#endregion
#region IProjectEntry Members
public bool IsAnalyzed {
get { return true; }
}
public int AnalysisVersion {
get { return 1; }
}
public string FilePath {
get {
EnsureLoaded();
Debug.Assert(_loadState == LoadState.Loaded);
return _filename;
}
}
public Dictionary<object, object> Properties {
get {
if (_properties == null) {
Interlocked.CompareExchange(ref _properties, new Dictionary<object, object>(), null);
}
return _properties;
}
}
public IModuleContext AnalysisContext {
get { return null; }
}
public void RemovedFromProject() { }
#endregion
#region IAnalyzable Members
public void Analyze(CancellationToken cancel) {
}
#endregion
#region ILocatedMember Members
public IEnumerable<LocationInfo> Locations {
get {
EnsureLoaded();
Debug.Assert(_loadState == LoadState.Loaded);
yield return new LocationInfo(FilePath, 1, 1);
}
}
#endregion
internal static CPythonModule GetDeclaringModuleFromContainer(IMemberContainer declaringType) {
return (declaringType as CPythonModule) ?? (CPythonModule)((CPythonType)declaringType).DeclaringModule;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ConversationThreadRequest.
/// </summary>
public partial class ConversationThreadRequest : BaseRequest, IConversationThreadRequest
{
/// <summary>
/// Constructs a new ConversationThreadRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public ConversationThreadRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified ConversationThread using POST.
/// </summary>
/// <param name="conversationThreadToCreate">The ConversationThread to create.</param>
/// <returns>The created ConversationThread.</returns>
public System.Threading.Tasks.Task<ConversationThread> CreateAsync(ConversationThread conversationThreadToCreate)
{
return this.CreateAsync(conversationThreadToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified ConversationThread using POST.
/// </summary>
/// <param name="conversationThreadToCreate">The ConversationThread to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ConversationThread.</returns>
public async System.Threading.Tasks.Task<ConversationThread> CreateAsync(ConversationThread conversationThreadToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<ConversationThread>(conversationThreadToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified ConversationThread.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified ConversationThread.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<ConversationThread>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified ConversationThread.
/// </summary>
/// <returns>The ConversationThread.</returns>
public System.Threading.Tasks.Task<ConversationThread> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified ConversationThread.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The ConversationThread.</returns>
public async System.Threading.Tasks.Task<ConversationThread> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<ConversationThread>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified ConversationThread using PATCH.
/// </summary>
/// <param name="conversationThreadToUpdate">The ConversationThread to update.</param>
/// <returns>The updated ConversationThread.</returns>
public System.Threading.Tasks.Task<ConversationThread> UpdateAsync(ConversationThread conversationThreadToUpdate)
{
return this.UpdateAsync(conversationThreadToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified ConversationThread using PATCH.
/// </summary>
/// <param name="conversationThreadToUpdate">The ConversationThread to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated ConversationThread.</returns>
public async System.Threading.Tasks.Task<ConversationThread> UpdateAsync(ConversationThread conversationThreadToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<ConversationThread>(conversationThreadToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadRequest Expand(Expression<Func<ConversationThread, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IConversationThreadRequest Select(Expression<Func<ConversationThread, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="conversationThreadToInitialize">The <see cref="ConversationThread"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(ConversationThread conversationThreadToInitialize)
{
if (conversationThreadToInitialize != null && conversationThreadToInitialize.AdditionalData != null)
{
if (conversationThreadToInitialize.Posts != null && conversationThreadToInitialize.Posts.CurrentPage != null)
{
conversationThreadToInitialize.Posts.AdditionalData = conversationThreadToInitialize.AdditionalData;
object nextPageLink;
conversationThreadToInitialize.AdditionalData.TryGetValue("posts@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
conversationThreadToInitialize.Posts.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Perception\AISense_Touch.h:36
namespace UnrealEngine
{
[ManageType("ManageAISense_Touch")]
public partial class ManageAISense_Touch : UAISense_Touch, IManageWrapper
{
public ManageAISense_Touch(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_CleanseInvalidSources(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UAISense_Touch_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
public override void CleanseInvalidSources()
=> E__Supper__UAISense_Touch_CleanseInvalidSources(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UAISense_Touch_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UAISense_Touch_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UAISense_Touch_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UAISense_Touch_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UAISense_Touch_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UAISense_Touch_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UAISense_Touch_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UAISense_Touch_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UAISense_Touch_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UAISense_Touch_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UAISense_Touch_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UAISense_Touch_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UAISense_Touch_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UAISense_Touch_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UAISense_Touch_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageAISense_Touch self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageAISense_Touch(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageAISense_Touch>(PtrDesc);
}
}
}
| |
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using JigLibX.Math;
#endregion
namespace JigLibX.Geometry
{
#region public struct Line
/// <summary>
/// A line goes through pos, and extends infinitely far in both
/// directions along dir.
/// </summary>
public struct Line
{
/// <summary>
/// Origin
/// </summary>
public Vector3 Origin;
/// <summary>
/// Direction
/// </summary>
public Vector3 Dir;
/// <summary>
/// Consructor
/// </summary>
/// <param name="origin"></param>
/// <param name="dir"></param>
public Line(Vector3 origin, Vector3 dir)
{
this.Origin = origin;
this.Dir = dir;
}
/// <summary>
/// GetOrigin
/// </summary>
/// <param name="t"></param>
/// <returns>Vector3</returns>
public Vector3 GetOrigin(float t)
{
return new Vector3(
Origin.X + t * Dir.X,
Origin.Y + t * Dir.Y,
Origin.Z + t * Dir.Z);
//return this.Origin + t * this.Dir;
}
}
#endregion
#region public struct Ray
/// <summary>
/// A Ray is just a line that extends in the +ve direction
/// </summary>
public struct Ray
{
/// <summary>
/// Origin
/// </summary>
public Vector3 Origin;
/// <summary>
/// Direction
/// </summary>
public Vector3 Dir;
/// <summary>
/// Constructor
/// </summary>
/// <param name="origin"></param>
/// <param name="dir"></param>
public Ray(Vector3 origin,Vector3 dir)
{
this.Origin = origin;
this.Dir = dir;
}
/// <summary>
/// GetOrigin
/// </summary>
/// <param name="t"></param>
/// <returns>Vector3</returns>
public Vector3 GetOrigin(float t)
{
return new Vector3(
Origin.X + t * Dir.X,
Origin.Y + t * Dir.Y,
Origin.Z + t * Dir.Z);
//return this.Origin + t * this.Dir;
}
}
#endregion
#region public struct Segment
/// <summary>
/// A Segment is a line that starts at origin and goes only as far as
/// (origin + delta).
/// </summary>
public struct Segment
{
/// <summary>
/// Origin
/// </summary>
public Vector3 Origin;
/// <summary>
/// Direction
/// </summary>
public Vector3 Delta;
/// <summary>
/// Constructor
/// </summary>
/// <param name="origin"></param>
/// <param name="delta"></param>
public Segment(Vector3 origin, Vector3 delta)
{
this.Origin = origin;
this.Delta = delta;
}
// BEN-OPTIMISATION: New method, ref origin and ref delta
/// <summary>
/// Constructor
/// </summary>
/// <param name="origin"></param>
/// <param name="delta"></param>
public Segment(ref Vector3 origin, ref Vector3 delta)
{
this.Origin = origin;
this.Delta = delta;
}
/// <summary>
/// GetPoint
/// </summary>
/// <param name="t"></param>
/// <param name="point"></param>
public void GetPoint(float t, out Vector3 point)
{
point = new Vector3(
t * Delta.X,
t * Delta.Y,
t * Delta.Z);
point.X += Origin.X;
point.Y += Origin.Y;
point.Z += Origin.Z;
}
/// <summary>
/// GetPoint
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public Vector3 GetPoint(float t)
{
Vector3 result = new Vector3(
t * Delta.X,
t * Delta.Y,
t * Delta.Z);
result.X += Origin.X;
result.Y += Origin.Y;
result.Z += Origin.Z;
return result;
}
// BEN-OPTIMISATION: New method, ref point.
/// <summary>
/// GetPoint
/// </summary>
/// <param name="point"></param>
/// <param name="t"></param>
public void GetPoint(ref Vector3 point, float t)
{
point.X = t * Delta.X + Origin.X;
point.Y = t * Delta.Y + Origin.Y;
point.Z = t * Delta.Z + Origin.Z;
}
/// <summary>
/// GetEnd
/// </summary>
/// <returns>Vector3</returns>
public Vector3 GetEnd()
{
return new Vector3(
Delta.X + Origin.X,
Delta.Y + Origin.Y,
Delta.Z + Origin.Z);
//return Origin + Delta;
}
}
#endregion
}
| |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Data.
THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Data.
THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using GME.CSharp;
using GME;
using GME.MGA;
using GME.MGA.Core;
using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces;
using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes;
using System.Diagnostics;
using System.Windows.Forms;
namespace ModelicaImporter
{
/// <summary>
/// This class implements the necessary COM interfaces for a GME interpreter component.
/// </summary>
[Guid(ComponentConfig.guid),
ProgId(ComponentConfig.progID),
ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class ModelicaImporterInterpreter : IMgaComponentEx, IGMEVersionInfo
{
/// <summary>
/// Contains information about the GUI event that initiated the invocation.
/// </summary>
public enum ComponentStartMode
{
GME_MAIN_START = 0, // Not used by GME
GME_BROWSER_START = 1, // Right click in the GME Tree Browser window
GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window
GME_EMBEDDED_START = 3, // Not used by GME
GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu
GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window
GME_ICON_START = 32, // Not used by GME
GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME
}
/// <summary>
/// This function is called for each interpreter invocation before Main.
/// Don't perform MGA operations here unless you open a tansaction.
/// </summary>
/// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
public void Initialize(MgaProject project)
{
// TODO: Add your initialization code here...
}
/// <summary>
/// The main entry point of the interpreter. A transaction is already open,
/// GMEConsole is available. A general try-catch block catches all the exceptions
/// coming from this function, you don't need to add it. For more information, see InvokeEx.
/// </summary>
/// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
/// <param name="currentobj">The model open in the active tab in GME. Its value is null if no model is open (no GME modeling windows open). </param>
/// <param name="selectedobjs">
/// A collection for the selected model elements. It is never null.
/// If the interpreter is invoked by the context menu of the GME Tree Browser, then the selected items in the tree browser. Folders
/// are never passed (they are not FCOs).
/// If the interpreter is invoked by clicking on the toolbar icon or the context menu of the modeling window, then the selected items
/// in the active GME modeling window. If nothing is selected, the collection is empty (contains zero elements).
/// </param>
/// <param name="startMode">Contains information about the GUI event that initiated the invocation.</param>
[ComVisible(false)]
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
{
// Check if OpenModelica is installed properly
if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENMODELICAHOME")))
{
this.Logger.WriteFailed(
"OpenModelica is probably not installed. OPENMODELICAHOME environment variable needs to be set. <a href=\"https://openmodelica.org\">https://openmodelica.org</a>");
return;
}
// nothing is open, import multiple components to folder 'ModelicaImports'
if (currentobj == null)
{
MessageBox.Show(
"New Components/TestComponents will be created in the folder 'ModelicaImports'.",
"For Your Information",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
this.Logger.WriteInfo("New Components/TestComponents will be created in the folder 'ModelicaImports'.");
// call ModelicaModelPicker with selectMultiple = true
using (ModelicaModelPicker modelpicker = new ModelicaModelPicker(true, project, this.Logger))
{
var dialogResult = modelpicker.ShowDialog();
if (dialogResult != System.Windows.Forms.DialogResult.OK)
{
this.Logger.WriteInfo("Modelica import was cancelled by the user.");
return;
}
}
}
else
{
if ((currentobj.Meta.Name != typeof(CyPhy.Component).Name &&
currentobj.Meta.Name != typeof(CyPhy.TestComponent).Name))
{
this.Logger.WriteError("Please open a Component or TestComponent and try again.");
return;
}
if (currentobj.Meta.Name == typeof(CyPhy.TestComponent).Name)
{
var childObjects = currentobj.ChildObjects;
foreach (MgaObject child in childObjects)
{
if (child.MetaBase.Name == "ModelicaModel")
{
this.Logger.WriteError("TestComponent {0} already has a ModelicaModel. Only one is allowed.", currentobj.Name);
return;
}
}
}
CyPhy.ComponentType cyphyComponent = null;
if (currentobj.Meta.Name == typeof(CyPhy.Component).Name)
{
cyphyComponent = CyPhyClasses.Component.Cast(currentobj);
}
else if (currentobj.Meta.Name == typeof(CyPhy.TestComponent).Name)
{
cyphyComponent = CyPhyClasses.TestComponent.Cast(currentobj);
}
// per META-2674
if (cyphyComponent.IsLib)
{
this.Logger.WriteError("Cannot modify a model in an attached Library; please select a valid Component or TestComponent.");
return;
}
// per META-2673
if (cyphyComponent.IsInstance)
{
this.Logger.WriteError("Cannot modify an Instance; please select a non-Instance Component or TestComponent.");
return;
}
string message = string.Format("All selected Modelica models will be added to {0}.", currentobj.Name);
MessageBox.Show(
message,
"For Your Information",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
this.Logger.WriteInfo(message);
// call ModelicaModelPicker with selectMultiple = false
using (ModelicaModelPicker modelpicker = new ModelicaModelPicker(false, project, this.Logger, cyphyComponent))
{
var dialogResult = modelpicker.ShowDialog();
if (dialogResult != System.Windows.Forms.DialogResult.OK)
{
this.Logger.WriteInfo("Modelica import was cancelled by the user.");
return;
}
}
}
}
#region IMgaComponentEx Members
MgaGateway MgaGateway { get; set; }
private CyPhyGUIs.GMELogger Logger { get; set; }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
{
if (!enabled)
{
return;
}
try
{
this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);
MgaGateway = new MgaGateway(project);
project.CreateTerritoryWithoutSink(out MgaGateway.territory);
MgaGateway.PerformInTransaction(delegate
{
Main(project, currentobj, selectedobjs, Convert(param));
});
}
finally
{
if (this.Logger != null)
{
this.Logger.Dispose();
this.Logger = null;
}
if (MgaGateway.territory != null)
{
MgaGateway.territory.Destroy();
}
MgaGateway = null;
project = null;
currentobj = null;
selectedobjs = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
private ComponentStartMode Convert(int param)
{
switch (param)
{
case (int)ComponentStartMode.GME_BGCONTEXT_START:
return ComponentStartMode.GME_BGCONTEXT_START;
case (int)ComponentStartMode.GME_BROWSER_START:
return ComponentStartMode.GME_BROWSER_START;
case (int)ComponentStartMode.GME_CONTEXT_START:
return ComponentStartMode.GME_CONTEXT_START;
case (int)ComponentStartMode.GME_EMBEDDED_START:
return ComponentStartMode.GME_EMBEDDED_START;
case (int)ComponentStartMode.GME_ICON_START:
return ComponentStartMode.GME_ICON_START;
case (int)ComponentStartMode.GME_MAIN_START:
return ComponentStartMode.GME_MAIN_START;
case (int)ComponentStartMode.GME_MENU_START:
return ComponentStartMode.GME_MENU_START;
case (int)ComponentStartMode.GME_SILENT_MODE:
return ComponentStartMode.GME_SILENT_MODE;
}
return ComponentStartMode.GME_SILENT_MODE;
}
#region Component Information
public string ComponentName
{
get { return GetType().Name; }
}
public string ComponentProgID
{
get
{
return ComponentConfig.progID;
}
}
public componenttype_enum ComponentType
{
get { return ComponentConfig.componentType; }
}
public string Paradigm
{
get { return ComponentConfig.paradigmName; }
}
#endregion
#region Enabling
bool enabled = true;
public void Enable(bool newval)
{
enabled = newval;
}
#endregion
#region Interactive Mode
protected bool interactiveMode = true;
public bool InteractiveMode
{
get
{
return interactiveMode;
}
set
{
interactiveMode = value;
}
}
#endregion
#region Custom Parameters
SortedDictionary<string, object> componentParameters = null;
public object get_ComponentParameter(string Name)
{
if (Name == "type")
return "csharp";
if (Name == "path")
return GetType().Assembly.Location;
if (Name == "fullname")
return GetType().FullName;
object value;
if (componentParameters != null && componentParameters.TryGetValue(Name, out value))
{
return value;
}
return null;
}
public void set_ComponentParameter(string Name, object pVal)
{
if (componentParameters == null)
{
componentParameters = new SortedDictionary<string, object>();
}
componentParameters[Name] = pVal;
}
#endregion
#region Unused Methods
// Old interface, it is never called for MgaComponentEx interfaces
public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param)
{
throw new NotImplementedException();
}
// Not used by GME
public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param)
{
throw new NotImplementedException();
}
#endregion
#endregion
#region IMgaVersionInfo Members
public GMEInterfaceVersion_enum version
{
get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; }
}
#endregion
#region Registration Helpers
[ComRegisterFunctionAttribute]
public static void GMERegister(Type t)
{
Registrar.RegisterComponentsInGMERegistry();
}
[ComUnregisterFunctionAttribute]
public static void GMEUnRegister(Type t)
{
Registrar.UnregisterComponentsInGMERegistry();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Test.Common;
using System.Threading;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class SendPacketsAsync
{
private readonly ITestOutputHelper _log;
private IPAddress _serverAddress = IPAddress.IPv6Loopback;
// Accessible directories for UWP app:
// C:\Users\<UserName>\AppData\Local\Packages\<ApplicationPackageName>\
private string TestFileName = Environment.GetEnvironmentVariable("LocalAppData") + @"\NCLTest.Socket.SendPacketsAsync.testpayload";
private static int s_testFileSize = 1024;
#region Additional test attributes
public SendPacketsAsync(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
byte[] buffer = new byte[s_testFileSize];
for (int i = 0; i < s_testFileSize; i++)
{
buffer[i] = (byte)(i % 255);
}
try
{
_log.WriteLine("Creating file {0} with size: {1}", TestFileName, s_testFileSize);
using (FileStream fs = new FileStream(TestFileName, FileMode.CreateNew))
{
fs.Write(buffer, 0, buffer.Length);
}
}
catch (IOException)
{
// Test payload file already exists.
_log.WriteLine("Payload file exists: {0}", TestFileName);
}
}
#endregion Additional test attributes
#region Basic Arguments
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Disposed_Throw(SocketImplementationType type)
{
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
sock.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
{
sock.SendPacketsAsync(new SocketAsyncEventArgs());
});
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullArgs_Throw(SocketImplementationType type)
{
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
AssertExtensions.Throws<ArgumentNullException>("e", () => sock.SendPacketsAsync(null));
}
}
}
[Fact]
public void NotConnected_Throw()
{
Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
// Needs to be connected before send
Assert.Throws<NotSupportedException>(() =>
{
socket.SendPacketsAsync(new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] });
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null m_SendPacketsElementsInternal array")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullList_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentNullException>("e.SendPacketsElements", () => SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0));
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullElement_Ignored(SocketImplementationType type)
{
SendPackets(type, (SendPacketsElement)null, 0);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void EmptyList_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement[0], SocketError.Success, 0);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SocketAsyncEventArgs_DefaultSendSize_0()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
Assert.Equal(0, args.SendPacketsSendSize);
}
#endregion Basic Arguments
#region Buffers
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NormalBuffer_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10]), 10);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NormalBufferRange_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 5, 5), 5);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void EmptyBuffer_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[0]), 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferZeroCount_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 0), 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferMixedBuffers_ZeroCountBufferIgnored(SocketImplementationType type)
{
SendPacketsElement[] elements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[10], 4, 0), // Ignored
new SendPacketsElement(new byte[10], 4, 4),
new SendPacketsElement(new byte[10], 0, 4)
};
SendPackets(type, elements, SocketError.Success, 8);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferZeroCountThenNormal_ZeroCountIgnored(SocketImplementationType type)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
// First do an empty send, ignored
args.SendPacketsElements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[5], 3, 0)
};
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(0, args.BytesTransferred);
completed.Reset();
// Now do a real send
args.SendPacketsElements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[5], 1, 4)
};
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(4, args.BytesTransferred);
}
}
}
}
#endregion Buffers
#region TransmitFileOptions
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SocketDisconnected_TransmitFileOptionDisconnect(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect, 4);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SocketDisconnectedAndReusable_TransmitFileOptionReuseSocket(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket, 4);
}
#endregion
#region Files
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
SendPackets(type, new SendPacketsElement(String.Empty), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[PlatformSpecific(TestPlatforms.Windows)] // whitespace-only is a valid name on Unix
public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(" "), 0);
});
}
[Theory]
[ActiveIssue(27269)]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[PlatformSpecific(TestPlatforms.Windows)] // valid filename chars on Unix
public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_MissingDirectoryName_Throws(SocketImplementationType type)
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(Path.Combine("nodir", "nofile")), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_MissingFile_Throws(SocketImplementationType type)
{
Assert.Throws<FileNotFoundException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("DoesntExit"), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_File_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName), s_testFileSize); // Whole File
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileZeroCount_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName, 0, 0), s_testFileSize); // Whole File
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FilePart_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName, 10, 20), 20);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileMultiPart_Success(SocketImplementationType type)
{
SendPacketsElement[] elements = new SendPacketsElement[]
{
new SendPacketsElement(TestFileName, 10, 20),
new SendPacketsElement(TestFileName, 30, 10),
new SendPacketsElement(TestFileName, 0, 10),
};
SendPackets(type, elements, SocketError.Success, 40);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileLargeOffset_Throws(SocketImplementationType type)
{
// Length is validated on Send
SendPackets(type, new SendPacketsElement(TestFileName, 11000, 1), SocketError.InvalidArgument, 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileLargeCount_Throws(SocketImplementationType type)
{
// Length is validated on Send
SendPackets(type, new SendPacketsElement(TestFileName, 5, 10000), SocketError.InvalidArgument, 0);
}
#endregion Files
#region Helpers
private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
args.SendPacketsElements = new[] { element };
args.SendPacketsFlags = flags;
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(bytesExpected, args.BytesTransferred);
}
switch (flags)
{
case TransmitFileOptions.Disconnect:
// Sending data again throws with socket shut down error.
Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); });
break;
case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect:
// Able to send data again with reuse socket flag set.
Assert.Equal(1, sock.Send(new byte[1] { 01 }));
break;
}
}
}
}
private void SendPackets(SocketImplementationType type, SendPacketsElement element, int bytesExpected)
{
SendPackets(type, new SendPacketsElement[] { element }, SocketError.Success, bytesExpected);
}
private void SendPackets(SocketImplementationType type, SendPacketsElement element, SocketError expectedResut, int bytesExpected)
{
SendPackets(type, new SendPacketsElement[] { element }, expectedResut, bytesExpected);
}
private void SendPackets(SocketImplementationType type, SendPacketsElement[] elements, SocketError expectedResut, int bytesExpected)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
args.SendPacketsElements = elements;
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(expectedResut, args.SocketError);
Assert.Equal(bytesExpected, args.BytesTransferred);
}
}
}
}
private void OnCompleted(object sender, SocketAsyncEventArgs e)
{
EventWaitHandle handle = (EventWaitHandle)e.UserToken;
handle.Set();
}
#endregion Helpers
}
}
| |
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
namespace TBS.ScreenManager
{
/// <summary>
/// Helper for reading input from keyboard, gamepad, and touch input. This class
/// tracks both the current and previous state of the input devices, and implements
/// query methods for high level input actions such as "move up through the menu"
/// or "pause the game".
/// </summary>
public class InputState
{
#region Fields
public const int MaxInputs = 4;
public readonly KeyboardState[] CurrentKeyboardStates;
public readonly GamePadState[] CurrentGamePadStates;
public readonly KeyboardState[] LastKeyboardStates;
public readonly GamePadState[] LastGamePadStates;
public readonly bool[] GamePadWasConnected;
public TouchCollection TouchState;
public readonly List<GestureSample> Gestures = new List<GestureSample>();
#endregion
#region Initialization
/// <summary>
/// Constructs a new input state.
/// </summary>
public InputState()
{
CurrentKeyboardStates = new KeyboardState[MaxInputs];
CurrentGamePadStates = new GamePadState[MaxInputs];
LastKeyboardStates = new KeyboardState[MaxInputs];
LastGamePadStates = new GamePadState[MaxInputs];
GamePadWasConnected = new bool[MaxInputs];
}
#endregion
#region Public Methods
/// <summary>
/// Reads the latest state of the keyboard and gamepad.
/// </summary>
public void Update()
{
for (int i = 0; i < MaxInputs; i++)
{
LastKeyboardStates[i] = CurrentKeyboardStates[i];
LastGamePadStates[i] = CurrentGamePadStates[i];
CurrentKeyboardStates[i] = Keyboard.GetState();
CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i);
// Keep track of whether a gamepad has ever been
// connected, so we can detect if it is unplugged.
if (CurrentGamePadStates[i].IsConnected)
{
GamePadWasConnected[i] = true;
}
}
TouchState = TouchPanel.GetState();
Gestures.Clear();
while (TouchPanel.IsGestureAvailable)
{
Gestures.Add(TouchPanel.ReadGesture());
}
}
/// <summary>
/// Helper for checking if a key was newly pressed during this update. The
/// controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When a keypress
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
if (controllingPlayer.HasValue)
{
// Read input from the specified player.
playerIndex = controllingPlayer.Value;
var i = (int)playerIndex;
return (CurrentKeyboardStates[i].IsKeyDown(key) &&
LastKeyboardStates[i].IsKeyUp(key));
}
// Accept input from any player.
return (IsNewKeyPress(key, PlayerIndex.One, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Two, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Three, out playerIndex) ||
IsNewKeyPress(key, PlayerIndex.Four, out playerIndex));
}
/// <summary>
/// Helper for checking if a button was newly pressed during this update.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When a button press
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
if (controllingPlayer.HasValue)
{
// Read input from the specified player.
playerIndex = controllingPlayer.Value;
var i = (int)playerIndex;
return (CurrentGamePadStates[i].IsButtonDown(button) &&
LastGamePadStates[i].IsButtonUp(button));
}
// Accept input from any player.
return (IsNewButtonPress(button, PlayerIndex.One, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Two, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Three, out playerIndex) ||
IsNewButtonPress(button, PlayerIndex.Four, out playerIndex));
}
/// <summary>
/// Checks for a "menu select" input action.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When the action
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsMenuSelect(PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
return IsNewKeyPress(Keys.Space, controllingPlayer, out playerIndex) ||
IsNewKeyPress(Keys.Enter, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.A, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "menu cancel" input action.
/// The controllingPlayer parameter specifies which player to read input for.
/// If this is null, it will accept input from any player. When the action
/// is detected, the output playerIndex reports which player pressed it.
/// </summary>
public bool IsMenuCancel(PlayerIndex? controllingPlayer,
out PlayerIndex playerIndex)
{
return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.B, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "menu up" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsMenuUp(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "menu down" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsMenuDown(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex);
}
/// <summary>
/// Checks for a "pause the game" input action.
/// The controllingPlayer parameter specifies which player to read
/// input for. If this is null, it will accept input from any player.
/// </summary>
public bool IsPauseGame(PlayerIndex? controllingPlayer)
{
PlayerIndex playerIndex;
return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex) ||
IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex);
}
#endregion
}
}
| |
//
// AudioFormat.cs:
//
// Authors:
// Miguel de Icaza (miguel@xamarin.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 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.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MonoMac.CoreFoundation;
using MonoMac.Foundation;
using OSStatus = System.Int32;
using AudioFileID = System.IntPtr;
namespace MonoMac.AudioToolbox {
// AudioFormatListItem
[StructLayout(LayoutKind.Sequential, Pack=4)] // Force same memory layout as in native code for easier marshalling
public struct AudioFormat
{
public AudioStreamBasicDescription AudioStreamBasicDescription;
public AudioChannelLayoutTag AudioChannelLayoutTag;
public unsafe static AudioFormat? GetFirstPlayableFormat (AudioFormat[] formatList)
{
if (formatList == null)
throw new ArgumentNullException ("formatList");
if (formatList.Length < 2)
throw new ArgumentException ("formatList");
fixed (AudioFormat* item = &formatList[0]) {
uint index;
int size = sizeof (uint);
var ptr_size = sizeof (AudioFormat) * formatList.Length;
if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FirstPlayableFormatFromList, ptr_size, item, ref size, out index) != 0)
return null;
return formatList [index];
}
}
public override string ToString ()
{
return AudioChannelLayoutTag + ":" + AudioStreamBasicDescription.ToString ();
}
}
public enum AudioFormatError
{
None = 0,
Unspecified = 0x77686174, // 'what'
UnsupportedProperty = 0x70726f70, // 'prop'
BadPropertySize = 0x2173697a, // '!siz'
BadSpecifierSize = 0x21737063, // '!spc'
UnsupportedDataFormat = 0x666d743f, // 'fmt?'
UnknownFormat = 0x21666d74 // '!fmt'
// TODO: Not documented
// '!dat'
}
[StructLayout (LayoutKind.Sequential)]
public struct AudioValueRange
{
public double Minimum;
public double Maximum;
}
public enum AudioBalanceFadeType
{
MaxUnityGain = 0,
EqualPower = 1
}
public class AudioBalanceFade
{
[StructLayout (LayoutKind.Sequential)]
struct Layout
{
public float LeftRightBalance;
public float BackFrontFade;
public AudioBalanceFadeType Type;
public IntPtr ChannelLayoutWeak;
}
public AudioBalanceFade (AudioChannelLayout channelLayout)
{
if (channelLayout == null)
throw new ArgumentNullException ("channelLayout");
this.ChannelLayout = channelLayout;
}
public float LeftRightBalance { get; set; }
public float BackFrontFade { get; set; }
public AudioBalanceFadeType Type { get; set; }
public AudioChannelLayout ChannelLayout { get; private set; }
public unsafe float[] GetBalanceFade ()
{
var type_size = sizeof (Layout);
var str = ToStruct ();
var ptr = Marshal.AllocHGlobal (type_size);
(*(Layout *) ptr) = str;
int size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.BalanceFade, type_size, ptr, out size) != 0)
return null;
AudioFormatError res;
var data = new float[size / sizeof (float)];
fixed (float* data_ptr = data) {
res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.BalanceFade, type_size, ptr, ref size, data_ptr);
}
Marshal.FreeHGlobal (str.ChannelLayoutWeak);
Marshal.FreeHGlobal (ptr);
return res == 0 ? data : null;
}
Layout ToStruct ()
{
var l = new Layout ()
{
LeftRightBalance = LeftRightBalance,
BackFrontFade = BackFrontFade,
Type = Type,
};
if (ChannelLayout != null) {
int temp;
l.ChannelLayoutWeak = ChannelLayout.ToBlock (out temp);
}
return l;
}
}
public enum PanningMode
{
SoundField = 3,
VectorBasedPanning = 4
}
public class AudioPanningInfo
{
[StructLayout (LayoutKind.Sequential)]
struct Layout
{
public PanningMode PanningMode;
public AudioChannelFlags CoordinateFlags;
public float Coord0, Coord1, Coord2;
public float GainScale;
public IntPtr OutputChannelMapWeak;
}
public AudioPanningInfo (AudioChannelLayout outputChannelMap)
{
if (outputChannelMap == null)
throw new ArgumentNullException ("outputChannelMap");
this.OutputChannelMap = outputChannelMap;
}
public PanningMode PanningMode { get; set; }
public AudioChannelFlags CoordinateFlags { get; set; }
public float[] Coordinates { get; private set; }
public float GainScale { get; set; }
public AudioChannelLayout OutputChannelMap { get; private set; }
public unsafe float[] GetPanningMatrix ()
{
var type_size = sizeof (Layout);
var str = ToStruct ();
var ptr = Marshal.AllocHGlobal (type_size);
*((Layout *)ptr) = str;
int size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.PanningMatrix, type_size, ptr, out size) != 0)
return null;
AudioFormatError res;
var data = new float[size / sizeof (float)];
fixed (float* data_ptr = data) {
res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.PanningMatrix, type_size, ptr, ref size, data_ptr);
}
Marshal.FreeHGlobal (str.OutputChannelMapWeak);
Marshal.FreeHGlobal (ptr);
return res == 0 ? data : null;
}
Layout ToStruct ()
{
var l = new Layout ()
{
PanningMode = PanningMode,
CoordinateFlags = CoordinateFlags,
Coord0 = Coordinates [0],
Coord1 = Coordinates [1],
Coord2 = Coordinates [2],
GainScale = GainScale
};
if (OutputChannelMap != null) {
int temp;
l.OutputChannelMapWeak = OutputChannelMap.ToBlock (out temp);
}
return l;
}
}
static partial class AudioFormatPropertyNative
{
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioFormatType inSpecifier,
out uint outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioStreamBasicDescription inSpecifier,
out uint outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioFormatInfo inSpecifier,
out uint outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, ref int inSpecifier,
out int outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
out int outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioFormatType inSpecifier,
ref uint ioDataSize, IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref int inSpecifier,
ref int ioDataSize, IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
ref int ioDataSize, IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
ref int ioDataSize, out IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
ref int ioDataSize, out int outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref int inSpecifier,
ref int ioDataSize, out int outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
IntPtr ioDataSize, IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioFormatInfo inSpecifier,
ref uint ioDataSize, AudioFormat* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioStreamBasicDescription inSpecifier,
ref uint ioDataSize, int* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref int inSpecifier,
ref int ioDataSize, int* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr* inSpecifier,
ref int ioDataSize, int* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr* inSpecifier,
ref int ioDataSize, float* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
ref int ioDataSize, float* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty inPropertyID, int inSpecifierSize, ref AudioStreamBasicDescription inSpecifier,
ref int ioPropertyDataSize, out IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty inPropertyID, int inSpecifierSize, ref AudioStreamBasicDescription inSpecifier,
ref int ioPropertyDataSize, out uint outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty inPropertyID, int inSpecifierSize, IntPtr inSpecifier, ref int ioPropertyDataSize,
ref AudioStreamBasicDescription outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty inPropertyID, int inSpecifierSize, AudioFormat* inSpecifier, ref int ioPropertyDataSize,
out uint outPropertyData);
}
// Properties are used from various types (most suitable should be used)
enum AudioFormatProperty
{
FormatInfo = 0x666d7469, // 'fmti'
FormatName = 0x666e616d, // 'fnam'
EncodeFormatIDs = 0x61636f66, // 'acof'
DecodeFormatIDs = 0x61636966, // 'acif'
FormatList = 0x666c7374, // 'flst'
ASBDFromESDS = 0x65737364, // 'essd' // TODO: FromElementaryStreamDescriptor
ChannelLayoutFromESDS = 0x6573636c, // 'escl' // TODO:
OutputFormatList = 0x6f666c73, // 'ofls'
FirstPlayableFormatFromList = 0x6670666c, // 'fpfl'
FormatIsVBR = 0x66766272, // 'fvbr'
FormatIsExternallyFramed = 0x66657866, // 'fexf'
FormatIsEncrypted = 0x63727970, // 'cryp'
Encoders = 0x6176656e, // 'aven'
Decoders = 0x61766465, // 'avde'
AvailableEncodeChannelLayoutTags = 0x6165636c, // 'aecl'
AvailableEncodeNumberChannels = 0x61766e63, // 'avnc'
AvailableEncodeBitRates = 0x61656272, // 'aebr'
AvailableEncodeSampleRates = 0x61657372, // 'aesr'
ASBDFromMPEGPacket = 0x61646d70, // 'admp' // TODO:
BitmapForLayoutTag = 0x626d7467, // 'bmtg'
MatrixMixMap = 0x6d6d6170, // 'mmap'
ChannelMap = 0x63686d70, // 'chmp'
NumberOfChannelsForLayout = 0x6e63686d, // 'nchm'
AreChannelLayoutsEquivalent = 0x63686571, // 'cheq' // TODO:
ValidateChannelLayout = 0x7661636c, // 'vacl'
ChannelLayoutForTag = 0x636d706c, // 'cmpl'
TagForChannelLayout = 0x636d7074, // 'cmpt'
ChannelLayoutName = 0x6c6f6e6d, // 'lonm'
ChannelLayoutSimpleName = 0x6c6f6e6d, // 'lsnm'
ChannelLayoutForBitmap = 0x636d7062, // 'cmpb'
ChannelName = 0x636e616d, // 'cnam'
ChannelShortName = 0x63736e6d, // 'csnm'
TagsForNumberOfChannels = 0x74616763, // 'tagc'
PanningMatrix = 0x70616e6d, // 'panm'
BalanceFade = 0x62616c66, // 'balf'
ID3TagSize = 0x69643373, // 'id3s' // TODO:
ID3TagToDictionary = 0x69643364, // 'id3d' // TODO:
#if !MONOMAC
HardwareCodecCapabilities = 0x68776363, // 'hwcc'
#endif
}
}
| |
namespace EIDSS.Reports.BaseControls
{
partial class ReportView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ReportView));
this.printingSystemReports = new DevExpress.XtraPrinting.PrintingSystem(this.components);
this.printControlReport = new EIDSS.Reports.BaseControls.ReportPrintControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.printBarManager = new DevExpress.XtraPrinting.Preview.PrintBarManager();
this.previewBar1 = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.biLoadDefault = new DevExpress.XtraBars.BarButtonItem();
this.biEdit = new DevExpress.XtraBars.BarButtonItem();
this.biFind = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPrint = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPrintDirect = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biPageSetup = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biScale = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biHandTool = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biMagnifier = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biZoomOut = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biZoom = new DevExpress.XtraPrinting.Preview.ZoomBarEditItem();
this.printPreviewRepositoryItemComboBox1 = new DevExpress.XtraPrinting.Preview.PrintPreviewRepositoryItemComboBox();
this.ZoomIn = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowFirstPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowPrevPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowNextPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biShowLastPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biMultiplePages = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biFillBackground = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.biExportFile = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.barStatus = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.biPage = new DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem();
this.barStaticItem1 = new DevExpress.XtraBars.BarStaticItem();
this.biProgressBar = new DevExpress.XtraPrinting.Preview.ProgressBarEditItem();
this.repositoryItemProgressBar1 = new DevExpress.XtraEditors.Repository.RepositoryItemProgressBar();
this.biStatusStatus = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem();
this.biStatusZoom = new DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem();
this.barMainMenu = new DevExpress.XtraPrinting.Preview.PreviewBar();
this.printPreviewSubItem4 = new DevExpress.XtraPrinting.Preview.PrintPreviewSubItem();
this.printPreviewBarItem27 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.printPreviewBarItem28 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.barToolbarsListItem1 = new DevExpress.XtraBars.BarToolbarsListItem();
this.biExportPdf = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportHtm = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportMht = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportRtf = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportXls = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportCsv = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportTxt = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.biExportGraphic = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem();
this.printPreviewBarItem2 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem();
this.timerScroll = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.printingSystemReports)).BeginInit();
this.printControlReport.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.printBarManager)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.printPreviewRepositoryItemComboBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemProgressBar1)).BeginInit();
this.SuspendLayout();
//
// printControlReport
//
this.printControlReport.AccessibleDescription = null;
this.printControlReport.AccessibleName = null;
resources.ApplyResources(this.printControlReport, "printControlReport");
this.printControlReport.BackgroundImage = null;
this.printControlReport.Controls.Add(this.barDockControlLeft);
this.printControlReport.Controls.Add(this.barDockControlRight);
this.printControlReport.Controls.Add(this.barDockControlBottom);
this.printControlReport.Controls.Add(this.barDockControlTop);
this.printControlReport.Font = null;
this.printControlReport.LookAndFeel.SkinName = "Blue";
this.printControlReport.Name = "printControlReport";
this.printControlReport.PrintingSystem = this.printingSystemReports;
//
// barDockControlLeft
//
this.barDockControlLeft.AccessibleDescription = null;
this.barDockControlLeft.AccessibleName = null;
resources.ApplyResources(this.barDockControlLeft, "barDockControlLeft");
this.barDockControlLeft.Font = null;
//
// barDockControlRight
//
this.barDockControlRight.AccessibleDescription = null;
this.barDockControlRight.AccessibleName = null;
resources.ApplyResources(this.barDockControlRight, "barDockControlRight");
this.barDockControlRight.Font = null;
//
// barDockControlBottom
//
this.barDockControlBottom.AccessibleDescription = null;
this.barDockControlBottom.AccessibleName = null;
resources.ApplyResources(this.barDockControlBottom, "barDockControlBottom");
this.barDockControlBottom.Font = null;
//
// barDockControlTop
//
this.barDockControlTop.AccessibleDescription = null;
this.barDockControlTop.AccessibleName = null;
resources.ApplyResources(this.barDockControlTop, "barDockControlTop");
this.barDockControlTop.Font = null;
//
// printBarManager
//
this.printBarManager.AllowCustomization = false;
this.printBarManager.AllowQuickCustomization = false;
this.printBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.previewBar1,
this.barStatus,
this.barMainMenu});
this.printBarManager.DockControls.Add(this.barDockControlTop);
this.printBarManager.DockControls.Add(this.barDockControlBottom);
this.printBarManager.DockControls.Add(this.barDockControlLeft);
this.printBarManager.DockControls.Add(this.barDockControlRight);
this.printBarManager.Form = this.printControlReport;
this.printBarManager.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("printBarManager.ImageStream")));
this.printBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.biPage,
this.barStaticItem1,
this.biProgressBar,
this.biStatusStatus,
this.barButtonItem1,
this.biStatusZoom,
this.biFind,
this.biPrint,
this.biPrintDirect,
this.biPageSetup,
this.biScale,
this.biHandTool,
this.biMagnifier,
this.biZoomOut,
this.biZoom,
this.ZoomIn,
this.biShowFirstPage,
this.biShowPrevPage,
this.biShowNextPage,
this.biShowLastPage,
this.biMultiplePages,
this.biFillBackground,
this.biExportFile,
this.printPreviewSubItem4,
this.printPreviewBarItem27,
this.printPreviewBarItem28,
this.barToolbarsListItem1,
this.biExportPdf,
this.biExportHtm,
this.biExportMht,
this.biExportRtf,
this.biExportXls,
this.biExportCsv,
this.biExportTxt,
this.biExportGraphic,
this.biEdit,
this.biLoadDefault});
this.printBarManager.MainMenu = this.barMainMenu;
this.printBarManager.MaxItemId = 60;
this.printBarManager.PreviewBar = this.previewBar1;
this.printBarManager.PrintControl = this.printControlReport;
this.printBarManager.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] {
this.repositoryItemProgressBar1,
this.printPreviewRepositoryItemComboBox1});
this.printBarManager.StatusBar = this.barStatus;
//
// previewBar1
//
this.previewBar1.BarName = "Toolbar";
this.previewBar1.DockCol = 0;
this.previewBar1.DockRow = 1;
this.previewBar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.previewBar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biLoadDefault, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biEdit),
new DevExpress.XtraBars.LinkPersistInfo(this.biFind, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biPrint),
new DevExpress.XtraBars.LinkPersistInfo(this.biPrintDirect),
new DevExpress.XtraBars.LinkPersistInfo(this.biPageSetup),
new DevExpress.XtraBars.LinkPersistInfo(this.biScale),
new DevExpress.XtraBars.LinkPersistInfo(this.biHandTool, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biMagnifier),
new DevExpress.XtraBars.LinkPersistInfo(this.biZoomOut, true),
new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.Width, this.biZoom, "", false, true, true, 70),
new DevExpress.XtraBars.LinkPersistInfo(this.ZoomIn),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowFirstPage, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowPrevPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowNextPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biShowLastPage),
new DevExpress.XtraBars.LinkPersistInfo(this.biMultiplePages, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biFillBackground),
new DevExpress.XtraBars.LinkPersistInfo(this.biExportFile, true)});
this.previewBar1.OptionsBar.AllowQuickCustomization = false;
this.previewBar1.OptionsBar.DisableClose = true;
this.previewBar1.OptionsBar.DisableCustomization = true;
this.previewBar1.OptionsBar.DrawDragBorder = false;
resources.ApplyResources(this.previewBar1, "previewBar1");
//
// biLoadDefault
//
this.biLoadDefault.AccessibleDescription = null;
this.biLoadDefault.AccessibleName = null;
resources.ApplyResources(this.biLoadDefault, "biLoadDefault");
this.biLoadDefault.Enabled = false;
this.biLoadDefault.Glyph = global::EIDSS.Reports.Properties.Resources.restore;
this.biLoadDefault.Id = 59;
this.biLoadDefault.Name = "biLoadDefault";
this.biLoadDefault.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
this.biLoadDefault.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biLoadDefault_ItemClick);
//
// biEdit
//
this.biEdit.AccessibleDescription = null;
this.biEdit.AccessibleName = null;
resources.ApplyResources(this.biEdit, "biEdit");
this.biEdit.Enabled = false;
this.biEdit.Glyph = global::EIDSS.Reports.Properties.Resources.msg_edit;
this.biEdit.Id = 58;
this.biEdit.Name = "biEdit";
this.biEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
this.biEdit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biEdit_ItemClick);
//
// biFind
//
this.biFind.AccessibleDescription = null;
this.biFind.AccessibleName = null;
resources.ApplyResources(this.biFind, "biFind");
this.biFind.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Find;
this.biFind.Enabled = false;
this.biFind.Id = 8;
this.biFind.ImageIndex = 20;
this.biFind.Name = "biFind";
//
// biPrint
//
this.biPrint.AccessibleDescription = null;
this.biPrint.AccessibleName = null;
this.biPrint.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biPrint, "biPrint");
this.biPrint.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Print;
this.biPrint.Enabled = false;
this.biPrint.Id = 12;
this.biPrint.ImageIndex = 0;
this.biPrint.Name = "biPrint";
//
// biPrintDirect
//
this.biPrintDirect.AccessibleDescription = null;
this.biPrintDirect.AccessibleName = null;
resources.ApplyResources(this.biPrintDirect, "biPrintDirect");
this.biPrintDirect.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PrintDirect;
this.biPrintDirect.Enabled = false;
this.biPrintDirect.Id = 13;
this.biPrintDirect.ImageIndex = 1;
this.biPrintDirect.Name = "biPrintDirect";
//
// biPageSetup
//
this.biPageSetup.AccessibleDescription = null;
this.biPageSetup.AccessibleName = null;
this.biPageSetup.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biPageSetup, "biPageSetup");
this.biPageSetup.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageSetup;
this.biPageSetup.Enabled = false;
this.biPageSetup.Id = 14;
this.biPageSetup.ImageIndex = 2;
this.biPageSetup.Name = "biPageSetup";
//
// biScale
//
this.biScale.AccessibleDescription = null;
this.biScale.AccessibleName = null;
this.biScale.ActAsDropDown = true;
this.biScale.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biScale, "biScale");
this.biScale.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Scale;
this.biScale.Enabled = false;
this.biScale.Id = 16;
this.biScale.ImageIndex = 25;
this.biScale.Name = "biScale";
//
// biHandTool
//
this.biHandTool.AccessibleDescription = null;
this.biHandTool.AccessibleName = null;
this.biHandTool.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biHandTool, "biHandTool");
this.biHandTool.Command = DevExpress.XtraPrinting.PrintingSystemCommand.HandTool;
this.biHandTool.Enabled = false;
this.biHandTool.Id = 17;
this.biHandTool.ImageIndex = 16;
this.biHandTool.Name = "biHandTool";
//
// biMagnifier
//
this.biMagnifier.AccessibleDescription = null;
this.biMagnifier.AccessibleName = null;
this.biMagnifier.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.biMagnifier, "biMagnifier");
this.biMagnifier.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Magnifier;
this.biMagnifier.Enabled = false;
this.biMagnifier.Id = 18;
this.biMagnifier.ImageIndex = 3;
this.biMagnifier.Name = "biMagnifier";
//
// biZoomOut
//
this.biZoomOut.AccessibleDescription = null;
this.biZoomOut.AccessibleName = null;
resources.ApplyResources(this.biZoomOut, "biZoomOut");
this.biZoomOut.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ZoomOut;
this.biZoomOut.Enabled = false;
this.biZoomOut.Id = 19;
this.biZoomOut.ImageIndex = 5;
this.biZoomOut.Name = "biZoomOut";
//
// biZoom
//
this.biZoom.AccessibleDescription = null;
this.biZoom.AccessibleName = null;
resources.ApplyResources(this.biZoom, "biZoom");
this.biZoom.Edit = this.printPreviewRepositoryItemComboBox1;
this.biZoom.EditValue = "100%";
this.biZoom.Enabled = false;
this.biZoom.Id = 20;
this.biZoom.Name = "biZoom";
//
// printPreviewRepositoryItemComboBox1
//
this.printPreviewRepositoryItemComboBox1.AccessibleDescription = null;
this.printPreviewRepositoryItemComboBox1.AccessibleName = null;
this.printPreviewRepositoryItemComboBox1.AutoComplete = false;
resources.ApplyResources(this.printPreviewRepositoryItemComboBox1, "printPreviewRepositoryItemComboBox1");
this.printPreviewRepositoryItemComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("printPreviewRepositoryItemComboBox1.Buttons"))))});
this.printPreviewRepositoryItemComboBox1.DropDownRows = 11;
this.printPreviewRepositoryItemComboBox1.Name = "printPreviewRepositoryItemComboBox1";
//
// ZoomIn
//
this.ZoomIn.AccessibleDescription = null;
this.ZoomIn.AccessibleName = null;
resources.ApplyResources(this.ZoomIn, "ZoomIn");
this.ZoomIn.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ZoomIn;
this.ZoomIn.Enabled = false;
this.ZoomIn.Id = 21;
this.ZoomIn.ImageIndex = 4;
this.ZoomIn.Name = "ZoomIn";
//
// biShowFirstPage
//
this.biShowFirstPage.AccessibleDescription = null;
this.biShowFirstPage.AccessibleName = null;
resources.ApplyResources(this.biShowFirstPage, "biShowFirstPage");
this.biShowFirstPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowFirstPage;
this.biShowFirstPage.Enabled = false;
this.biShowFirstPage.Id = 22;
this.biShowFirstPage.ImageIndex = 7;
this.biShowFirstPage.Name = "biShowFirstPage";
//
// biShowPrevPage
//
this.biShowPrevPage.AccessibleDescription = null;
this.biShowPrevPage.AccessibleName = null;
resources.ApplyResources(this.biShowPrevPage, "biShowPrevPage");
this.biShowPrevPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowPrevPage;
this.biShowPrevPage.Enabled = false;
this.biShowPrevPage.Id = 23;
this.biShowPrevPage.ImageIndex = 8;
this.biShowPrevPage.Name = "biShowPrevPage";
//
// biShowNextPage
//
this.biShowNextPage.AccessibleDescription = null;
this.biShowNextPage.AccessibleName = null;
resources.ApplyResources(this.biShowNextPage, "biShowNextPage");
this.biShowNextPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowNextPage;
this.biShowNextPage.Enabled = false;
this.biShowNextPage.Id = 24;
this.biShowNextPage.ImageIndex = 9;
this.biShowNextPage.Name = "biShowNextPage";
//
// biShowLastPage
//
this.biShowLastPage.AccessibleDescription = null;
this.biShowLastPage.AccessibleName = null;
resources.ApplyResources(this.biShowLastPage, "biShowLastPage");
this.biShowLastPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowLastPage;
this.biShowLastPage.Enabled = false;
this.biShowLastPage.Id = 25;
this.biShowLastPage.ImageIndex = 10;
this.biShowLastPage.Name = "biShowLastPage";
//
// biMultiplePages
//
this.biMultiplePages.AccessibleDescription = null;
this.biMultiplePages.AccessibleName = null;
this.biMultiplePages.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biMultiplePages, "biMultiplePages");
this.biMultiplePages.Command = DevExpress.XtraPrinting.PrintingSystemCommand.MultiplePages;
this.biMultiplePages.Enabled = false;
this.biMultiplePages.Id = 26;
this.biMultiplePages.ImageIndex = 11;
this.biMultiplePages.Name = "biMultiplePages";
//
// biFillBackground
//
this.biFillBackground.AccessibleDescription = null;
this.biFillBackground.AccessibleName = null;
this.biFillBackground.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biFillBackground, "biFillBackground");
this.biFillBackground.Command = DevExpress.XtraPrinting.PrintingSystemCommand.FillBackground;
this.biFillBackground.Enabled = false;
this.biFillBackground.Id = 27;
this.biFillBackground.ImageIndex = 12;
this.biFillBackground.Name = "biFillBackground";
//
// biExportFile
//
this.biExportFile.AccessibleDescription = null;
this.biExportFile.AccessibleName = null;
this.biExportFile.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown;
resources.ApplyResources(this.biExportFile, "biExportFile");
this.biExportFile.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportFile;
this.biExportFile.Enabled = false;
this.biExportFile.Id = 29;
this.biExportFile.ImageIndex = 18;
this.biExportFile.Name = "biExportFile";
//
// barStatus
//
this.barStatus.BarName = "Status Bar";
this.barStatus.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
this.barStatus.DockCol = 0;
this.barStatus.DockRow = 0;
this.barStatus.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
this.barStatus.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.biPage),
new DevExpress.XtraBars.LinkPersistInfo(this.barStaticItem1, true),
new DevExpress.XtraBars.LinkPersistInfo(this.biProgressBar),
new DevExpress.XtraBars.LinkPersistInfo(this.biStatusStatus),
new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1),
new DevExpress.XtraBars.LinkPersistInfo(this.biStatusZoom, true)});
this.barStatus.OptionsBar.AllowQuickCustomization = false;
this.barStatus.OptionsBar.DrawDragBorder = false;
this.barStatus.OptionsBar.UseWholeRow = true;
resources.ApplyResources(this.barStatus, "barStatus");
//
// biPage
//
this.biPage.AccessibleDescription = null;
this.biPage.AccessibleName = null;
this.biPage.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
resources.ApplyResources(this.biPage, "biPage");
this.biPage.Id = 0;
this.biPage.LeftIndent = 1;
this.biPage.Name = "biPage";
this.biPage.RightIndent = 1;
this.biPage.TextAlignment = System.Drawing.StringAlignment.Near;
this.biPage.Type = "PageOfPages";
//
// barStaticItem1
//
this.barStaticItem1.AccessibleDescription = null;
this.barStaticItem1.AccessibleName = null;
this.barStaticItem1.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
resources.ApplyResources(this.barStaticItem1, "barStaticItem1");
this.barStaticItem1.Id = 1;
this.barStaticItem1.Name = "barStaticItem1";
this.barStaticItem1.TextAlignment = System.Drawing.StringAlignment.Near;
//
// biProgressBar
//
this.biProgressBar.AccessibleDescription = null;
this.biProgressBar.AccessibleName = null;
this.biProgressBar.Edit = this.repositoryItemProgressBar1;
this.biProgressBar.EditHeight = 12;
resources.ApplyResources(this.biProgressBar, "biProgressBar");
this.biProgressBar.Id = 2;
this.biProgressBar.Name = "biProgressBar";
this.biProgressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
//
// repositoryItemProgressBar1
//
this.repositoryItemProgressBar1.AccessibleDescription = null;
this.repositoryItemProgressBar1.AccessibleName = null;
resources.ApplyResources(this.repositoryItemProgressBar1, "repositoryItemProgressBar1");
this.repositoryItemProgressBar1.Name = "repositoryItemProgressBar1";
//
// biStatusStatus
//
this.biStatusStatus.AccessibleDescription = null;
this.biStatusStatus.AccessibleName = null;
resources.ApplyResources(this.biStatusStatus, "biStatusStatus");
this.biStatusStatus.Command = DevExpress.XtraPrinting.PrintingSystemCommand.StopPageBuilding;
this.biStatusStatus.Enabled = false;
this.biStatusStatus.Id = 3;
this.biStatusStatus.Name = "biStatusStatus";
this.biStatusStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
//
// barButtonItem1
//
this.barButtonItem1.AccessibleDescription = null;
this.barButtonItem1.AccessibleName = null;
this.barButtonItem1.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Left;
this.barButtonItem1.Enabled = false;
resources.ApplyResources(this.barButtonItem1, "barButtonItem1");
this.barButtonItem1.Id = 4;
this.barButtonItem1.Name = "barButtonItem1";
//
// biStatusZoom
//
this.biStatusZoom.AccessibleDescription = null;
this.biStatusZoom.AccessibleName = null;
this.biStatusZoom.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right;
this.biStatusZoom.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
resources.ApplyResources(this.biStatusZoom, "biStatusZoom");
this.biStatusZoom.Id = 5;
this.biStatusZoom.Name = "biStatusZoom";
this.biStatusZoom.TextAlignment = System.Drawing.StringAlignment.Near;
this.biStatusZoom.Type = "ZoomFactor";
//
// barMainMenu
//
this.barMainMenu.BarName = "Main Menu";
this.barMainMenu.DockCol = 0;
this.barMainMenu.DockRow = 0;
this.barMainMenu.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.barMainMenu.OptionsBar.MultiLine = true;
this.barMainMenu.OptionsBar.UseWholeRow = true;
resources.ApplyResources(this.barMainMenu, "barMainMenu");
this.barMainMenu.Visible = false;
//
// printPreviewSubItem4
//
this.printPreviewSubItem4.AccessibleDescription = null;
this.printPreviewSubItem4.AccessibleName = null;
resources.ApplyResources(this.printPreviewSubItem4, "printPreviewSubItem4");
this.printPreviewSubItem4.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayout;
this.printPreviewSubItem4.Id = 35;
this.printPreviewSubItem4.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem27),
new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem28)});
this.printPreviewSubItem4.Name = "printPreviewSubItem4";
//
// printPreviewBarItem27
//
this.printPreviewBarItem27.AccessibleDescription = null;
this.printPreviewBarItem27.AccessibleName = null;
this.printPreviewBarItem27.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem27, "printPreviewBarItem27");
this.printPreviewBarItem27.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayoutFacing;
this.printPreviewBarItem27.Enabled = false;
this.printPreviewBarItem27.GroupIndex = 100;
this.printPreviewBarItem27.Id = 36;
this.printPreviewBarItem27.Name = "printPreviewBarItem27";
//
// printPreviewBarItem28
//
this.printPreviewBarItem28.AccessibleDescription = null;
this.printPreviewBarItem28.AccessibleName = null;
this.printPreviewBarItem28.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem28, "printPreviewBarItem28");
this.printPreviewBarItem28.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayoutContinuous;
this.printPreviewBarItem28.Enabled = false;
this.printPreviewBarItem28.GroupIndex = 100;
this.printPreviewBarItem28.Id = 37;
this.printPreviewBarItem28.Name = "printPreviewBarItem28";
//
// barToolbarsListItem1
//
this.barToolbarsListItem1.AccessibleDescription = null;
this.barToolbarsListItem1.AccessibleName = null;
resources.ApplyResources(this.barToolbarsListItem1, "barToolbarsListItem1");
this.barToolbarsListItem1.Id = 38;
this.barToolbarsListItem1.Name = "barToolbarsListItem1";
//
// biExportPdf
//
this.biExportPdf.AccessibleDescription = null;
this.biExportPdf.AccessibleName = null;
resources.ApplyResources(this.biExportPdf, "biExportPdf");
this.biExportPdf.Checked = true;
this.biExportPdf.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportPdf;
this.biExportPdf.Enabled = false;
this.biExportPdf.GroupIndex = 1;
this.biExportPdf.Id = 39;
this.biExportPdf.Name = "biExportPdf";
//
// biExportHtm
//
this.biExportHtm.AccessibleDescription = null;
this.biExportHtm.AccessibleName = null;
resources.ApplyResources(this.biExportHtm, "biExportHtm");
this.biExportHtm.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportHtm;
this.biExportHtm.Enabled = false;
this.biExportHtm.GroupIndex = 1;
this.biExportHtm.Id = 40;
this.biExportHtm.Name = "biExportHtm";
//
// biExportMht
//
this.biExportMht.AccessibleDescription = null;
this.biExportMht.AccessibleName = null;
resources.ApplyResources(this.biExportMht, "biExportMht");
this.biExportMht.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportMht;
this.biExportMht.Enabled = false;
this.biExportMht.GroupIndex = 1;
this.biExportMht.Id = 41;
this.biExportMht.Name = "biExportMht";
//
// biExportRtf
//
this.biExportRtf.AccessibleDescription = null;
this.biExportRtf.AccessibleName = null;
resources.ApplyResources(this.biExportRtf, "biExportRtf");
this.biExportRtf.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportRtf;
this.biExportRtf.Enabled = false;
this.biExportRtf.GroupIndex = 1;
this.biExportRtf.Id = 42;
this.biExportRtf.Name = "biExportRtf";
//
// biExportXls
//
this.biExportXls.AccessibleDescription = null;
this.biExportXls.AccessibleName = null;
resources.ApplyResources(this.biExportXls, "biExportXls");
this.biExportXls.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportXls;
this.biExportXls.Enabled = false;
this.biExportXls.GroupIndex = 1;
this.biExportXls.Id = 43;
this.biExportXls.Name = "biExportXls";
//
// biExportCsv
//
this.biExportCsv.AccessibleDescription = null;
this.biExportCsv.AccessibleName = null;
resources.ApplyResources(this.biExportCsv, "biExportCsv");
this.biExportCsv.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportCsv;
this.biExportCsv.Enabled = false;
this.biExportCsv.GroupIndex = 1;
this.biExportCsv.Id = 44;
this.biExportCsv.Name = "biExportCsv";
//
// biExportTxt
//
this.biExportTxt.AccessibleDescription = null;
this.biExportTxt.AccessibleName = null;
resources.ApplyResources(this.biExportTxt, "biExportTxt");
this.biExportTxt.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportTxt;
this.biExportTxt.Enabled = false;
this.biExportTxt.GroupIndex = 1;
this.biExportTxt.Id = 45;
this.biExportTxt.Name = "biExportTxt";
//
// biExportGraphic
//
this.biExportGraphic.AccessibleDescription = null;
this.biExportGraphic.AccessibleName = null;
resources.ApplyResources(this.biExportGraphic, "biExportGraphic");
this.biExportGraphic.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportGraphic;
this.biExportGraphic.Enabled = false;
this.biExportGraphic.GroupIndex = 1;
this.biExportGraphic.Id = 46;
this.biExportGraphic.Name = "biExportGraphic";
//
// printPreviewBarItem2
//
this.printPreviewBarItem2.AccessibleDescription = null;
this.printPreviewBarItem2.AccessibleName = null;
this.printPreviewBarItem2.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
resources.ApplyResources(this.printPreviewBarItem2, "printPreviewBarItem2");
this.printPreviewBarItem2.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageSetup;
this.printPreviewBarItem2.Enabled = false;
this.printPreviewBarItem2.Id = 14;
this.printPreviewBarItem2.ImageIndex = 2;
this.printPreviewBarItem2.Name = "printPreviewBarItem2";
//
// timerScroll
//
this.timerScroll.Interval = 300;
this.timerScroll.Tick += new System.EventHandler(this.timerScroll_Tick);
//
// ReportView
//
this.AccessibleDescription = null;
this.AccessibleName = null;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = null;
this.Controls.Add(this.printControlReport);
this.DoubleBuffered = true;
this.Font = null;
this.Name = "ReportView";
((System.ComponentModel.ISupportInitialize)(this.printingSystemReports)).EndInit();
this.printControlReport.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.printBarManager)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.printPreviewRepositoryItemComboBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repositoryItemProgressBar1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraPrinting.PrintingSystem printingSystemReports;
private ReportPrintControl printControlReport;
private DevExpress.XtraPrinting.Preview.PrintBarManager printBarManager;
private DevExpress.XtraPrinting.Preview.PreviewBar previewBar1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biFind;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPrint;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPrintDirect;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPageSetup;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biScale;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biHandTool;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biMagnifier;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biZoomOut;
private DevExpress.XtraPrinting.Preview.ZoomBarEditItem biZoom;
private DevExpress.XtraPrinting.Preview.PrintPreviewRepositoryItemComboBox printPreviewRepositoryItemComboBox1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem ZoomIn;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowFirstPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowPrevPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowNextPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowLastPage;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biMultiplePages;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biFillBackground;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biExportFile;
private DevExpress.XtraPrinting.Preview.PreviewBar barStatus;
private DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem biPage;
private DevExpress.XtraBars.BarStaticItem barStaticItem1;
private DevExpress.XtraPrinting.Preview.ProgressBarEditItem biProgressBar;
private DevExpress.XtraEditors.Repository.RepositoryItemProgressBar repositoryItemProgressBar1;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biStatusStatus;
private DevExpress.XtraBars.BarButtonItem barButtonItem1;
private DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem biStatusZoom;
private DevExpress.XtraPrinting.Preview.PreviewBar barMainMenu;
private DevExpress.XtraPrinting.Preview.PrintPreviewSubItem printPreviewSubItem4;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem27;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem28;
private DevExpress.XtraBars.BarToolbarsListItem barToolbarsListItem1;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportPdf;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportHtm;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportMht;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportRtf;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportXls;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportCsv;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportTxt;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportGraphic;
private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem2;
private DevExpress.XtraBars.BarButtonItem biEdit;
private DevExpress.XtraBars.BarButtonItem biLoadDefault;
private System.Windows.Forms.Timer timerScroll;
}
}
| |
#region License
/*
* Copyright 2009- Marko Lahma
*
* 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.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using Quartz.Util;
namespace Quartz.Impl.AdoJobStore.Common
{
/// <summary>
/// Concrete implementation of <see cref="IDbProvider" />.
/// </summary>
/// <author>Marko Lahma</author>
public class DbProvider : IDbProvider
{
protected const string PropertyDbProvider = StdSchedulerFactory.PropertyDbProvider;
protected const string DbProviderSectionName = StdSchedulerFactory.ConfigurationSectionName;
protected const string DbProviderResourceName = "Quartz.Impl.AdoJobStore.Common.dbproviders.properties";
private string connectionString;
private readonly DbMetadata dbMetadata;
private readonly MethodInfo commandBindByNamePropertySetter;
private static readonly IList<DbMetadataFactory> dbMetadataFactories;
private static readonly Dictionary<string, DbMetadata> dbMetadataLookup = new Dictionary<string, DbMetadata>();
/// <summary>
/// Parse metadata once in static constructor.
/// </summary>
static DbProvider()
{
dbMetadataFactories = new List<DbMetadataFactory>
{
new ConfigurationBasedDbMetadataFactory(DbProviderSectionName, PropertyDbProvider),
new EmbeddedAssemblyResourceDbMetadataFactory(DbProviderResourceName, PropertyDbProvider),
};
}
/// <summary>
/// Initializes a new instance of the <see cref="DbProvider"/> class.
/// </summary>
/// <param name="dbProviderName">Name of the db provider.</param>
/// <param name="connectionString">The connection string.</param>
public DbProvider(string dbProviderName, string connectionString)
{
this.connectionString = connectionString;
dbMetadata = GetDbMetadata(dbProviderName);
if (dbMetadata == null)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid DB provider name: {0}{1}{2}", dbProviderName, Environment.NewLine, GenerateValidProviderNamesInfo()));
}
// check if command supports direct setting of BindByName property, needed for Oracle Managed ODP diver at least
var property = dbMetadata.CommandType.GetProperty("BindByName", BindingFlags.Instance | BindingFlags.Public);
if (property != null && property.PropertyType == typeof (bool) && property.CanWrite)
{
commandBindByNamePropertySetter = property.GetSetMethod();
}
}
public void Initialize()
{
// do nothing, initialized in static constructor
}
///<summary>
/// Registers DB metadata information for given provider name.
///</summary>
///<param name="dbProviderName"></param>
///<param name="metadata"></param>
public static void RegisterDbMetadata(string dbProviderName, DbMetadata metadata)
{
dbMetadataLookup[dbProviderName] = metadata;
}
protected virtual DbMetadata GetDbMetadata(string providerName)
{
DbMetadata result;
if (!dbMetadataLookup.TryGetValue(providerName, out result))
{
foreach (var dbMetadataFactory in dbMetadataFactories)
{
if (dbMetadataFactory.GetProviderNames().Contains(providerName))
{
result = dbMetadataFactory.GetDbMetadata(providerName);
RegisterDbMetadata(providerName, result);
return result;
}
}
throw new ArgumentOutOfRangeException("providerName", "There is no metadata information for provider '" + providerName + "'");
}
return result;
}
/// <summary>
/// Generates the valid provider names information.
/// </summary>
/// <returns></returns>
protected static string GenerateValidProviderNamesInfo()
{
var providerNames = dbMetadataFactories
.SelectMany(factory => factory.GetProviderNames())
.Distinct()
.OrderBy(name => name);
StringBuilder sb = new StringBuilder("Valid DB Provider names are:").Append(Environment.NewLine);
foreach (string providerName in providerNames)
{
sb.Append("\t").Append(providerName).Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Returns a new command object for executing SQL statements/Stored Procedures
/// against the database.
/// </summary>
/// <returns>An new <see cref="IDbCommand"/></returns>
public virtual IDbCommand CreateCommand()
{
var command = ObjectUtils.InstantiateType<IDbCommand>(dbMetadata.CommandType);
if (commandBindByNamePropertySetter != null)
{
commandBindByNamePropertySetter.Invoke(command, new object[] { Metadata.BindByName });
}
return command;
}
/// <summary>
/// Returns a new instance of the providers CommandBuilder class.
/// </summary>
/// <returns>A new Command Builder</returns>
/// <remarks>In .NET 1.1 there was no common base class or interface
/// for command builders, hence the return signature is object to
/// be portable (but more loosely typed) across .NET 1.1/2.0</remarks>
public virtual object CreateCommandBuilder()
{
return ObjectUtils.InstantiateType<object>(dbMetadata.CommandBuilderType);
}
/// <summary>
/// Returns a new connection object to communicate with the database.
/// </summary>
/// <returns>A new <see cref="IDbConnection"/></returns>
public virtual IDbConnection CreateConnection()
{
IDbConnection conn = ObjectUtils.InstantiateType<IDbConnection>(dbMetadata.ConnectionType);
conn.ConnectionString = ConnectionString;
return conn;
}
/// <summary>
/// Returns a new parameter object for binding values to parameter
/// placeholders in SQL statements or Stored Procedure variables.
/// </summary>
/// <returns>A new <see cref="IDbDataParameter"/></returns>
public virtual IDbDataParameter CreateParameter()
{
return ObjectUtils.InstantiateType<IDbDataParameter>(dbMetadata.ParameterType);
}
/// <summary>
/// Connection string used to create connections.
/// </summary>
/// <value></value>
public virtual string ConnectionString
{
get { return connectionString; }
set { connectionString = value; }
}
/// <summary>
/// Gets the metadata.
/// </summary>
/// <value>The metadata.</value>
public virtual DbMetadata Metadata
{
get { return dbMetadata; }
}
/// <summary>
/// Shutdowns this instance.
/// </summary>
public virtual void Shutdown()
{
}
}
}
| |
/*
* 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.Linq;
using System.Reflection;
using System.Text;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using Mono.Addins;
using log4net;
using Nini.Config;
namespace OpenSim.Groups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsServiceHGConnectorModule")]
public class GroupsServiceHGConnectorModule : ISharedRegionModule, IGroupsServicesConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private IGroupsServicesConnector m_LocalGroupsConnector;
private string m_LocalGroupsServiceLocation;
private IUserManagement m_UserManagement;
private IOfflineIMService m_OfflineIM;
private IMessageTransferModule m_Messaging;
private List<Scene> m_Scenes;
private ForeignImporter m_ForeignImporter;
private string m_ServiceLocation;
private IConfigSource m_Config;
private Dictionary<string, GroupsServiceHGConnector> m_NetworkConnectors = new Dictionary<string, GroupsServiceHGConnector>();
private RemoteConnectorCacheWrapper m_CacheWrapper; // for caching info of external group services
#region ISharedRegionModule
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
return;
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("ServicesConnectorModule", string.Empty) != Name))
{
return;
}
m_Config = config;
m_ServiceLocation = groupsConfig.GetString("LocalService", "local"); // local or remote
m_LocalGroupsServiceLocation = groupsConfig.GetString("GroupsExternalURI", "http://127.0.0.1");
m_Scenes = new List<Scene>();
m_Enabled = true;
m_log.DebugFormat("[Groups]: Initializing {0} with LocalService {1}", this.Name, m_ServiceLocation);
}
public string Name
{
get { return "Groups HG Service Connector"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_log.DebugFormat("[Groups]: Registering {0} with {1}", this.Name, scene.RegionInfo.RegionName);
scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
m_Scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
m_Scenes.Remove(scene);
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
if (m_UserManagement == null)
{
m_UserManagement = scene.RequestModuleInterface<IUserManagement>();
m_OfflineIM = scene.RequestModuleInterface<IOfflineIMService>();
m_Messaging = scene.RequestModuleInterface<IMessageTransferModule>();
m_ForeignImporter = new ForeignImporter(m_UserManagement);
if (m_ServiceLocation.Equals("local"))
{
m_LocalGroupsConnector = new GroupsServiceLocalConnectorModule(m_Config, m_UserManagement);
// Also, if local, create the endpoint for the HGGroupsService
new HGGroupsServiceRobustConnector(m_Config, MainServer.Instance, string.Empty,
scene.RequestModuleInterface<IOfflineIMService>(), scene.RequestModuleInterface<IUserAccountService>());
}
else
m_LocalGroupsConnector = new GroupsServiceRemoteConnectorModule(m_Config, m_UserManagement);
m_CacheWrapper = new RemoteConnectorCacheWrapper(m_UserManagement);
}
}
public void PostInitialise()
{
}
public void Close()
{
}
#endregion
private void OnNewClient(IClientAPI client)
{
client.OnCompleteMovementToRegion += OnCompleteMovementToRegion;
}
void OnCompleteMovementToRegion(IClientAPI client, bool arg2)
{
object sp = null;
if (client.Scene.TryGetScenePresence(client.AgentId, out sp))
{
if (sp is ScenePresence && ((ScenePresence)sp).PresenceType != PresenceType.Npc)
{
AgentCircuitData aCircuit = ((ScenePresence)sp).Scene.AuthenticateHandler.GetAgentCircuitData(client.AgentId);
if (aCircuit != null && (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0 &&
m_OfflineIM != null && m_Messaging != null)
{
List<GridInstantMessage> ims = m_OfflineIM.GetMessages(aCircuit.AgentID);
if (ims != null && ims.Count > 0)
foreach (GridInstantMessage im in ims)
m_Messaging.SendInstantMessage(im, delegate(bool success) { });
}
}
}
}
#region IGroupsServicesConnector
public UUID CreateGroup(UUID RequestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish, UUID founderID, out string reason)
{
reason = string.Empty;
if (m_UserManagement.IsLocalGridUser(RequestingAgentID))
return m_LocalGroupsConnector.CreateGroup(RequestingAgentID, name, charter, showInList, insigniaID,
membershipFee, openEnrollment, allowPublish, maturePublish, founderID, out reason);
else
{
reason = "Only local grid users are allowed to create a new group";
return UUID.Zero;
}
}
public bool UpdateGroup(string RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee,
bool openEnrollment, bool allowPublish, bool maturePublish, out string reason)
{
reason = string.Empty;
string url = string.Empty;
string name = string.Empty;
if (IsLocal(groupID, out url, out name))
return m_LocalGroupsConnector.UpdateGroup(AgentUUI(RequestingAgentID), groupID, charter, showInList, insigniaID, membershipFee,
openEnrollment, allowPublish, maturePublish, out reason);
else
{
reason = "Changes to remote group not allowed. Please go to the group's original world.";
return false;
}
}
public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID, string GroupName)
{
string url = string.Empty;
string name = string.Empty;
if (IsLocal(GroupID, out url, out name))
return m_LocalGroupsConnector.GetGroupRecord(AgentUUI(RequestingAgentID), GroupID, GroupName);
else if (url != string.Empty)
{
ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(RequestingAgentID, RequestingAgentID, GroupID);
string accessToken = string.Empty;
if (membership != null)
accessToken = membership.AccessToken;
else
return null;
GroupsServiceHGConnector c = GetConnector(url);
if (c != null)
{
ExtendedGroupRecord grec = m_CacheWrapper.GetGroupRecord(RequestingAgentID, GroupID, GroupName, delegate
{
return c.GetGroupRecord(AgentUUIForOutside(RequestingAgentID), GroupID, GroupName, accessToken);
});
if (grec != null)
ImportForeigner(grec.FounderUUI);
return grec;
}
}
return null;
}
public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
{
return m_LocalGroupsConnector.FindGroups(AgentUUI(RequestingAgentID), search);
}
public List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(GroupID, out url, out gname))
{
string agentID = AgentUUI(RequestingAgentID);
return m_LocalGroupsConnector.GetGroupMembers(agentID, GroupID);
}
else if (!string.IsNullOrEmpty(url))
{
ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(RequestingAgentID, RequestingAgentID, GroupID);
string accessToken = string.Empty;
if (membership != null)
accessToken = membership.AccessToken;
else
return null;
GroupsServiceHGConnector c = GetConnector(url);
if (c != null)
{
return m_CacheWrapper.GetGroupMembers(RequestingAgentID, GroupID, delegate
{
return c.GetGroupMembers(AgentUUIForOutside(RequestingAgentID), GroupID, accessToken);
});
}
}
return new List<GroupMembersData>();
}
public bool AddGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, out string reason)
{
reason = string.Empty;
string url = string.Empty, gname = string.Empty;
if (IsLocal(groupID, out url, out gname))
return m_LocalGroupsConnector.AddGroupRole(AgentUUI(RequestingAgentID), groupID, roleID, name, description, title, powers, out reason);
else
{
reason = "Operation not allowed outside this group's origin world.";
return false;
}
}
public bool UpdateGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(groupID, out url, out gname))
return m_LocalGroupsConnector.UpdateGroupRole(AgentUUI(RequestingAgentID), groupID, roleID, name, description, title, powers);
else
{
return false;
}
}
public void RemoveGroupRole(string RequestingAgentID, UUID groupID, UUID roleID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(groupID, out url, out gname))
m_LocalGroupsConnector.RemoveGroupRole(AgentUUI(RequestingAgentID), groupID, roleID);
else
{
return;
}
}
public List<GroupRolesData> GetGroupRoles(string RequestingAgentID, UUID groupID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(groupID, out url, out gname))
return m_LocalGroupsConnector.GetGroupRoles(AgentUUI(RequestingAgentID), groupID);
else if (!string.IsNullOrEmpty(url))
{
ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(RequestingAgentID, RequestingAgentID, groupID);
string accessToken = string.Empty;
if (membership != null)
accessToken = membership.AccessToken;
else
return null;
GroupsServiceHGConnector c = GetConnector(url);
if (c != null)
{
return m_CacheWrapper.GetGroupRoles(RequestingAgentID, groupID, delegate
{
return c.GetGroupRoles(AgentUUIForOutside(RequestingAgentID), groupID, accessToken);
});
}
}
return new List<GroupRolesData>();
}
public List<GroupRoleMembersData> GetGroupRoleMembers(string RequestingAgentID, UUID groupID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(groupID, out url, out gname))
return m_LocalGroupsConnector.GetGroupRoleMembers(AgentUUI(RequestingAgentID), groupID);
else if (!string.IsNullOrEmpty(url))
{
ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(RequestingAgentID, RequestingAgentID, groupID);
string accessToken = string.Empty;
if (membership != null)
accessToken = membership.AccessToken;
else
return null;
GroupsServiceHGConnector c = GetConnector(url);
if (c != null)
{
return m_CacheWrapper.GetGroupRoleMembers(RequestingAgentID, groupID, delegate
{
return c.GetGroupRoleMembers(AgentUUIForOutside(RequestingAgentID), groupID, accessToken);
});
}
}
return new List<GroupRoleMembersData>();
}
public bool AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string token, out string reason)
{
string url = string.Empty;
string name = string.Empty;
reason = string.Empty;
UUID uid = new UUID(AgentID);
if (IsLocal(GroupID, out url, out name))
{
if (m_UserManagement.IsLocalGridUser(uid)) // local user
{
// normal case: local group, local user
return m_LocalGroupsConnector.AddAgentToGroup(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID, token, out reason);
}
else // local group, foreign user
{
// the user is accepting the invitation, or joining, where the group resides
token = UUID.Random().ToString();
bool success = m_LocalGroupsConnector.AddAgentToGroup(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID, token, out reason);
if (success)
{
// Here we always return true. The user has been added to the local group,
// independent of whether the remote operation succeeds or not
url = m_UserManagement.GetUserServerURL(uid, "GroupsServerURI");
if (url == string.Empty)
{
reason = "You don't have an accessible groups server in your home world. You membership to this group in only within this grid.";
return true;
}
GroupsServiceHGConnector c = GetConnector(url);
if (c != null)
c.CreateProxy(AgentUUI(RequestingAgentID), AgentID, token, GroupID, m_LocalGroupsServiceLocation, name, out reason);
return true;
}
return false;
}
}
else if (m_UserManagement.IsLocalGridUser(uid)) // local user
{
// foreign group, local user. She's been added already by the HG service.
// Let's just check
if (m_LocalGroupsConnector.GetAgentGroupMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID) != null)
return true;
}
reason = "Operation not allowed outside this group's origin world";
return false;
}
public void RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
string url = string.Empty, name = string.Empty;
if (!IsLocal(GroupID, out url, out name) && url != string.Empty)
{
ExtendedGroupMembershipData membership = m_LocalGroupsConnector.GetAgentGroupMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID);
if (membership != null)
{
GroupsServiceHGConnector c = GetConnector(url);
if (c != null)
c.RemoveAgentFromGroup(AgentUUIForOutside(AgentID), GroupID, membership.AccessToken);
}
}
// remove from local service
m_LocalGroupsConnector.RemoveAgentFromGroup(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID);
}
public bool AddAgentToGroupInvite(string RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID, string agentID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(groupID, out url, out gname))
return m_LocalGroupsConnector.AddAgentToGroupInvite(AgentUUI(RequestingAgentID), inviteID, groupID, roleID, AgentUUI(agentID));
else
return false;
}
public GroupInviteInfo GetAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
{
return m_LocalGroupsConnector.GetAgentToGroupInvite(AgentUUI(RequestingAgentID), inviteID); ;
}
public void RemoveAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
{
m_LocalGroupsConnector.RemoveAgentToGroupInvite(AgentUUI(RequestingAgentID), inviteID);
}
public void AddAgentToGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(GroupID, out url, out gname))
m_LocalGroupsConnector.AddAgentToGroupRole(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID);
}
public void RemoveAgentFromGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(GroupID, out url, out gname))
m_LocalGroupsConnector.RemoveAgentFromGroupRole(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID);
}
public List<GroupRolesData> GetAgentGroupRoles(string RequestingAgentID, string AgentID, UUID GroupID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(GroupID, out url, out gname))
return m_LocalGroupsConnector.GetAgentGroupRoles(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID);
else
return new List<GroupRolesData>();
}
public void SetAgentActiveGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(GroupID, out url, out gname))
m_LocalGroupsConnector.SetAgentActiveGroup(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID);
}
public ExtendedGroupMembershipData GetAgentActiveMembership(string RequestingAgentID, string AgentID)
{
return m_LocalGroupsConnector.GetAgentActiveMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID));
}
public void SetAgentActiveGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(GroupID, out url, out gname))
m_LocalGroupsConnector.SetAgentActiveGroupRole(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, RoleID);
}
public void UpdateMembership(string RequestingAgentID, string AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile)
{
m_LocalGroupsConnector.UpdateMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID, AcceptNotices, ListInProfile);
}
public ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(GroupID, out url, out gname))
return m_LocalGroupsConnector.GetAgentGroupMembership(AgentUUI(RequestingAgentID), AgentUUI(AgentID), GroupID);
else
return null;
}
public List<GroupMembershipData> GetAgentGroupMemberships(string RequestingAgentID, string AgentID)
{
return m_LocalGroupsConnector.GetAgentGroupMemberships(AgentUUI(RequestingAgentID), AgentUUI(AgentID));
}
public bool AddGroupNotice(string RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message,
bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID)
{
string url = string.Empty, gname = string.Empty;
if (IsLocal(groupID, out url, out gname))
{
if (m_LocalGroupsConnector.AddGroupNotice(AgentUUI(RequestingAgentID), groupID, noticeID, fromName, subject, message,
hasAttachment, attType, attName, attItemID, AgentUUI(attOwnerID)))
{
// then send the notice to every grid for which there are members in this group
List<GroupMembersData> members = m_LocalGroupsConnector.GetGroupMembers(AgentUUI(RequestingAgentID), groupID);
List<string> urls = new List<string>();
foreach (GroupMembersData m in members)
{
if (!m_UserManagement.IsLocalGridUser(m.AgentID))
{
string gURL = m_UserManagement.GetUserServerURL(m.AgentID, "GroupsServerURI");
if (!urls.Contains(gURL))
urls.Add(gURL);
}
}
// so we have the list of urls to send the notice to
// this may take a long time...
Util.RunThreadNoTimeout(delegate
{
foreach (string u in urls)
{
GroupsServiceHGConnector c = GetConnector(u);
if (c != null)
{
c.AddNotice(AgentUUIForOutside(RequestingAgentID), groupID, noticeID, fromName, subject, message,
hasAttachment, attType, attName, attItemID, AgentUUIForOutside(attOwnerID));
}
}
}, "AddGroupNotice", null);
return true;
}
return false;
}
else
return false;
}
public GroupNoticeInfo GetGroupNotice(string RequestingAgentID, UUID noticeID)
{
GroupNoticeInfo notice = m_LocalGroupsConnector.GetGroupNotice(AgentUUI(RequestingAgentID), noticeID);
if (notice != null && notice.noticeData.HasAttachment && notice.noticeData.AttachmentOwnerID != null)
ImportForeigner(notice.noticeData.AttachmentOwnerID);
return notice;
}
public List<ExtendedGroupNoticeData> GetGroupNotices(string RequestingAgentID, UUID GroupID)
{
return m_LocalGroupsConnector.GetGroupNotices(AgentUUI(RequestingAgentID), GroupID);
}
#endregion
#region hypergrid groups
private string AgentUUI(string AgentIDStr)
{
UUID AgentID = UUID.Zero;
try
{
AgentID = new UUID(AgentIDStr);
}
catch (FormatException)
{
return AgentID.ToString();
}
if (m_UserManagement.IsLocalGridUser(AgentID))
return AgentID.ToString();
AgentCircuitData agent = null;
foreach (Scene scene in m_Scenes)
{
agent = scene.AuthenticateHandler.GetAgentCircuitData(AgentID);
if (agent != null)
break;
}
if (agent != null)
return Util.ProduceUserUniversalIdentifier(agent);
// we don't know anything about this foreign user
// try asking the user management module, which may know more
return m_UserManagement.GetUserUUI(AgentID);
}
private string AgentUUIForOutside(string AgentIDStr)
{
UUID AgentID = UUID.Zero;
try
{
AgentID = new UUID(AgentIDStr);
}
catch (FormatException)
{
return AgentID.ToString();
}
AgentCircuitData agent = null;
foreach (Scene scene in m_Scenes)
{
agent = scene.AuthenticateHandler.GetAgentCircuitData(AgentID);
if (agent != null)
break;
}
if (agent == null) // oops
return AgentID.ToString();
return Util.ProduceUserUniversalIdentifier(agent);
}
private UUID ImportForeigner(string uID)
{
UUID userID = UUID.Zero;
string url = string.Empty, first = string.Empty, last = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uID, out userID, out url, out first, out last, out tmp))
m_UserManagement.AddUser(userID, first, last, url);
return userID;
}
private bool IsLocal(UUID groupID, out string serviceLocation, out string name)
{
serviceLocation = string.Empty;
name = string.Empty;
if (groupID.Equals(UUID.Zero))
return true;
ExtendedGroupRecord group = m_LocalGroupsConnector.GetGroupRecord(UUID.Zero.ToString(), groupID, string.Empty);
if (group == null)
{
//m_log.DebugFormat("[XXX]: IsLocal? group {0} not found -- no.", groupID);
return false;
}
serviceLocation = group.ServiceLocation;
name = group.GroupName;
bool isLocal = (group.ServiceLocation == string.Empty);
//m_log.DebugFormat("[XXX]: IsLocal? {0}", isLocal);
return isLocal;
}
private GroupsServiceHGConnector GetConnector(string url)
{
lock (m_NetworkConnectors)
{
if (m_NetworkConnectors.ContainsKey(url))
return m_NetworkConnectors[url];
GroupsServiceHGConnector c = new GroupsServiceHGConnector(url);
m_NetworkConnectors[url] = c;
}
return m_NetworkConnectors[url];
}
#endregion
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Compute.V1
{
/// <summary>Settings for <see cref="GlobalAddressesClient"/> instances.</summary>
public sealed partial class GlobalAddressesSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="GlobalAddressesSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="GlobalAddressesSettings"/>.</returns>
public static GlobalAddressesSettings GetDefault() => new GlobalAddressesSettings();
/// <summary>Constructs a new <see cref="GlobalAddressesSettings"/> object with default settings.</summary>
public GlobalAddressesSettings()
{
}
private GlobalAddressesSettings(GlobalAddressesSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
DeleteSettings = existing.DeleteSettings;
DeleteOperationsSettings = existing.DeleteOperationsSettings.Clone();
GetSettings = existing.GetSettings;
InsertSettings = existing.InsertSettings;
InsertOperationsSettings = existing.InsertOperationsSettings.Clone();
ListSettings = existing.ListSettings;
OnCopy(existing);
}
partial void OnCopy(GlobalAddressesSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GlobalAddressesClient.Delete</c> and <c>GlobalAddressesClient.DeleteAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// Long Running Operation settings for calls to <c>GlobalAddressesClient.Delete</c> and
/// <c>GlobalAddressesClient.DeleteAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings DeleteOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>GlobalAddressesClient.Get</c>
/// and <c>GlobalAddressesClient.GetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>GlobalAddressesClient.Insert</c> and <c>GlobalAddressesClient.InsertAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings InsertSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// Long Running Operation settings for calls to <c>GlobalAddressesClient.Insert</c> and
/// <c>GlobalAddressesClient.InsertAsync</c>.
/// </summary>
/// <remarks>
/// Uses default <see cref="gax::PollSettings"/> of:
/// <list type="bullet">
/// <item><description>Initial delay: 20 seconds.</description></item>
/// <item><description>Delay multiplier: 1.5</description></item>
/// <item><description>Maximum delay: 45 seconds.</description></item>
/// <item><description>Total timeout: 24 hours.</description></item>
/// </list>
/// </remarks>
public lro::OperationsSettings InsertOperationsSettings { get; set; } = new lro::OperationsSettings
{
DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)),
};
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>GlobalAddressesClient.List</c>
/// and <c>GlobalAddressesClient.ListAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="GlobalAddressesSettings"/> object.</returns>
public GlobalAddressesSettings Clone() => new GlobalAddressesSettings(this);
}
/// <summary>
/// Builder class for <see cref="GlobalAddressesClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class GlobalAddressesClientBuilder : gaxgrpc::ClientBuilderBase<GlobalAddressesClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public GlobalAddressesSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public GlobalAddressesClientBuilder()
{
UseJwtAccessWithScopes = GlobalAddressesClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref GlobalAddressesClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<GlobalAddressesClient> task);
/// <summary>Builds the resulting client.</summary>
public override GlobalAddressesClient Build()
{
GlobalAddressesClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<GlobalAddressesClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<GlobalAddressesClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private GlobalAddressesClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return GlobalAddressesClient.Create(callInvoker, Settings);
}
private async stt::Task<GlobalAddressesClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return GlobalAddressesClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => GlobalAddressesClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => GlobalAddressesClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => GlobalAddressesClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter;
}
/// <summary>GlobalAddresses client wrapper, for convenient use.</summary>
/// <remarks>
/// The GlobalAddresses API.
/// </remarks>
public abstract partial class GlobalAddressesClient
{
/// <summary>
/// The default endpoint for the GlobalAddresses service, which is a host of "compute.googleapis.com" and a port
/// of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "compute.googleapis.com:443";
/// <summary>The default GlobalAddresses scopes.</summary>
/// <remarks>
/// The default GlobalAddresses scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/compute</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="GlobalAddressesClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="GlobalAddressesClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="GlobalAddressesClient"/>.</returns>
public static stt::Task<GlobalAddressesClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new GlobalAddressesClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="GlobalAddressesClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="GlobalAddressesClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="GlobalAddressesClient"/>.</returns>
public static GlobalAddressesClient Create() => new GlobalAddressesClientBuilder().Build();
/// <summary>
/// Creates a <see cref="GlobalAddressesClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="GlobalAddressesSettings"/>.</param>
/// <returns>The created <see cref="GlobalAddressesClient"/>.</returns>
internal static GlobalAddressesClient Create(grpccore::CallInvoker callInvoker, GlobalAddressesSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
GlobalAddresses.GlobalAddressesClient grpcClient = new GlobalAddresses.GlobalAddressesClient(callInvoker);
return new GlobalAddressesClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC GlobalAddresses client</summary>
public virtual GlobalAddresses.GlobalAddressesClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified address resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Operation, Operation> Delete(DeleteGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified address resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified address resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteGlobalAddressRequest request, st::CancellationToken cancellationToken) =>
DeleteAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>Delete</c>.</summary>
public virtual lro::OperationsClient DeleteOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Delete</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<Operation, Operation> PollOnceDelete(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Operation, Operation>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Delete</c>
/// .
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> PollOnceDeleteAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Operation, Operation>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), DeleteOperationsClient, callSettings);
/// <summary>
/// Deletes the specified address resource.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="address">
/// Name of the address resource to delete.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Operation, Operation> Delete(string project, string address, gaxgrpc::CallSettings callSettings = null) =>
Delete(new DeleteGlobalAddressRequest
{
Address = gax::GaxPreconditions.CheckNotNullOrEmpty(address, nameof(address)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
}, callSettings);
/// <summary>
/// Deletes the specified address resource.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="address">
/// Name of the address resource to delete.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(string project, string address, gaxgrpc::CallSettings callSettings = null) =>
DeleteAsync(new DeleteGlobalAddressRequest
{
Address = gax::GaxPreconditions.CheckNotNullOrEmpty(address, nameof(address)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
}, callSettings);
/// <summary>
/// Deletes the specified address resource.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="address">
/// Name of the address resource to delete.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(string project, string address, st::CancellationToken cancellationToken) =>
DeleteAsync(project, address, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the specified address resource. Gets a list of available addresses by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Address Get(GetGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified address resource. Gets a list of available addresses by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Address> GetAsync(GetGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified address resource. Gets a list of available addresses by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Address> GetAsync(GetGlobalAddressRequest request, st::CancellationToken cancellationToken) =>
GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the specified address resource. Gets a list of available addresses by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="address">
/// Name of the address resource to return.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Address Get(string project, string address, gaxgrpc::CallSettings callSettings = null) =>
Get(new GetGlobalAddressRequest
{
Address = gax::GaxPreconditions.CheckNotNullOrEmpty(address, nameof(address)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
}, callSettings);
/// <summary>
/// Returns the specified address resource. Gets a list of available addresses by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="address">
/// Name of the address resource to return.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Address> GetAsync(string project, string address, gaxgrpc::CallSettings callSettings = null) =>
GetAsync(new GetGlobalAddressRequest
{
Address = gax::GaxPreconditions.CheckNotNullOrEmpty(address, nameof(address)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
}, callSettings);
/// <summary>
/// Returns the specified address resource. Gets a list of available addresses by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="address">
/// Name of the address resource to return.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Address> GetAsync(string project, string address, st::CancellationToken cancellationToken) =>
GetAsync(project, address, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates an address resource in the specified project by using the data included in the request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Operation, Operation> Insert(InsertGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an address resource in the specified project by using the data included in the request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an address resource in the specified project by using the data included in the request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertGlobalAddressRequest request, st::CancellationToken cancellationToken) =>
InsertAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>The long-running operations client for <c>Insert</c>.</summary>
public virtual lro::OperationsClient InsertOperationsClient => throw new sys::NotImplementedException();
/// <summary>
/// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Insert</c>.
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The result of polling the operation.</returns>
public virtual lro::Operation<Operation, Operation> PollOnceInsert(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Operation, Operation>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), InsertOperationsClient, callSettings);
/// <summary>
/// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>Insert</c>
/// .
/// </summary>
/// <param name="operationName">
/// The name of a previously invoked operation. Must not be <c>null</c> or empty.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A task representing the result of polling the operation.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> PollOnceInsertAsync(string operationName, gaxgrpc::CallSettings callSettings = null) =>
lro::Operation<Operation, Operation>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), InsertOperationsClient, callSettings);
/// <summary>
/// Creates an address resource in the specified project by using the data included in the request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="addressResource">
/// The body resource for this request
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual lro::Operation<Operation, Operation> Insert(string project, Address addressResource, gaxgrpc::CallSettings callSettings = null) =>
Insert(new InsertGlobalAddressRequest
{
AddressResource = gax::GaxPreconditions.CheckNotNull(addressResource, nameof(addressResource)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
}, callSettings);
/// <summary>
/// Creates an address resource in the specified project by using the data included in the request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="addressResource">
/// The body resource for this request
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(string project, Address addressResource, gaxgrpc::CallSettings callSettings = null) =>
InsertAsync(new InsertGlobalAddressRequest
{
AddressResource = gax::GaxPreconditions.CheckNotNull(addressResource, nameof(addressResource)),
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
}, callSettings);
/// <summary>
/// Creates an address resource in the specified project by using the data included in the request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="addressResource">
/// The body resource for this request
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<lro::Operation<Operation, Operation>> InsertAsync(string project, Address addressResource, st::CancellationToken cancellationToken) =>
InsertAsync(project, addressResource, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Retrieves a list of global addresses.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Address"/> resources.</returns>
public virtual gax::PagedEnumerable<AddressList, Address> List(ListGlobalAddressesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves a list of global addresses.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Address"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<AddressList, Address> ListAsync(ListGlobalAddressesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves a list of global addresses.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Address"/> resources.</returns>
public virtual gax::PagedEnumerable<AddressList, Address> List(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
List(new ListGlobalAddressesRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Retrieves a list of global addresses.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Address"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<AddressList, Address> ListAsync(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListAsync(new ListGlobalAddressesRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
}
/// <summary>GlobalAddresses client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// The GlobalAddresses API.
/// </remarks>
public sealed partial class GlobalAddressesClientImpl : GlobalAddressesClient
{
private readonly gaxgrpc::ApiCall<DeleteGlobalAddressRequest, Operation> _callDelete;
private readonly gaxgrpc::ApiCall<GetGlobalAddressRequest, Address> _callGet;
private readonly gaxgrpc::ApiCall<InsertGlobalAddressRequest, Operation> _callInsert;
private readonly gaxgrpc::ApiCall<ListGlobalAddressesRequest, AddressList> _callList;
/// <summary>
/// Constructs a client wrapper for the GlobalAddresses service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="GlobalAddressesSettings"/> used within this client.</param>
public GlobalAddressesClientImpl(GlobalAddresses.GlobalAddressesClient grpcClient, GlobalAddressesSettings settings)
{
GrpcClient = grpcClient;
GlobalAddressesSettings effectiveSettings = settings ?? GlobalAddressesSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
DeleteOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClientForGlobalOperations(), effectiveSettings.DeleteOperationsSettings);
InsertOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClientForGlobalOperations(), effectiveSettings.InsertOperationsSettings);
_callDelete = clientHelper.BuildApiCall<DeleteGlobalAddressRequest, Operation>(grpcClient.DeleteAsync, grpcClient.Delete, effectiveSettings.DeleteSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("address", request => request.Address);
Modify_ApiCall(ref _callDelete);
Modify_DeleteApiCall(ref _callDelete);
_callGet = clientHelper.BuildApiCall<GetGlobalAddressRequest, Address>(grpcClient.GetAsync, grpcClient.Get, effectiveSettings.GetSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("address", request => request.Address);
Modify_ApiCall(ref _callGet);
Modify_GetApiCall(ref _callGet);
_callInsert = clientHelper.BuildApiCall<InsertGlobalAddressRequest, Operation>(grpcClient.InsertAsync, grpcClient.Insert, effectiveSettings.InsertSettings).WithGoogleRequestParam("project", request => request.Project);
Modify_ApiCall(ref _callInsert);
Modify_InsertApiCall(ref _callInsert);
_callList = clientHelper.BuildApiCall<ListGlobalAddressesRequest, AddressList>(grpcClient.ListAsync, grpcClient.List, effectiveSettings.ListSettings).WithGoogleRequestParam("project", request => request.Project);
Modify_ApiCall(ref _callList);
Modify_ListApiCall(ref _callList);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_DeleteApiCall(ref gaxgrpc::ApiCall<DeleteGlobalAddressRequest, Operation> call);
partial void Modify_GetApiCall(ref gaxgrpc::ApiCall<GetGlobalAddressRequest, Address> call);
partial void Modify_InsertApiCall(ref gaxgrpc::ApiCall<InsertGlobalAddressRequest, Operation> call);
partial void Modify_ListApiCall(ref gaxgrpc::ApiCall<ListGlobalAddressesRequest, AddressList> call);
partial void OnConstruction(GlobalAddresses.GlobalAddressesClient grpcClient, GlobalAddressesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC GlobalAddresses client</summary>
public override GlobalAddresses.GlobalAddressesClient GrpcClient { get; }
partial void Modify_DeleteGlobalAddressRequest(ref DeleteGlobalAddressRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetGlobalAddressRequest(ref GetGlobalAddressRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_InsertGlobalAddressRequest(ref InsertGlobalAddressRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListGlobalAddressesRequest(ref ListGlobalAddressesRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>The long-running operations client for <c>Delete</c>.</summary>
public override lro::OperationsClient DeleteOperationsClient { get; }
/// <summary>
/// Deletes the specified address resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<Operation, Operation> Delete(DeleteGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteGlobalAddressRequest(ref request, ref callSettings);
Operation response = _callDelete.Sync(request, callSettings);
GetGlobalOperationRequest pollRequest = GetGlobalOperationRequest.FromInitialResponse(response);
request.PopulatePollRequestFields(pollRequest);
return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), DeleteOperationsClient);
}
/// <summary>
/// Deletes the specified address resource.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<Operation, Operation>> DeleteAsync(DeleteGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteGlobalAddressRequest(ref request, ref callSettings);
Operation response = await _callDelete.Async(request, callSettings).ConfigureAwait(false);
GetGlobalOperationRequest pollRequest = GetGlobalOperationRequest.FromInitialResponse(response);
request.PopulatePollRequestFields(pollRequest);
return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), DeleteOperationsClient);
}
/// <summary>
/// Returns the specified address resource. Gets a list of available addresses by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Address Get(GetGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetGlobalAddressRequest(ref request, ref callSettings);
return _callGet.Sync(request, callSettings);
}
/// <summary>
/// Returns the specified address resource. Gets a list of available addresses by making a list() request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Address> GetAsync(GetGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetGlobalAddressRequest(ref request, ref callSettings);
return _callGet.Async(request, callSettings);
}
/// <summary>The long-running operations client for <c>Insert</c>.</summary>
public override lro::OperationsClient InsertOperationsClient { get; }
/// <summary>
/// Creates an address resource in the specified project by using the data included in the request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override lro::Operation<Operation, Operation> Insert(InsertGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_InsertGlobalAddressRequest(ref request, ref callSettings);
Operation response = _callInsert.Sync(request, callSettings);
GetGlobalOperationRequest pollRequest = GetGlobalOperationRequest.FromInitialResponse(response);
request.PopulatePollRequestFields(pollRequest);
return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), InsertOperationsClient);
}
/// <summary>
/// Creates an address resource in the specified project by using the data included in the request.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override async stt::Task<lro::Operation<Operation, Operation>> InsertAsync(InsertGlobalAddressRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_InsertGlobalAddressRequest(ref request, ref callSettings);
Operation response = await _callInsert.Async(request, callSettings).ConfigureAwait(false);
GetGlobalOperationRequest pollRequest = GetGlobalOperationRequest.FromInitialResponse(response);
request.PopulatePollRequestFields(pollRequest);
return new lro::Operation<Operation, Operation>(response.ToLroResponse(pollRequest.ToLroOperationName()), InsertOperationsClient);
}
/// <summary>
/// Retrieves a list of global addresses.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Address"/> resources.</returns>
public override gax::PagedEnumerable<AddressList, Address> List(ListGlobalAddressesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListGlobalAddressesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListGlobalAddressesRequest, AddressList, Address>(_callList, request, callSettings);
}
/// <summary>
/// Retrieves a list of global addresses.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Address"/> resources.</returns>
public override gax::PagedAsyncEnumerable<AddressList, Address> ListAsync(ListGlobalAddressesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListGlobalAddressesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListGlobalAddressesRequest, AddressList, Address>(_callList, request, callSettings);
}
}
public partial class ListGlobalAddressesRequest : gaxgrpc::IPageRequest
{
/// <inheritdoc/>
public int PageSize
{
get => checked((int)MaxResults);
set => MaxResults = checked((uint)value);
}
}
public static partial class GlobalAddresses
{
public partial class GlobalAddressesClient
{
/// <summary>
/// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as
/// this client, delegating to GlobalOperations.
/// </summary>
/// <returns>A new Operations client for the same target as this client.</returns>
public virtual lro::Operations.OperationsClient CreateOperationsClientForGlobalOperations() =>
GlobalOperations.GlobalOperationsClient.CreateOperationsClient(CallInvoker);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcgv = Google.Cloud.Gaming.V1Beta;
using sys = System;
namespace Google.Cloud.Gaming.V1Beta
{
/// <summary>Resource name for the <c>Realm</c> resource.</summary>
public sealed partial class RealmName : gax::IResourceName, sys::IEquatable<RealmName>
{
/// <summary>The possible contents of <see cref="RealmName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/realms/{realm}</c>.
/// </summary>
ProjectLocationRealm = 1,
}
private static gax::PathTemplate s_projectLocationRealm = new gax::PathTemplate("projects/{project}/locations/{location}/realms/{realm}");
/// <summary>Creates a <see cref="RealmName"/> 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="RealmName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static RealmName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RealmName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="RealmName"/> with the pattern <c>projects/{project}/locations/{location}/realms/{realm}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="realmId">The <c>Realm</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RealmName"/> constructed from the provided ids.</returns>
public static RealmName FromProjectLocationRealm(string projectId, string locationId, string realmId) =>
new RealmName(ResourceNameType.ProjectLocationRealm, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), realmId: gax::GaxPreconditions.CheckNotNullOrEmpty(realmId, nameof(realmId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RealmName"/> with pattern
/// <c>projects/{project}/locations/{location}/realms/{realm}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="realmId">The <c>Realm</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RealmName"/> with pattern
/// <c>projects/{project}/locations/{location}/realms/{realm}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string realmId) =>
FormatProjectLocationRealm(projectId, locationId, realmId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RealmName"/> with pattern
/// <c>projects/{project}/locations/{location}/realms/{realm}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="realmId">The <c>Realm</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RealmName"/> with pattern
/// <c>projects/{project}/locations/{location}/realms/{realm}</c>.
/// </returns>
public static string FormatProjectLocationRealm(string projectId, string locationId, string realmId) =>
s_projectLocationRealm.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(realmId, nameof(realmId)));
/// <summary>Parses the given resource name string into a new <see cref="RealmName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/realms/{realm}</c></description></item>
/// </list>
/// </remarks>
/// <param name="realmName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RealmName"/> if successful.</returns>
public static RealmName Parse(string realmName) => Parse(realmName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RealmName"/> 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>projects/{project}/locations/{location}/realms/{realm}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="realmName">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="RealmName"/> if successful.</returns>
public static RealmName Parse(string realmName, bool allowUnparsed) =>
TryParse(realmName, allowUnparsed, out RealmName 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="RealmName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/realms/{realm}</c></description></item>
/// </list>
/// </remarks>
/// <param name="realmName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RealmName"/>, 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 realmName, out RealmName result) => TryParse(realmName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RealmName"/> 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>projects/{project}/locations/{location}/realms/{realm}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="realmName">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="RealmName"/>, 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 realmName, bool allowUnparsed, out RealmName result)
{
gax::GaxPreconditions.CheckNotNull(realmName, nameof(realmName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationRealm.TryParseName(realmName, out resourceName))
{
result = FromProjectLocationRealm(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(realmName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RealmName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string realmId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
RealmId = realmId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RealmName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/realms/{realm}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="realmId">The <c>Realm</c> ID. Must not be <c>null</c> or empty.</param>
public RealmName(string projectId, string locationId, string realmId) : this(ResourceNameType.ProjectLocationRealm, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), realmId: gax::GaxPreconditions.CheckNotNullOrEmpty(realmId, nameof(realmId)))
{
}
/// <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>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Realm</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RealmId { 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.ProjectLocationRealm: return s_projectLocationRealm.Expand(ProjectId, LocationId, RealmId);
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 RealmName);
/// <inheritdoc/>
public bool Equals(RealmName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RealmName a, RealmName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RealmName a, RealmName b) => !(a == b);
}
public partial class ListRealmsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetRealmRequest
{
/// <summary>
/// <see cref="gcgv::RealmName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::RealmName RealmName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::RealmName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateRealmRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteRealmRequest
{
/// <summary>
/// <see cref="gcgv::RealmName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::RealmName RealmName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::RealmName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Realm
{
/// <summary>
/// <see cref="gcgv::RealmName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcgv::RealmName RealmName
{
get => string.IsNullOrEmpty(Name) ? null : gcgv::RealmName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* 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;
namespace DocuSign.eSign.Model
{
/// <summary>
/// FolderItemV2
/// </summary>
[DataContract]
public partial class FolderItemV2 : IEquatable<FolderItemV2>, IValidatableObject
{
public FolderItemV2()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="FolderItemV2" /> class.
/// </summary>
/// <param name="CompletedDateTime">Specifies the date and time this item was completed..</param>
/// <param name="CreatedDateTime">Indicates the date and time the item was created..</param>
/// <param name="EnvelopeId">The envelope ID of the envelope status that failed to post..</param>
/// <param name="EnvelopeUri">Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes..</param>
/// <param name="ExpireDateTime">The date and time the envelope is set to expire..</param>
/// <param name="FolderId">.</param>
/// <param name="FolderUri">.</param>
/// <param name="Is21CFRPart11">When set to **true**, indicates that this module is enabled on the account..</param>
/// <param name="IsSignatureProviderEnvelope">.</param>
/// <param name="LastModifiedDateTime">The date and time the item was last modified..</param>
/// <param name="OwnerName">.</param>
/// <param name="Recipients">Recipients.</param>
/// <param name="RecipientsUri">Contains a URI for an endpoint that you can use to retrieve the recipients..</param>
/// <param name="SenderCompany">.</param>
/// <param name="SenderEmail">.</param>
/// <param name="SenderName">.</param>
/// <param name="SenderUserId">.</param>
/// <param name="SentDateTime">The date and time the envelope was sent..</param>
/// <param name="Status">Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later..</param>
/// <param name="Subject">.</param>
public FolderItemV2(string CompletedDateTime = default(string), string CreatedDateTime = default(string), string EnvelopeId = default(string), string EnvelopeUri = default(string), string ExpireDateTime = default(string), string FolderId = default(string), string FolderUri = default(string), string Is21CFRPart11 = default(string), string IsSignatureProviderEnvelope = default(string), string LastModifiedDateTime = default(string), string OwnerName = default(string), Recipients Recipients = default(Recipients), string RecipientsUri = default(string), string SenderCompany = default(string), string SenderEmail = default(string), string SenderName = default(string), string SenderUserId = default(string), string SentDateTime = default(string), string Status = default(string), string Subject = default(string))
{
this.CompletedDateTime = CompletedDateTime;
this.CreatedDateTime = CreatedDateTime;
this.EnvelopeId = EnvelopeId;
this.EnvelopeUri = EnvelopeUri;
this.ExpireDateTime = ExpireDateTime;
this.FolderId = FolderId;
this.FolderUri = FolderUri;
this.Is21CFRPart11 = Is21CFRPart11;
this.IsSignatureProviderEnvelope = IsSignatureProviderEnvelope;
this.LastModifiedDateTime = LastModifiedDateTime;
this.OwnerName = OwnerName;
this.Recipients = Recipients;
this.RecipientsUri = RecipientsUri;
this.SenderCompany = SenderCompany;
this.SenderEmail = SenderEmail;
this.SenderName = SenderName;
this.SenderUserId = SenderUserId;
this.SentDateTime = SentDateTime;
this.Status = Status;
this.Subject = Subject;
}
/// <summary>
/// Specifies the date and time this item was completed.
/// </summary>
/// <value>Specifies the date and time this item was completed.</value>
[DataMember(Name="completedDateTime", EmitDefaultValue=false)]
public string CompletedDateTime { get; set; }
/// <summary>
/// Indicates the date and time the item was created.
/// </summary>
/// <value>Indicates the date and time the item was created.</value>
[DataMember(Name="createdDateTime", EmitDefaultValue=false)]
public string CreatedDateTime { get; set; }
/// <summary>
/// The envelope ID of the envelope status that failed to post.
/// </summary>
/// <value>The envelope ID of the envelope status that failed to post.</value>
[DataMember(Name="envelopeId", EmitDefaultValue=false)]
public string EnvelopeId { get; set; }
/// <summary>
/// Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes.
/// </summary>
/// <value>Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes.</value>
[DataMember(Name="envelopeUri", EmitDefaultValue=false)]
public string EnvelopeUri { get; set; }
/// <summary>
/// The date and time the envelope is set to expire.
/// </summary>
/// <value>The date and time the envelope is set to expire.</value>
[DataMember(Name="expireDateTime", EmitDefaultValue=false)]
public string ExpireDateTime { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="folderId", EmitDefaultValue=false)]
public string FolderId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="folderUri", EmitDefaultValue=false)]
public string FolderUri { get; set; }
/// <summary>
/// When set to **true**, indicates that this module is enabled on the account.
/// </summary>
/// <value>When set to **true**, indicates that this module is enabled on the account.</value>
[DataMember(Name="is21CFRPart11", EmitDefaultValue=false)]
public string Is21CFRPart11 { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="isSignatureProviderEnvelope", EmitDefaultValue=false)]
public string IsSignatureProviderEnvelope { get; set; }
/// <summary>
/// The date and time the item was last modified.
/// </summary>
/// <value>The date and time the item was last modified.</value>
[DataMember(Name="lastModifiedDateTime", EmitDefaultValue=false)]
public string LastModifiedDateTime { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="ownerName", EmitDefaultValue=false)]
public string OwnerName { get; set; }
/// <summary>
/// Gets or Sets Recipients
/// </summary>
[DataMember(Name="recipients", EmitDefaultValue=false)]
public Recipients Recipients { get; set; }
/// <summary>
/// Contains a URI for an endpoint that you can use to retrieve the recipients.
/// </summary>
/// <value>Contains a URI for an endpoint that you can use to retrieve the recipients.</value>
[DataMember(Name="recipientsUri", EmitDefaultValue=false)]
public string RecipientsUri { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="senderCompany", EmitDefaultValue=false)]
public string SenderCompany { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="senderEmail", EmitDefaultValue=false)]
public string SenderEmail { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="senderName", EmitDefaultValue=false)]
public string SenderName { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="senderUserId", EmitDefaultValue=false)]
public string SenderUserId { get; set; }
/// <summary>
/// The date and time the envelope was sent.
/// </summary>
/// <value>The date and time the envelope was sent.</value>
[DataMember(Name="sentDateTime", EmitDefaultValue=false)]
public string SentDateTime { get; set; }
/// <summary>
/// Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.
/// </summary>
/// <value>Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="subject", EmitDefaultValue=false)]
public string Subject { 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 FolderItemV2 {\n");
sb.Append(" CompletedDateTime: ").Append(CompletedDateTime).Append("\n");
sb.Append(" CreatedDateTime: ").Append(CreatedDateTime).Append("\n");
sb.Append(" EnvelopeId: ").Append(EnvelopeId).Append("\n");
sb.Append(" EnvelopeUri: ").Append(EnvelopeUri).Append("\n");
sb.Append(" ExpireDateTime: ").Append(ExpireDateTime).Append("\n");
sb.Append(" FolderId: ").Append(FolderId).Append("\n");
sb.Append(" FolderUri: ").Append(FolderUri).Append("\n");
sb.Append(" Is21CFRPart11: ").Append(Is21CFRPart11).Append("\n");
sb.Append(" IsSignatureProviderEnvelope: ").Append(IsSignatureProviderEnvelope).Append("\n");
sb.Append(" LastModifiedDateTime: ").Append(LastModifiedDateTime).Append("\n");
sb.Append(" OwnerName: ").Append(OwnerName).Append("\n");
sb.Append(" Recipients: ").Append(Recipients).Append("\n");
sb.Append(" RecipientsUri: ").Append(RecipientsUri).Append("\n");
sb.Append(" SenderCompany: ").Append(SenderCompany).Append("\n");
sb.Append(" SenderEmail: ").Append(SenderEmail).Append("\n");
sb.Append(" SenderName: ").Append(SenderName).Append("\n");
sb.Append(" SenderUserId: ").Append(SenderUserId).Append("\n");
sb.Append(" SentDateTime: ").Append(SentDateTime).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Subject: ").Append(Subject).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as FolderItemV2);
}
/// <summary>
/// Returns true if FolderItemV2 instances are equal
/// </summary>
/// <param name="other">Instance of FolderItemV2 to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FolderItemV2 other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CompletedDateTime == other.CompletedDateTime ||
this.CompletedDateTime != null &&
this.CompletedDateTime.Equals(other.CompletedDateTime)
) &&
(
this.CreatedDateTime == other.CreatedDateTime ||
this.CreatedDateTime != null &&
this.CreatedDateTime.Equals(other.CreatedDateTime)
) &&
(
this.EnvelopeId == other.EnvelopeId ||
this.EnvelopeId != null &&
this.EnvelopeId.Equals(other.EnvelopeId)
) &&
(
this.EnvelopeUri == other.EnvelopeUri ||
this.EnvelopeUri != null &&
this.EnvelopeUri.Equals(other.EnvelopeUri)
) &&
(
this.ExpireDateTime == other.ExpireDateTime ||
this.ExpireDateTime != null &&
this.ExpireDateTime.Equals(other.ExpireDateTime)
) &&
(
this.FolderId == other.FolderId ||
this.FolderId != null &&
this.FolderId.Equals(other.FolderId)
) &&
(
this.FolderUri == other.FolderUri ||
this.FolderUri != null &&
this.FolderUri.Equals(other.FolderUri)
) &&
(
this.Is21CFRPart11 == other.Is21CFRPart11 ||
this.Is21CFRPart11 != null &&
this.Is21CFRPart11.Equals(other.Is21CFRPart11)
) &&
(
this.IsSignatureProviderEnvelope == other.IsSignatureProviderEnvelope ||
this.IsSignatureProviderEnvelope != null &&
this.IsSignatureProviderEnvelope.Equals(other.IsSignatureProviderEnvelope)
) &&
(
this.LastModifiedDateTime == other.LastModifiedDateTime ||
this.LastModifiedDateTime != null &&
this.LastModifiedDateTime.Equals(other.LastModifiedDateTime)
) &&
(
this.OwnerName == other.OwnerName ||
this.OwnerName != null &&
this.OwnerName.Equals(other.OwnerName)
) &&
(
this.Recipients == other.Recipients ||
this.Recipients != null &&
this.Recipients.Equals(other.Recipients)
) &&
(
this.RecipientsUri == other.RecipientsUri ||
this.RecipientsUri != null &&
this.RecipientsUri.Equals(other.RecipientsUri)
) &&
(
this.SenderCompany == other.SenderCompany ||
this.SenderCompany != null &&
this.SenderCompany.Equals(other.SenderCompany)
) &&
(
this.SenderEmail == other.SenderEmail ||
this.SenderEmail != null &&
this.SenderEmail.Equals(other.SenderEmail)
) &&
(
this.SenderName == other.SenderName ||
this.SenderName != null &&
this.SenderName.Equals(other.SenderName)
) &&
(
this.SenderUserId == other.SenderUserId ||
this.SenderUserId != null &&
this.SenderUserId.Equals(other.SenderUserId)
) &&
(
this.SentDateTime == other.SentDateTime ||
this.SentDateTime != null &&
this.SentDateTime.Equals(other.SentDateTime)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.Subject == other.Subject ||
this.Subject != null &&
this.Subject.Equals(other.Subject)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CompletedDateTime != null)
hash = hash * 59 + this.CompletedDateTime.GetHashCode();
if (this.CreatedDateTime != null)
hash = hash * 59 + this.CreatedDateTime.GetHashCode();
if (this.EnvelopeId != null)
hash = hash * 59 + this.EnvelopeId.GetHashCode();
if (this.EnvelopeUri != null)
hash = hash * 59 + this.EnvelopeUri.GetHashCode();
if (this.ExpireDateTime != null)
hash = hash * 59 + this.ExpireDateTime.GetHashCode();
if (this.FolderId != null)
hash = hash * 59 + this.FolderId.GetHashCode();
if (this.FolderUri != null)
hash = hash * 59 + this.FolderUri.GetHashCode();
if (this.Is21CFRPart11 != null)
hash = hash * 59 + this.Is21CFRPart11.GetHashCode();
if (this.IsSignatureProviderEnvelope != null)
hash = hash * 59 + this.IsSignatureProviderEnvelope.GetHashCode();
if (this.LastModifiedDateTime != null)
hash = hash * 59 + this.LastModifiedDateTime.GetHashCode();
if (this.OwnerName != null)
hash = hash * 59 + this.OwnerName.GetHashCode();
if (this.Recipients != null)
hash = hash * 59 + this.Recipients.GetHashCode();
if (this.RecipientsUri != null)
hash = hash * 59 + this.RecipientsUri.GetHashCode();
if (this.SenderCompany != null)
hash = hash * 59 + this.SenderCompany.GetHashCode();
if (this.SenderEmail != null)
hash = hash * 59 + this.SenderEmail.GetHashCode();
if (this.SenderName != null)
hash = hash * 59 + this.SenderName.GetHashCode();
if (this.SenderUserId != null)
hash = hash * 59 + this.SenderUserId.GetHashCode();
if (this.SentDateTime != null)
hash = hash * 59 + this.SentDateTime.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.Subject != null)
hash = hash * 59 + this.Subject.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Referensi_Tarif_List : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRefTarif";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["TarifManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
else
{
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddTarif");
}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
GetListJenisLayanan();
GetListPoliklinik();
GetListKelompokLayanan();
GetListKelas();
UpdateDataView(true);
}
}
public void GetListKelompokLayanan()
{
string KelompokLayananId = "";
SIMRS.DataAccess.RS_KelompokLayanan myObj = new SIMRS.DataAccess.RS_KelompokLayanan();
DataTable dt = myObj.GetList();
cmbKelompokLayanan.Items.Clear();
int i = 0;
cmbKelompokLayanan.Items.Add("");
cmbKelompokLayanan.Items[i].Text = "";
cmbKelompokLayanan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelompokLayanan.Items.Add("");
cmbKelompokLayanan.Items[i].Text = dr["Kode"].ToString() + ". " + dr["Nama"].ToString();
cmbKelompokLayanan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == KelompokLayananId)
cmbKelompokLayanan.SelectedIndex = i;
i++;
}
}
public void GetListJenisLayanan()
{
string JenisLayananId = "";
SIMRS.DataAccess.RS_JenisLayanan myObj = new SIMRS.DataAccess.RS_JenisLayanan();
DataTable dt = myObj.GetList();
cmbJenisLayanan.Items.Clear();
int i = 0;
cmbJenisLayanan.Items.Add("");
cmbJenisLayanan.Items[i].Text = "";
cmbJenisLayanan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbJenisLayanan.Items.Add("");
cmbJenisLayanan.Items[i].Text = dr["Kode"].ToString() + ". " + dr["Nama"].ToString();
cmbJenisLayanan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == JenisLayananId)
cmbJenisLayanan.SelectedIndex = i;
i++;
}
}
public void GetListPoliklinik()
{
string PoliklinikId = "";
SIMRS.DataAccess.RS_Poliklinik myObj = new SIMRS.DataAccess.RS_Poliklinik();
DataTable dt = myObj.GetList();
cmbPoliklinik.Items.Clear();
int i = 0;
cmbPoliklinik.Items.Add("");
cmbPoliklinik.Items[i].Text = "";
cmbPoliklinik.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPoliklinik.Items.Add("");
cmbPoliklinik.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString() + " (" + dr["KelompokPoliklinikNama"].ToString() + ")";
cmbPoliklinik.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PoliklinikId)
cmbPoliklinik.SelectedIndex = i;
i++;
}
}
public void GetListKelas()
{
string KelasId = "";
SIMRS.DataAccess.RS_Kelas myObj = new SIMRS.DataAccess.RS_Kelas();
DataTable dt = myObj.GetList();
cmbKelas.Items.Clear();
int i = 0;
cmbKelas.Items.Add("");
cmbKelas.Items[i].Text = "";
cmbKelas.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelas.Items.Add("");
cmbKelas.Items[i].Text = dr["Nama"].ToString();
cmbKelas.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == KelasId)
cmbKelas.SelectedIndex = i;
i++;
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_Tarif myObj = new SIMRS.DataAccess.RS_Tarif();
DataTable myData = myObj.SelectAll();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
string filter = "";
if (cmbJenisLayanan.SelectedIndex >0 )
filter = " JenisLayananId = " + cmbJenisLayanan.SelectedItem.Value;
if (cmbPoliklinik.SelectedIndex > 0)
{
filter += filter != "" ? " AND ":"";
filter += " PoliklinikId = " + cmbPoliklinik.SelectedItem.Value;
}
if (cmbKelompokLayanan.SelectedIndex > 0)
{
filter += filter != "" ? " AND " : "";
filter += " KelompokLayananId = " + cmbKelompokLayanan.SelectedItem.Value;
}
if (cmbKelas.SelectedIndex > 0)
{
filter += filter != "" ? " AND " : "";
filter += " KelasId = " + cmbKelas.SelectedItem.Value;
}
dv.RowFilter = filter;
BindData(dv);
}
#endregion
#region .Update Link Item Butom
/// <summary>
/// The function is responsible for get link button form.
/// </summary>
/// <param name="szId"></param>
/// <param name="CurrentPage"></param>
/// <returns></returns>
public string GetLinkButton(string Id, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["TarifManagement"] != null)
{
szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
return szResult;
}
#endregion
}
| |
// This file is part of the C5 Generic Collection Library for C# and CLI
// See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using C5;
namespace GConvexHull;
/// <summary>
/// Summary description for Form1.
/// </summary>
public class TesterForm : System.Windows.Forms.Form
{
//My data
//My GUI stuff
private System.Windows.Forms.Panel drawarea;
private Graphics drawg;
//Std stuff
private System.Windows.Forms.Button runButton;
private TextBox pointCount;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public TesterForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
drawg = drawarea.CreateGraphics();
reset();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.drawarea = new System.Windows.Forms.Panel();
this.runButton = new System.Windows.Forms.Button();
this.pointCount = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// drawarea
//
this.drawarea.BackColor = System.Drawing.Color.White;
this.drawarea.Location = new System.Drawing.Point(8, 9);
this.drawarea.Name = "drawarea";
this.drawarea.Size = new System.Drawing.Size(500, 500);
this.drawarea.TabIndex = 0;
this.drawarea.Paint += new System.Windows.Forms.PaintEventHandler(this.drawarea_Paint);
this.drawarea.Invalidated += new System.Windows.Forms.InvalidateEventHandler(this.drawarea_Invalidated);
this.drawarea.MouseMove += new System.Windows.Forms.MouseEventHandler(this.drawarea_MouseMove);
this.drawarea.MouseClick += new System.Windows.Forms.MouseEventHandler(this.drawarea_MouseClick);
//
// runButton
//
this.runButton.Location = new System.Drawing.Point(8, 516);
this.runButton.Name = "runButton";
this.runButton.Size = new System.Drawing.Size(42, 20);
this.runButton.TabIndex = 1;
this.runButton.Text = "Run";
this.runButton.Click += new System.EventHandler(this.runButton_Click);
//
// pointCount
//
this.pointCount.Location = new System.Drawing.Point(97, 517);
this.pointCount.Name = "pointCount";
this.pointCount.Size = new System.Drawing.Size(55, 20);
this.pointCount.TabIndex = 5;
//
// TesterForm
//
this.ClientSize = new System.Drawing.Size(524, 550);
this.Controls.Add(this.pointCount);
this.Controls.Add(this.runButton);
this.Controls.Add(this.drawarea);
this.Name = "TesterForm";
this.Text = "C5 Tester";
this.Load += new System.EventHandler(this.TesterForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new TesterForm());
}
Point[] pts;
Point[] chpts;
private void runButton_Click(object sender, System.EventArgs e)
{
int N = int.Parse(pointCount.Text);
pts = new Point[N];
for (int i = 0; i < N; i++)
pts[i] = Point.Random(500, 500);
chpts = Convexhull.ConvexHull(pts);
drawarea.Invalidate();
}
private void drawarea_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
mydraw();
}
private void resetButton_Click(object sender, System.EventArgs e)
{
reset();
}
private void reset()
{
drawarea.Invalidate();//(new Rectangle(0, 0, 40, 40));
}
public void mydraw()
{
if (pts == null)
{
return;
}
for (int i = 0; i < pts.Length; i++)
{
Point p = pts[i];
drawg.DrawEllipse(new Pen(Color.Red), transx(p.x) - 2, transy(p.y) - 2, 4, 4);
}
for (int i = 0; i < chpts.Length; i++)
{
int j = i + 1 < chpts.Length ? i + 1 : 0;
drawg.DrawEllipse(new Pen(Color.Blue), transx(chpts[i].x) - 2, transy(chpts[i].y) - 2, 4, 4);
drawg.DrawLine(new Pen(Color.LawnGreen), transx(chpts[i].x), transx(chpts[i].y), transx(chpts[j].x), transx(chpts[j].y));
}
}
private int transx(double x)
{
return (int)x;
}
private int transy(double y)
{
return (int)y;
}
private void dumpButton_Click(object sender, System.EventArgs e)
{
Debug.WriteLine("###############");
Debug.WriteLine("###############");
}
private void graphTypeControlArray_Click(object sender, System.EventArgs e)
{
Debug.WriteLine(e.GetType());
Debug.WriteLine(sender.GetType());
drawarea.Invalidate();
}
private void drawarea_MouseMove(object sender, MouseEventArgs e)
{
}
private void drawarea_MouseClick(object sender, MouseEventArgs e)
{
//double x = untransx(e.X), y = untransy(e.Y);
}
private void drawarea_Invalidated(object sender, InvalidateEventArgs e)
{
//msg.Text = e.InvalidRect + "";
//mydraw();
}
private void preparedFigureSelection_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void voronoiButton_CheckedChanged(object sender, EventArgs e)
{
graphTypeControlArray_Click(sender, e);
}
private void delaunayButton_CheckedChanged(object sender, EventArgs e)
{
graphTypeControlArray_Click(sender, e);
}
private void TesterForm_Load(object sender, EventArgs e)
{
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.IsolatedStorage
{
public class IsolatedStorageFileStream : FileStream
{
private const string BackSlash = "\\";
private const int DefaultBufferSize = 1024;
private FileStream _fs;
private IsolatedStorageFile _isf;
private string _givenPath;
private string _fullPath;
public IsolatedStorageFileStream(string path, FileMode mode)
: this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, null)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, IsolatedStorageFile isf)
: this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, isf)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access)
: this(path, mode, access, access == FileAccess.Read ? FileShare.Read : FileShare.None, DefaultBufferSize, null)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, IsolatedStorageFile isf)
: this(path, mode, access, access == FileAccess.Read ? FileShare.Read : FileShare.None, DefaultBufferSize, isf)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share)
: this(path, mode, access, share, DefaultBufferSize, null)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile isf)
: this(path, mode, access, share, DefaultBufferSize, isf)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
: this(path, mode, access, share, bufferSize, null)
{
}
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf)
: this(path, mode, access, share, bufferSize, InitializeFileStream(path, mode, access, share, bufferSize, isf))
{
}
// On NetFX FileStream has an internal no arg constructor that we utilize to provide the facade. We don't have access
// to internals in CoreFX so we'll do the next best thing and contort ourselves into the SafeFileHandle constructor.
// (A path constructor would try and create the requested file and give us two open handles.)
//
// We only expose our own nested FileStream so the base class having a handle doesn't matter. Passing a new SafeFileHandle
// with ownsHandle: false avoids the parent class closing without our knowledge.
private IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, InitialiationData initializationData)
: base(new SafeFileHandle(initializationData.NestedStream.SafeFileHandle.DangerousGetHandle(), ownsHandle: false), access, bufferSize)
{
_isf = initializationData.StorageFile;
_givenPath = path;
_fullPath = initializationData.FullPath;
_fs = initializationData.NestedStream;
}
private struct InitialiationData
{
public FileStream NestedStream;
public IsolatedStorageFile StorageFile;
public string FullPath;
}
// If IsolatedStorageFile is null, then we default to using a file that is scoped by user, appdomain, and assembly.
private static InitialiationData InitializeFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if ((path.Length == 0) || path.Equals(BackSlash))
throw new ArgumentException(
SR.IsolatedStorage_Path);
bool createdStore = false;
if (isf == null)
{
isf = IsolatedStorageFile.GetUserStoreForDomain();
createdStore = true;
}
if (isf.Disposed)
throw new ObjectDisposedException(null, SR.IsolatedStorage_StoreNotOpen);
switch (mode)
{
case FileMode.CreateNew: // Assume new file
case FileMode.Create: // Check for New file & Unreserve
case FileMode.OpenOrCreate: // Check for new file
case FileMode.Truncate: // Unreserve old file size
case FileMode.Append: // Check for new file
case FileMode.Open: // Open existing, else exception
break;
default:
throw new ArgumentException(SR.IsolatedStorage_FileOpenMode);
}
InitialiationData data = new InitialiationData
{
FullPath = isf.GetFullPath(path),
StorageFile = isf
};
try
{
data.NestedStream = new FileStream(data.FullPath, mode, access, share, bufferSize, FileOptions.None);
}
catch (Exception e)
{
// Make an attempt to clean up the StorageFile if we created it
try
{
if (createdStore)
{
data.StorageFile?.Dispose();
}
}
catch
{
}
// Exception message might leak the IsolatedStorage path. The desktop prevented this by calling an
// internal API which made sure that the exception message was scrubbed. However since the innerException
// is never returned to the user(GetIsolatedStorageException() does not populate the innerexception
// in retail bits we leak the path only under the debugger via IsolatedStorageException._underlyingException which
// they can any way look at via IsolatedStorageFile instance as well.
throw IsolatedStorageFile.GetIsolatedStorageException(SR.IsolatedStorage_Operation_ISFS, e);
}
return data;
}
public override bool CanRead
{
get
{
return _fs.CanRead;
}
}
public override bool CanWrite
{
get
{
return _fs.CanWrite;
}
}
public override bool CanSeek
{
get
{
return _fs.CanSeek;
}
}
public override long Length
{
get
{
return _fs.Length;
}
}
public override long Position
{
get
{
return _fs.Position;
}
set
{
_fs.Position = value;
}
}
public override bool IsAsync
{
get
{
return _fs.IsAsync;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_fs != null)
_fs.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
public override void Flush()
{
_fs.Flush();
}
public override void Flush(bool flushToDisk)
{
_fs.Flush(flushToDisk);
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return _fs.FlushAsync();
}
public override void SetLength(long value)
{
_fs.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count)
{
return _fs.Read(buffer, offset, count);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken)
{
return _fs.ReadAsync(buffer, offset, count, cancellationToken);
}
public override int ReadByte()
{
return _fs.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin)
{
// Desktop implementation of IsolatedStorage ensures that in case the size is increased the new memory is zero'ed out.
// However in this implementation we simply call the FileStream.Seek APIs which have an undefined behavior.
return _fs.Seek(offset, origin);
}
public override void Write(byte[] buffer, int offset, int count)
{
_fs.Write(buffer, offset, count);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _fs.WriteAsync(buffer, offset, count, cancellationToken);
}
public override void WriteByte(byte value)
{
_fs.WriteByte(value);
}
public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
{
return _fs.BeginRead(array, offset, numBytes, userCallback, stateObject);
}
public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
{
return _fs.BeginWrite(array, offset, numBytes, userCallback, stateObject);
}
public override int EndRead(IAsyncResult asyncResult)
{
return _fs.EndRead(asyncResult);
}
public override void EndWrite(IAsyncResult asyncResult)
{
_fs.EndWrite(asyncResult);
}
[Obsolete("This property has been deprecated. Please use IsolatedStorageFileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public override IntPtr Handle
{
get { return _fs.Handle; }
}
public override void Unlock(long position, long length)
{
_fs.Unlock(position, length);
}
public override void Lock(long position, long length)
{
_fs.Lock(position, length);
}
public override SafeFileHandle SafeFileHandle
{
get
{
throw new IsolatedStorageException(SR.IsolatedStorage_Operation_ISFS);
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
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 info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel; // need this for the properties metadata
using System.Xml;
using System.Text.RegularExpressions;
using fyiReporting.RDL;
using System.Drawing.Design;
using System.Globalization;
using System.Windows.Forms.Design;
using System.Windows.Forms;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// PropertyImage - The Image specific Properties
/// </summary>
internal class PropertyImage : PropertyReportItem
{
internal PropertyImage(DesignXmlDraw d, DesignCtl dc, List<XmlNode> ris) : base(d, dc, ris)
{
}
[CategoryAttribute("Image"),
DescriptionAttribute("The image properties.")]
public PropertyImageI Image
{
get { return new PropertyImageI(this); }
}
}
[TypeConverter(typeof(PropertyImageConverter)),
Editor(typeof(PropertyImageUIEditor), typeof(System.Drawing.Design.UITypeEditor))]
internal class PropertyImageI : IReportItem
{
PropertyImage _pi;
internal PropertyImageI(PropertyImage pi)
{
_pi = pi;
}
[RefreshProperties(RefreshProperties.Repaint),
TypeConverter(typeof(ImageSourceConverter)),
DescriptionAttribute("Image Source:External, Embedded, Database.")]
public string Source
{
get
{
return _pi.GetValue("Source", "External");
}
set
{
_pi.SetValue("Source", value);
}
}
[RefreshProperties(RefreshProperties.Repaint),
DescriptionAttribute("Value depends upon the source of the image.")]
public PropertyExpr Value
{
get
{
return new PropertyExpr(_pi.GetValue("Value", ""));
}
set
{
_pi.SetValue("Value", value.Expression);
}
}
[RefreshProperties(RefreshProperties.Repaint),
TypeConverter(typeof(ImageMIMETypeConverter)),
DescriptionAttribute("When Source is Database MIMEType describes the type of image.")]
public string MIMEType
{
get
{
return _pi.GetValue("MIMEType", "");
}
set
{
if (string.Compare(this.Source.Trim(), "database", true) == 0)
throw new ArgumentException("MIMEType isn't relevent when Source isn't Database.");
_pi.SetValue("MIMEType", value);
}
}
[DescriptionAttribute("Defines how image is sized when image doesn't match specified size.")]
public ImageSizingEnum Sizing
{
get
{
string s = _pi.GetValue("Sizing", "AutoSize");
return ImageSizing.GetStyle(s);
}
set
{
_pi.SetValue("Sizing", value.ToString());
}
}
public override string ToString()
{
string s = this.Source;
string v = "";
if (s.ToLower().Trim() != "none")
v = this.Value.Expression;
return string.Format("{0} {1}", s, v);
}
#region IReportItem Members
public PropertyReportItem GetPRI()
{
return this._pi;
}
#endregion
}
#region ImageConverter
internal class PropertyImageConverter : ExpandableObjectConverter
{
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
public override bool CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if (destinationType == typeof(PropertyImageI))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is PropertyImage)
{
PropertyImageI pi = value as PropertyImageI;
return pi.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
#endregion
#region UIEditor
internal class PropertyImageUIEditor : UITypeEditor
{
internal PropertyImageUIEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
if ((context == null) || (provider == null))
return base.EditValue(context, provider, value);
// Access the Property Browser's UI display service
IWindowsFormsEditorService editorService =
(IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (editorService == null)
return base.EditValue(context, provider, value);
// Create an instance of the UI editor form
IReportItem iri = context.Instance as IReportItem;
if (iri == null)
return base.EditValue(context, provider, value);
PropertyImage pre = iri.GetPRI() as PropertyImage;
PropertyImageI pbi = value as PropertyImageI;
if (pbi == null)
return base.EditValue(context, provider, value);
using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes,
SingleCtlTypeEnum.ImageCtl, null))
{
///////
// Display the UI editor dialog
if (editorService.ShowDialog(scd) == DialogResult.OK)
{
// Return the new property value from the UI editor form
return new PropertyImageI(pre);
}
return base.EditValue(context, provider, value);
}
}
}
#endregion
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Automation.Models;
using Microsoft.WindowsAzure;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation runbooks. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
/// more information)
/// </summary>
public partial interface IRunbookOperations
{
/// <summary>
/// Create a runbook schedule link. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the create runbook schedule link
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create runbook schedule link operation.
/// </returns>
Task<RunbookCreateScheduleLinkResponse> CreateScheduleLinkAsync(string automationAccount, RunbookCreateScheduleLinkParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Delete the runbook identified by runbookId. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='runbookId'>
/// The runbook id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> DeleteAsync(string automationAccount, string runbookId, CancellationToken cancellationToken);
/// <summary>
/// Delete the runbook schedule link. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the delete runbook schedule link
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> DeleteScheduleLinkAsync(string automationAccount, RunbookDeleteScheduleLinkParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Edit the runbook identified by runbookId. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='runbookId'>
/// The runbook id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the edit runbook operation.
/// </returns>
Task<RunbookEditResponse> EditAsync(string automationAccount, string runbookId, CancellationToken cancellationToken);
/// <summary>
/// Retrieve the runbook identified by runbookId. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='runbookId'>
/// The runbook id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
Task<RunbookGetResponse> GetAsync(string automationAccount, string runbookId, CancellationToken cancellationToken);
/// <summary>
/// Retrieve the runbook identified by runbookId. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='runbookId'>
/// The runbook id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get runbook operation.
/// </returns>
Task<RunbookGetResponse> GetWithSchedulesAsync(string automationAccount, string runbookId, CancellationToken cancellationToken);
/// <summary>
/// Retrieve a list of one runbook identified by runbookName. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='runbookName'>
/// The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
Task<RunbookListResponse> ListByNameAsync(string automationAccount, string runbookName, CancellationToken cancellationToken);
/// <summary>
/// Retrieve a list of one runbook identified by runbookName. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='runbookName'>
/// The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
Task<RunbookListResponse> ListByNameWithSchedulesAsync(string automationAccount, string runbookName, CancellationToken cancellationToken);
/// <summary>
/// Retrieve a list of runbooks which run on the schedule. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the list runbook by schedule name
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
Task<RunbookListResponse> ListByScheduleNameAsync(string automationAccount, RunbookListByScheduleNameParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Retrieve a list of runbooks which run on the schedule. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the list runbook by schedule name
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
Task<RunbookListResponse> ListByScheduleNameWithSchedulesAsync(string automationAccount, RunbookListByScheduleNameParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Retrieve a list of runbooks for the given automation account. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='skipToken'>
/// The skip token.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list runbook operation.
/// </returns>
Task<RunbookListResponse> ListWithSchedulesAsync(string automationAccount, string skipToken, CancellationToken cancellationToken);
/// <summary>
/// Publish the runbook identified by runbookId. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the publish runbook operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the publish runbook operation.
/// </returns>
Task<RunbookPublishResponse> PublishAsync(string automationAccount, RunbookPublishParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Start the runbook identified by runbookId. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the start runbook operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the start runbook operation.
/// </returns>
Task<RunbookStartResponse> StartAsync(string automationAccount, RunbookStartParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Update the runbook identified by runbookId. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXXXX.aspx
/// for more information)
/// </summary>
/// <param name='automationAccount'>
/// The automation account name.
/// </param>
/// <param name='parameters'>
/// The parameters supplied to the update runbook operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> UpdateAsync(string automationAccount, RunbookUpdateParameters parameters, CancellationToken cancellationToken);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace DuckDuck.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 470514 $
* $LastChangedDate: 2006-11-02 13:46:13 -0700 (Thu, 02 Nov 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2005, 2006 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
#if dotnet2
using System;
using System.Collections;
using IBatisNet.Common;
using IBatisNet.Common.Exceptions;
using IBatisNet.Common.Utilities;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.DataMapper.Test.Domain;
using System.Collections.Generic;
using NUnit.Framework;
namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests.Generics
{
[TestFixture]
public class StatementTest : BaseTest
{
#region SetUp & TearDown
/// <summary>
/// SetUp
/// </summary>
[SetUp]
public void Init()
{
InitScript(sqlMap.DataSource, ScriptDirectory + "account-init.sql");
InitScript(sqlMap.DataSource, ScriptDirectory + "order-init.sql");
InitScript(sqlMap.DataSource, ScriptDirectory + "line-item-init.sql");
InitScript(sqlMap.DataSource, ScriptDirectory + "enumeration-init.sql");
InitScript(sqlMap.DataSource, ScriptDirectory + "other-init.sql");
}
/// <summary>
/// TearDown
/// </summary>
[TearDown]
public void Dispose()
{ /* ... */
}
#endregion
#region Object Query tests
/// <summary>
/// Test Open connection with a connection string
/// </summary>
[Test]
public void TestOpenConnection()
{
sqlMap.OpenConnection(sqlMap.DataSource.ConnectionString);
Account account = sqlMap.QueryForObject<Account>("SelectWithProperty", null);
sqlMap.CloseConnection();
AssertAccount1(account);
}
/// <summary>
/// Test use a statement with property subtitution
/// (JIRA 22)
/// </summary>
[Test]
public void TestSelectWithProperty()
{
Account account = sqlMap.QueryForObject<Account>("SelectWithProperty", null);
AssertAccount1(account);
}
/// <summary>
/// Test ExecuteQueryForObject Via ColumnName
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaColumnName()
{
Account account = sqlMap.QueryForObject<Account>("GetAccountViaColumnName", 1);
AssertAccount1(account);
}
/// <summary>
/// Test ExecuteQueryForObject Via ColumnIndex
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaColumnIndex()
{
Account account = sqlMap.QueryForObject<Account>("GetAccountViaColumnIndex", 1);
AssertAccount1(account);
}
/// <summary>
/// Test ExecuteQueryForObject Via ResultClass
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaResultClass()
{
Account account = sqlMap.QueryForObject<Account>("GetAccountViaResultClass", 1);
AssertAccount1(account);
}
/// <summary>
/// Test ExecuteQueryForObject With simple ResultClass : string
/// </summary>
[Test]
public void TestExecuteQueryForObjectWithSimpleResultClass()
{
string email = sqlMap.QueryForObject<string>("GetEmailAddressViaResultClass", 1);
Assert.AreEqual("Joe.Dalton@somewhere.com", email);
}
/// <summary>
/// Test ExecuteQueryForObject With simple ResultMap : string
/// </summary>
[Test]
public void TestExecuteQueryForObjectWithSimpleResultMap()
{
string email = sqlMap.QueryForObject<string>("GetEmailAddressViaResultMap", 1);
Assert.AreEqual("Joe.Dalton@somewhere.com", email);
}
/// <summary>
/// Test Primitive ReturnValue : System.DateTime
/// </summary>
[Test]
public void TestPrimitiveReturnValue()
{
DateTime CardExpiry = sqlMap.QueryForObject<DateTime>("GetOrderCardExpiryViaResultClass", 1);
Assert.AreEqual(new DateTime(2003, 02, 15, 8, 15, 00), CardExpiry);
}
/// <summary>
/// Test ExecuteQueryForObject with result object : Account
/// </summary>
[Test]
public void TestExecuteQueryForObjectWithResultObject()
{
Account account = new Account();
Account testAccount = sqlMap.QueryForObject<Account>("GetAccountViaColumnName", 1, account);
AssertAccount1(account);
Assert.IsTrue(account == testAccount);
}
/// <summary>
/// Test ExecuteQueryForObject as Hashtable
/// </summary>
[Test]
public void TestExecuteQueryForObjectAsHashtable()
{
Hashtable account = sqlMap.QueryForObject<Hashtable>("GetAccountAsHashtable", 1);
AssertAccount1AsHashtable(account);
}
/// <summary>
/// Test ExecuteQueryForObject as Hashtable ResultClass
/// </summary>
[Test]
public void TestExecuteQueryForObjectAsHashtableResultClass()
{
Hashtable account = sqlMap.QueryForObject<Hashtable>("GetAccountAsHashtableResultClass", 1);
AssertAccount1AsHashtableForResultClass(account);
}
/// <summary>
/// Test ExecuteQueryForObject via Hashtable
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaHashtable()
{
Hashtable param = new Hashtable();
param.Add("LineItem_ID", 4);
param.Add("Order_ID", 9);
LineItem testItem = sqlMap.QueryForObject<LineItem>("GetSpecificLineItem", param);
Assert.IsNotNull(testItem);
Assert.AreEqual("TSM-12", testItem.Code);
}
/// <summary>
/// Test Query Dynamic Sql Element
/// </summary>
[Test]
public void TestQueryDynamicSqlElement()
{
//IList list = sqlMap.QueryForList("GetDynamicOrderedEmailAddressesViaResultMap", "Account_ID");
IList<string> list = sqlMap.QueryForList<string>("GetDynamicOrderedEmailAddressesViaResultMap", "Account_ID");
Assert.AreEqual("Joe.Dalton@somewhere.com", list[0]);
//list = sqlMap.QueryForList("GetDynamicOrderedEmailAddressesViaResultMap", "Account_FirstName");
list = sqlMap.QueryForList<string>("GetDynamicOrderedEmailAddressesViaResultMap", "Account_FirstName");
Assert.AreEqual("Averel.Dalton@somewhere.com", list[0]);
}
/// <summary>
/// Test Execute QueryForList With ResultMap With Dynamic Element
/// </summary>
[Test]
public void TestExecuteQueryForListWithResultMapWithDynamicElement()
{
IList<Account> list = sqlMap.QueryForList<Account>("GetAllAccountsViaResultMapWithDynamicElement", "LIKE");
AssertAccount1(list[0]);
Assert.AreEqual(4, list.Count);
Assert.AreEqual(1, list[0].Id);
Assert.AreEqual(2, list[1].Id);
Assert.AreEqual(4, list[2].Id);
list = sqlMap.QueryForList<Account>("GetAllAccountsViaResultMapWithDynamicElement", "=");
Assert.AreEqual(0, list.Count);
}
/// <summary>
/// Test Simple Dynamic Substitution
/// </summary>
[Test]
[Ignore("No longer supported.")]
public void TestSimpleDynamicSubstitution()
{
string statement = "select" + " Account_ID as Id," + " Account_FirstName as FirstName," + " Account_LastName as LastName," + " Account_Email as EmailAddress" + " from Accounts" + " WHERE Account_ID = #id#";
Hashtable param = new Hashtable();
param.Add("id", 1);
param.Add("statement", statement);
IList list = sqlMap.QueryForList("SimpleDynamicSubstitution", param);
AssertAccount1((Account)list[0]);
Assert.AreEqual(1, list.Count);
}
/// <summary>
/// Test Get Account Via Inline Parameters
/// </summary>
[Test]
public void TestExecuteQueryForObjectViaInlineParameters()
{
Account account = new Account();
account.Id = 1;
Account testAccount = sqlMap.QueryForObject<Account>("GetAccountViaInlineParameters", account);
AssertAccount1(testAccount);
}
/// <summary>
/// Test ExecuteQuery For Object With Enum property
/// </summary>
[Test]
public void TestExecuteQueryForObjectWithEnum()
{
Enumeration enumClass = sqlMap.QueryForObject<Enumeration>("GetEnumeration", 1);
Assert.AreEqual(enumClass.Day, Days.Sat);
Assert.AreEqual(enumClass.Color, Colors.Red);
Assert.AreEqual(enumClass.Month, Months.August);
enumClass = sqlMap.QueryForObject("GetEnumeration", 3) as Enumeration;
Assert.AreEqual(enumClass.Day, Days.Mon);
Assert.AreEqual(enumClass.Color, Colors.Blue);
Assert.AreEqual(enumClass.Month, Months.September);
}
#endregion
#region List Query tests
/// <summary>
/// Test QueryForList with Hashtable ResultMap
/// </summary>
[Test]
public void TestQueryForListWithGeneric()
{
List<Account> accounts = new List<Account>();
sqlMap.QueryForList("GetAllAccountsViaResultMap", null, (System.Collections.IList)accounts);
AssertAccount1(accounts[0]);
Assert.AreEqual(5, accounts.Count);
Assert.AreEqual(1, accounts[0].Id);
Assert.AreEqual(2, accounts[1].Id);
Assert.AreEqual(3, accounts[2].Id);
Assert.AreEqual(4, accounts[3].Id);
Assert.AreEqual(5, accounts[4].Id);
}
/// <summary>
/// Test QueryForList with Hashtable ResultMap
/// </summary>
[Test]
public void TestQueryForListWithHashtableResultMap()
{
IList<Hashtable> list = sqlMap.QueryForList<Hashtable>("GetAllAccountsAsHashMapViaResultMap", null);
AssertAccount1AsHashtable(list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, list[0]["Id"]);
Assert.AreEqual(2, list[1]["Id"]);
Assert.AreEqual(3, list[2]["Id"]);
Assert.AreEqual(4, list[3]["Id"]);
Assert.AreEqual(5, list[4]["Id"]);
}
/// <summary>
/// Test QueryForList with Hashtable ResultClass
/// </summary>
[Test]
public void TestQueryForListWithHashtableResultClass()
{
IList<Hashtable> list = sqlMap.QueryForList<Hashtable>("GetAllAccountsAsHashtableViaResultClass", null);
AssertAccount1AsHashtableForResultClass(list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, list[0][BaseTest.ConvertKey("Id")]);
Assert.AreEqual(2, list[1][BaseTest.ConvertKey("Id")]);
Assert.AreEqual(3, list[2][BaseTest.ConvertKey("Id")]);
Assert.AreEqual(4, list[3][BaseTest.ConvertKey("Id")]);
Assert.AreEqual(5, list[4][BaseTest.ConvertKey("Id")]);
}
/// <summary>
/// Test QueryForList with IList ResultClass
/// </summary>
[Test]
public void TestQueryForListWithIListResultClass()
{
IList<IList> list = sqlMap.QueryForList<IList>("GetAllAccountsAsArrayListViaResultClass", null);
IList listAccount = list[0];
Assert.AreEqual(1, listAccount[0]);
Assert.AreEqual("Joe", listAccount[1]);
Assert.AreEqual("Dalton", listAccount[2]);
Assert.AreEqual("Joe.Dalton@somewhere.com", listAccount[3]);
Assert.AreEqual(5, list.Count);
listAccount = (IList)list[0];
Assert.AreEqual(1, listAccount[0]);
listAccount = (IList)list[1];
Assert.AreEqual(2, listAccount[0]);
listAccount = (IList)list[2];
Assert.AreEqual(3, listAccount[0]);
listAccount = (IList)list[3];
Assert.AreEqual(4, listAccount[0]);
listAccount = (IList)list[4];
Assert.AreEqual(5, listAccount[0]);
}
/// <summary>
/// Test QueryForList With ResultMap, result collection as ArrayList
/// </summary>
[Test]
public void TestQueryForListWithResultMap()
{
IList<Account> list = sqlMap.QueryForList<Account>("GetAllAccountsViaResultMap", null);
AssertAccount1(list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, list[0].Id);
Assert.AreEqual(2, list[1].Id);
Assert.AreEqual(3, list[2].Id);
Assert.AreEqual(4, list[3].Id);
Assert.AreEqual(5, list[4].Id);
}
/// <summary>
/// Test QueryForList with ResultObject :
/// AccountCollection strongly typed collection
/// </summary>
[Test]
public void TestQueryForListWithResultObject()
{
IList<Account> accounts = new List<Account>();
sqlMap.QueryForList("GetAllAccountsViaResultMap", null, accounts);
AssertAccount1(accounts[0]);
Assert.AreEqual(5, accounts.Count);
Assert.AreEqual(1, accounts[0].Id);
Assert.AreEqual(2, accounts[1].Id);
Assert.AreEqual(3, accounts[2].Id);
Assert.AreEqual(4, accounts[3].Id);
Assert.AreEqual(5, accounts[4].Id);
}
/// <summary>
/// Test QueryForList with no result.
/// </summary>
[Test]
public void TestQueryForListWithNoResult()
{
IList<Account> list = sqlMap.QueryForList<Account>("GetNoAccountsViaResultMap", null);
Assert.AreEqual(0, list.Count);
}
/// <summary>
/// Test QueryForList with ResultClass : Account.
/// </summary>
[Test]
public void TestQueryForListResultClass()
{
IList<Account> list = sqlMap.QueryForList<Account>("GetAllAccountsViaResultClass", null);
AssertAccount1(list[0]);
Assert.AreEqual(5, list.Count);
Assert.AreEqual(1, list[0].Id);
Assert.AreEqual(2, list[1].Id);
Assert.AreEqual(3, list[2].Id);
Assert.AreEqual(4, list[3].Id);
Assert.AreEqual(5, list[4].Id);
}
/// <summary>
/// Test QueryForList with simple resultClass : string
/// </summary>
[Test]
public void TestQueryForListWithSimpleResultClass()
{
IList<string> list = sqlMap.QueryForList<string>("GetAllEmailAddressesViaResultClass", null);
Assert.AreEqual("Joe.Dalton@somewhere.com", list[0]);
Assert.AreEqual("Averel.Dalton@somewhere.com", list[1]);
Assert.IsNull(list[2]);
Assert.AreEqual("Jack.Dalton@somewhere.com", list[3]);
Assert.AreEqual("gilles.bayon@nospam.org", list[4]);
}
/// <summary>
/// Test QueryForList with simple ResultMap : string
/// </summary>
[Test]
public void TestQueryForListWithSimpleResultMap()
{
IList<string> list = sqlMap.QueryForList<string>("GetAllEmailAddressesViaResultMap", null);
Assert.AreEqual("Joe.Dalton@somewhere.com", list[0]);
Assert.AreEqual("Averel.Dalton@somewhere.com", list[1]);
Assert.IsNull(list[2]);
Assert.AreEqual("Jack.Dalton@somewhere.com", list[3]);
Assert.AreEqual("gilles.bayon@nospam.org", list[4]);
}
/// <summary>
/// Test QueryForListWithSkipAndMax
/// </summary>
[Test]
public void TestQueryForListWithSkipAndMax()
{
IList<Account> list = sqlMap.QueryForList<Account>("GetAllAccountsViaResultMap", null, 2, 2);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(3, list[0].Id);
Assert.AreEqual(4, list[1].Id);
}
[Test]
public void TestQueryWithRowDelegate()
{
_index = 0;
RowDelegate<Account> handler = new RowDelegate<Account>(this.RowHandler);
IList<Account> list = sqlMap.QueryWithRowDelegate<Account>("GetAllAccountsViaResultMap", null, handler);
Assert.AreEqual(5, _index);
Assert.AreEqual(5, list.Count);
AssertAccount1(list[0]);
Assert.AreEqual(1, list[0].Id);
Assert.AreEqual(2, list[1].Id);
Assert.AreEqual(3, list[2].Id);
Assert.AreEqual(4, list[3].Id);
Assert.AreEqual(5, list[4].Id);
}
/// <summary>
/// Test QueryForList with constructor use on result object
/// </summary>
[Test]
public void TestJIRA172()
{
IList<Order> list = sqlMap.QueryForList<Order>("GetManyOrderWithConstructor", null);
Assert.IsTrue(list.Count > 0);
}
#endregion
#region Row delegate
private int _index = 0;
public void RowHandler(object obj, object paramterObject, IList<Account> list)
{
_index++;
Assert.AreEqual(_index, ((Account)obj).Id);
list.Add(((Account)obj));
}
#endregion
#region QueryForDictionary
/// <summary>
/// Test ExecuteQueryForDictionary
/// </summary>
[Test]
public void TestExecuteQueryForDictionary()
{
IDictionary<string, Account> map = sqlMap.QueryForDictionary<string, Account>("GetAllAccountsViaResultClass", null, "FirstName");
Assert.AreEqual(5, map.Count);
AssertAccount1(map["Joe"]);
Assert.AreEqual(1, map["Joe"].Id);
Assert.AreEqual(2, map["Averel"].Id);
Assert.AreEqual(3, map["William"].Id);
Assert.AreEqual(4, map["Jack"].Id);
Assert.AreEqual(5, map["Gilles"].Id);
}
/// <summary>
/// Test ExecuteQueryForDictionary With Cache.
/// </summary>
[Test]
public void TestExecuteQueryQueryForDictionaryWithCache()
{
IDictionary<string, Account> map = sqlMap.QueryForDictionary<string, Account>("GetAllAccountsCache", null, "FirstName");
int firstId = HashCodeProvider.GetIdentityHashCode(map);
Assert.AreEqual(5, map.Count);
AssertAccount1(map["Joe"]);
Assert.AreEqual(1, map["Joe"].Id);
Assert.AreEqual(2, map["Averel"].Id);
Assert.AreEqual(3, map["William"].Id);
Assert.AreEqual(4, map["Jack"].Id);
Assert.AreEqual(5, map["Gilles"].Id);
map = sqlMap.QueryForDictionary<string, Account>("GetAllAccountsCache", null, "FirstName");
int secondId = HashCodeProvider.GetIdentityHashCode(map);
Assert.AreEqual(firstId, secondId);
}
/// <summary>
/// Test ExecuteQueryForMap : Hashtable.
/// </summary>
/// <remarks>
/// If the keyProperty is an integer, you must acces the map
/// by map[integer] and not by map["integer"]
/// </remarks>
[Test]
public void TestExecuteQueryForDictionary2()
{
IDictionary<string, Order> map = sqlMap.QueryForDictionary<string, Order>("GetAllOrderWithLineItems", null, "PostalCode");
Assert.AreEqual(11, map.Count);
Order order = map["T4H 9G4"];
Assert.AreEqual(2, order.LineItemsIList.Count);
}
/// <summary>
/// Test ExecuteQueryForMap with value property :
/// "FirstName" as key, "EmailAddress" as value
/// </summary>
[Test]
public void TestExecuteQueryForDictionaryWithValueProperty()
{
IDictionary<string, string> map = sqlMap.QueryForDictionary<string, string>("GetAllAccountsViaResultClass", null, "FirstName", "EmailAddress");
Assert.AreEqual(5, map.Count);
Assert.AreEqual("Joe.Dalton@somewhere.com", map["Joe"]);
Assert.AreEqual("Averel.Dalton@somewhere.com", map["Averel"]);
Assert.IsNull(map["William"]);
Assert.AreEqual("Jack.Dalton@somewhere.com", map["Jack"]);
Assert.AreEqual("gilles.bayon@nospam.org", map["Gilles"]);
}
#endregion
}
}
#endif
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
internal sealed class TypeBuilderInstantiation : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Static Members
internal static Type MakeGenericType(Type type, Type[] typeArguments)
{
Contract.Requires(type != null, "this is only called from RuntimeType.MakeGenericType and TypeBuilder.MakeGenericType so 'type' cannot be null");
if (!type.IsGenericTypeDefinition)
throw new InvalidOperationException();
if (typeArguments == null)
throw new ArgumentNullException("typeArguments");
Contract.EndContractBlock();
foreach (Type t in typeArguments)
{
if (t == null)
throw new ArgumentNullException("typeArguments");
}
return new TypeBuilderInstantiation(type, typeArguments);
}
#endregion
#region Private Data Mebers
private Type m_type;
private Type[] m_inst;
private string m_strFullQualName;
internal Hashtable m_hashtable = new Hashtable();
#endregion
#region Constructor
private TypeBuilderInstantiation(Type type, Type[] inst)
{
m_type = type;
m_inst = inst;
m_hashtable = new Hashtable();
}
#endregion
#region Object Overrides
public override String ToString()
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
}
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*".ToCharArray(), this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&".ToCharArray(), this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]".ToCharArray(), this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string comma = "";
for(int i = 1; i < rank; i++)
comma += ",";
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", comma);
return SymbolType.FormCompoundType(s.ToCharArray(), this, 0);
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName
{
get
{
if (m_strFullQualName == null)
m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
return m_strFullQualName;
}
}
public override String Namespace { get { return m_type.Namespace; } }
public override String AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } }
private Type Substitute(Type[] substitutes)
{
Type[] inst = GetGenericArguments();
Type[] instSubstituted = new Type[inst.Length];
for (int i = 0; i < instSubstituted.Length; i++)
{
Type t = inst[i];
if (t is TypeBuilderInstantiation)
{
instSubstituted[i] = (t as TypeBuilderInstantiation).Substitute(substitutes);
}
else if (t is GenericTypeParameterBuilder)
{
// Substitute
instSubstituted[i] = substitutes[t.GenericParameterPosition];
}
else
{
instSubstituted[i] = t;
}
}
return GetGenericTypeDefinition().MakeGenericType(instSubstituted);
}
public override Type BaseType
{
// B<A,B,C>
// D<T,S> : B<S,List<T>,char>
// D<string,int> : B<int,List<string>,char>
// D<S,T> : B<T,List<S>,char>
// D<S,string> : B<string,List<S>,char>
get
{
Type typeBldrBase = m_type.BaseType;
if (typeBldrBase == null)
return null;
TypeBuilderInstantiation typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation;
if (typeBldrBaseAs == null)
return typeBldrBase;
return typeBldrBaseAs.Substitute(GetGenericArguments());
}
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; }
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { return m_inst; }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return true; } }
public override bool IsConstructedGenericType { get { return true; } }
public override bool IsGenericParameter { get { return false; } }
public override int GenericParameterPosition { get { throw new InvalidOperationException(); } }
protected override bool IsValueTypeImpl() { return m_type.IsValueType; }
public override bool ContainsGenericParameters
{
get
{
for (int i = 0; i < m_inst.Length; i++)
{
if (m_inst[i].ContainsGenericParameters)
return true;
}
return false;
}
}
public override MethodBase DeclaringMethod { get { return null; } }
public override Type GetGenericTypeDefinition() { return m_type; }
public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericTypeDefinition")); }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type c)
{
throw new NotSupportedException();
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
using System.Dynamic;
using System.Configuration;
using System.Transactions;
using System.Linq;
using System.Reflection;
using System.Threading;
namespace Art.Domain
{
// ############################################################################
// #
// # ---==> T H I S F I L E W A S G E N E R A T E D <==---
// #
// # This file was generated by PRO Spark, C# Edition, Version 4.5
// # Generated on 7/24/2013 4:11:01 PM
// #
// # Edits to this file may cause incorrect behavior and will be lost
// # if the code is regenerated.
// #
// ############################################################################
#region Data Layer
public partial class Db
{
static DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
public string connectionString { get; set; }
public Db(string conn = null)
{
try
{
if (conn == null) // index is 1 because 0 = localdb
connectionString = ConfigurationManager.ConnectionStrings[1].ConnectionString;
else
connectionString = ConfigurationManager.ConnectionStrings[conn].ConnectionString;
}
catch (Exception ex)
{
throw new DbException("Error locating connection string" + (conn == null ? "." : ": " + conn), ex);
}
}
// use wrapper because yield cannot be in immediate try catch
public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
try { return ReadCore(sql, make, parms); }
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// fast read and instantiate (i.e. make) a list of objects
IEnumerable<T> ReadCore<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);
}
}
}
}
}
// use wrapper because yield cannot be in immediate try catch
public IEnumerable<dynamic> Query(string sql, params object[] parms)
{
try { return QueryCore(sql, parms); }
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// fast read a list of dynamic types
IEnumerable<dynamic> QueryCore(string sql, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return reader.ToExpando();
}
}
}
}
}
// executes any sql in database
public void Execute(string sql, params object[] parms)
{
Update(sql, parms);
}
// return a scalar object
public object Scalar(string sql, params object[] parms)
{
try
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
return command.ExecuteScalar();
}
}
}
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// insert a new record
public int Insert(string sql, params object[] parms)
{
try
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql + ";SELECT SCOPE_IDENTITY();", connection, parms))
{
return int.Parse(command.ExecuteScalar().ToString());
}
}
}
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// update an existing record
public int Update(string sql, params object[] parms)
{
try
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
return command.ExecuteNonQuery();
}
}
}
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// delete a record
public int Delete(string sql, params object[] parms)
{
return Update(sql, parms);
}
#region Transaction support
DbConnection _connection;
DbTransaction _transaction;
// begins a new transaction
public void BeginTransaction()
{
_connection = CreateConnection();
_transaction = _connection.BeginTransaction();
}
// completes an ongoing transaction
public void EndTransaction()
{
_transaction.Commit();
_connection.Close();
_transaction.Dispose();
_connection.Dispose();
_transaction = null;
_connection = null;
}
// insert a new record as part of a transaction
public int TransactedInsert(string sql, params object[] parms)
{
try
{
using (var command = CreateCommand(sql + ";SELECT SCOPE_IDENTITY();", _connection, parms))
{
command.Transaction = _transaction;
return int.Parse(command.ExecuteScalar().ToString());
}
}
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// update a record as part of a transaction
public int TransactedUpdate(string sql, params object[] parms)
{
try
{
using (var command = CreateCommand(sql, _connection, parms))
{
command.Transaction = _transaction;
return command.ExecuteNonQuery();
}
}
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// delete a record as apart of a transaction
public int TransactedDelete(string sql, params object[] parms)
{
return TransactedUpdate(sql, parms);
}
#endregion
#region DataSet data access
// returns a DataSet given a query
public DataSet GetDataSet(string sql, params object[] parms)
{
try
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
using (var adapter = CreateAdapter(command))
{
var ds = new DataSet();
adapter.Fill(ds);
return ds;
}
}
}
}
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// returns a DataTable given a query
public DataTable GetDataTable(string sql, params object[] parms)
{
try
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(sql, connection, parms))
{
using (var adapter = CreateAdapter(command))
{
var dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
}
}
catch (Exception ex) { throw new DbException(sql, parms, ex); }
}
// returns a DataRow given a query
public DataRow GetDataRow(string sql, params object[] parms)
{
var dataTable = GetDataTable(sql, parms);
return dataTable.Rows.Count > 0 ? dataTable.Rows[0] : null;
}
#endregion
// creates a connection object
DbConnection CreateConnection()
{
var connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
// creates a command object
DbCommand CreateCommand(string sql, DbConnection conn, params object[] parms)
{
var command = factory.CreateCommand();
command.Connection = conn;
command.CommandText = sql;
command.AddParameters(parms);
return command;
}
// creates an adapter object
DbDataAdapter CreateAdapter(DbCommand command)
{
var adapter = factory.CreateDataAdapter();
adapter.SelectCommand = command;
return adapter;
}
}
// extension methods
public static class DbExtentions
{
// adds parameters to a command. either named or ordinal parameters.
public static void AddParameters(this DbCommand command, object[] parms)
{
if (parms != null && parms.Length > 0)
{
// named parameters. Used in INSERT, UPDATE, DELETE
if (parms[0] != null && parms[0].ToString()[0] == '@')
{
for (int i = 0; i < parms.Length; i += 2)
{
var p = command.CreateParameter();
p.ParameterName = parms[i].ToString();
// No empty strings to the database
if (parms[i + 1] is string && (string)parms[i + 1] == "")
parms[i + 1] = null;
p.Value = parms[i + 1] ?? DBNull.Value;
command.Parameters.Add(p);
}
}
else // ordinal parameters. Used in SELECT
{
for (int i = 0; i < parms.Length; i++)
{
// Allow no empty strings to the database
if (parms[i] is string && (string)parms[i] == "")
parms[i] = null;
var p = command.CreateParameter();
p.ParameterName = "@" + i;
p.Value = parms[i] ?? DBNull.Value;
command.Parameters.Add(p);
}
}
}
}
// iterate over fields in datareader and returns an expando object
public static dynamic ToExpando(this IDataReader reader)
{
var dictionary = new ExpandoObject() as IDictionary<string, object>;
for (int i = 0; i < reader.FieldCount; i++)
dictionary.Add(reader.GetName(i), reader[i] == DBNull.Value ? null : reader[i]);
return dictionary as ExpandoObject;
}
}
// custom exception which holds Db execution context
public class DbException : Exception
{
public DbException()
{
}
public DbException(string message)
: base("In Db: " + message)
{
}
public DbException(string message, Exception innerException)
: base("In Db: " + message, innerException)
{
}
public DbException(string sql, object[] parms, Exception innerException)
: base("In Db: " + string.Format("Sql: {0} Parms: {1}", (sql ?? "--"),
(parms != null ? string.Join(",", Array.ConvertAll<object, string>(parms, o => (o ?? "null").ToString())) : "--")),
innerException)
{
}
}
#endregion
#region Domain Layer
// entity class. base class to all domain objects
public partial class Entity<T> where T : Entity<T>, new()
{
protected static string tableName { get; set; }
protected static string keyName { get; set; }
protected static Db db { get; set; }
protected static bool audit { get; set; }
static Dictionary<string, PropertyInfo> props { get; set; }
static Dictionary<string, SchemaMap> map { get; set; }
static string sqlSelect { get; set; }
static string sqlInsert { get; set; }
static string sqlUpdate { get; set; }
static string sqlDelete { get; set; }
static string sqlPaged { get; set; }
#region Static initialization
static Entity()
{
Init();
}
// this allows custom db, table, and key to be specified at startup
public static void Init(Db db = null, string table = null, string key = null)
{
InitDb(db, table, key);
InitMap();
InitSelect();
InitInsert();
InitUpdate();
InitDelete();
InitPaged();
}
// sets db, table and primary key names
static void InitDb(Db _db, string table, string key)
{
db = _db ?? new ArtDb();
tableName = table ?? typeof(T).Name;
keyName = key ?? "Id";
}
// creates a column-to-property map and their default values
static void InitMap()
{
props = typeof(T).GetProperties().ToDictionary(p => p.Name);
map = new Dictionary<string, SchemaMap>();
foreach (dynamic column in Columns)
{
if (props.ContainsKey(column.COLUMN_NAME))
{
map.Add(column.COLUMN_NAME, new SchemaMap
{
Prop = props[column.COLUMN_NAME],
Default = Default(column.COLUMN_DEFAULT)
});
}
}
}
static string[] auditColumns = new[] { "CreatedOn", "CreatedBy", "ChangedOn", "ChangedBy" };
// retrieves column schema data from database
static IEnumerable<dynamic> Columns
{
get
{
// get all columns for table
string sql = @"SELECT COLUMN_NAME, COLUMN_DEFAULT, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @0";
var columns = db.Query(sql, tableName);
var noAuditColumns = columns.Where(c => !auditColumns.Contains((string)c.COLUMN_NAME));
// with all audit columns present auditing will be supported
audit = columns.Count() - noAuditColumns.Count() == auditColumns.Count();
if (audit) return noAuditColumns;
return columns;
}
}
// returns clean column default value
static object Default(string value)
{
if (value.IsNullOrEmpty()) return null;
else if (value.Contains("getdate()")) return "getdate()";
else if (value.Contains("newid()")) return Guid.NewGuid();
string val = value.Replace("(N'", "").Replace("(", "").Replace(")", "").Replace("'", "");
// cast default values
int i;
if (int.TryParse(val, out i)) return i;
double d;
if (double.TryParse(val, out d)) return d;
return val;
}
#endregion
#region Constructors
// default contructor
public Entity() { }
// creates new entity with optional default values
public Entity(bool defaults = false)
{
if (defaults)
{
foreach (var item in map.Values)
item.Prop.SetValue(this, item.Default.OrNow(), null);
}
}
#endregion
// retrieves a single object by id
public T Single(int? id)
{
string sql = CreateSelect(keyName + " = @0 ");
return db.Read(sql, Make, id).FirstOrDefault();
}
// retrieves a single object with a where clause
public T Single(string where = null, params object[] parms)
{
string sql = CreateSelect(where);
return db.Read(sql, Make, parms).FirstOrDefault();
}
// retrieves a list of objects by their ids
public IEnumerable<T> All(string ids)
{
string sql = CreateSelect(keyName + " IN (" + ids + ") ");
return db.Read(sql, Make, null);
}
// retrieves a list of objects given several criteria
public IEnumerable<T> All(string where = null, string orderBy = null, int top = 0, params object[] parms)
{
string sql = CreateSelect(where, orderBy, top);
return db.Read(sql, Make, parms);
}
// retrieves a paged list of objects given several criteia
public IEnumerable<T> Paged(out int totalRows, string where = null, string orderBy = null, int page = 0, int pageSize = 20, params object[] parms)
{
totalRows = Count(where, parms);
string sql = CreatePaged(where, orderBy, page, pageSize);
return db.Read(sql, Make, parms);
}
// retrieves any scalar value by criteria
public virtual object Scalar(string operation, string column = null, string where = null, params object[] parms)
{
string sql = CreateScalar(operation, column, where);
return db.Scalar(sql, parms);
}
// retrieves a scalar count value by criteria
public virtual int Count(string where = null, params object[] parms)
{
string sql = CreateScalar("COUNT", keyName, where);
return (int)db.Scalar(sql, parms);
}
// retrieves a scalar max value by criteria
public virtual object Max(string column = null, string where = null, params object[] parms)
{
string sql = CreateScalar("MAX", column ?? keyName, where);
object o = db.Scalar(sql, parms);
return o is DBNull ? null : o;
}
// retrieves a scalar min value by criteria
public virtual object Min(string column = null, string where = null, params object[] parms)
{
string sql = CreateScalar("MIN", column ?? keyName, where);
object o = db.Scalar(sql, parms);
return o is DBNull ? null : o;
}
// retrieves a scalar sum value by criteria
public virtual object Sum(string column = null, string where = null, params object[] parms)
{
string sql = CreateScalar("SUM", column ?? keyName, where);
object o = db.Scalar(sql, parms);
return o is DBNull ? null : o;
}
// iterates over data reader fields and populates an entity instance
static Func<IDataReader, T> Make = reader =>
{
T t = new T();
for (int i = 0; i < reader.FieldCount; i++)
{
string key = reader.GetName(i);
object val = reader[i] == DBNull.Value ? null : reader[i];
map[key].Prop.SetValue(t, val, null);
}
return t;
};
// iterates over object properties and prepares these as sql parameters
protected object[] Take()
{
var objects = new List<object>();
foreach (var item in map.Values)
{
objects.Add("@" + item.Prop.Name);
objects.Add(item.Prop.GetValue(this, null));
}
if (audit)
{
var dt = DateTime.Now;
var userId = TryGetUserId();
objects.Add("@CreatedOn"); objects.Add(dt);
objects.Add("@CreatedBy"); objects.Add(userId);
objects.Add("@ChangedOn"); objects.Add(dt);
objects.Add("@ChangedBy"); objects.Add(userId);
}
return objects.ToArray();
}
// try getting user id from thread
protected virtual int? TryGetUserId()
{
if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
return null;
int? userId = null;
try
{
// principal is of type CustomPrincipal as defined in Web project
dynamic principal = Thread.CurrentPrincipal;
userId = principal.UserId;
if (userId != null) return userId;
}
catch { /* no action */}
return userId;
}
// retrieves a list of dynamic objects using an arbitrary sql query
public IEnumerable<T> Query(string sql, params object[] parms)
{
var items = db.Query(sql, parms);
foreach (var item in items)
{
yield return ToType(item);
}
}
// maps an expando object to a typed entity instance
static Func<ExpandoObject, T> ToType = expando =>
{
T t = new T();
var dictionary = expando as IDictionary<string, object>;
foreach (var key in dictionary.Keys)
{
if (map.ContainsKey(key))
map[key].Prop.SetValue(t, dictionary[key], null);
}
return t;
};
// executes any sql in database
public void Execute(string sql, params object[] parms)
{
db.Execute(sql, parms);
}
// helper: creates a sql select statement
string CreateSelect(string where, string orderBy = null, int top = 0)
{
string t = top > 0 ? "TOP " + top : null;
string w = where.IsNullOrEmpty() ? null : "WHERE " + where;
string o = "ORDER BY " + (orderBy.IsNullOrEmpty() ? keyName : orderBy);
return string.Format(sqlSelect, t, w, o);
}
// helper: creates a sql select statement for pagination
string CreatePaged(string where, string orderBy, int page, int pageSize)
{
string t = "TOP " + pageSize;
string w = where.IsNullOrEmpty() ? null : "WHERE " + where;
string o = orderBy.IsNullOrEmpty() ? keyName : orderBy;
string r = "WHERE Row > " + ((page - 1) * pageSize);
return string.Format(sqlPaged, t, w, o, r);
}
// helper: creates a scalar sql select statement
string CreateScalar(string operation, string column, string where = null)
{
string op = operation.ToUpper();
string c = column ?? keyName;
string t = tableName.Bracket();
string w = where.IsNullOrEmpty() ? null : "WHERE " + where;
return string.Format("SELECT {0}({1}) FROM {2} {3}", op, c, t, w);
}
// indexer. this provides easy access to properties
object this[string name]
{
get { return map[name].Prop.GetValue(this, null); }
set { map[name].Prop.SetValue(this, value, null); }
}
#region Initialize Sql Statements
// builds a sql select template string
static void InitSelect()
{
var cols = new StringBuilder();
foreach (var key in map.Keys)
cols.AppendFormat("{0}, ", key);
// {{0}} is placeholders for TOP, {{1}} and {{2}} for WHERE, ORDER BY.
string sql = "SELECT {{0}} {0} FROM {1} {{1}} {{2}}";
sqlSelect = string.Format(sql, cols.TrimEnd(), tableName.Bracket());
}
// builds a sql select template string for pagination
static void InitPaged()
{
var cols = new StringBuilder();
foreach (var key in map.Keys)
cols.AppendFormat("{0}, ", key);
// {{0}} is for TOP, {{1}} and {{2}} for WHERE, ORDER BY, {{3}} for Row WHERE.
string sql = "SELECT {{0}} {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {{2}}) AS Row, {0} FROM {1} {{1}} ) AS Paged {{3}}";
sqlPaged = string.Format(sql, cols.TrimEnd(), tableName.Bracket());
}
// builds a sql insert template string
static void InitInsert()
{
var cols = new StringBuilder();
var vals = new StringBuilder();
foreach (var key in PropsWithoutPrimaryKey)
{
cols.AppendFormat("{0}, ", key);
vals.AppendFormat("@{0}, ", key);
}
string sql = "INSERT INTO {0} ({1}) VALUES ({2})";
sqlInsert = string.Format(sql, tableName.Bracket(), cols.TrimEnd(), vals.TrimEnd());
}
// builds a sql update template string
static void InitUpdate()
{
var sets = new StringBuilder();
foreach (var key in PropsWithoutPrimaryKey)
{
// don't include 'create' audit fields
if (audit && (key == "CreatedOn" || key == "CreatedBy")) continue;
sets.AppendFormat("{0}=@{1}, ", key, key);
}
string sql = "UPDATE {0} SET {1} WHERE {2} = @{3}";
sqlUpdate = string.Format(sql, tableName.Bracket(), sets.TrimEnd(), keyName, keyName);
}
// builds a sql delete template string
static void InitDelete()
{
string sql = "DELETE FROM {0} WHERE {1} = @{2}";
sqlDelete = string.Format(sql, tableName.Bracket(), keyName, keyName);
}
// returns all list of properties except primary key
static IEnumerable<string> PropsWithoutPrimaryKey
{
get
{
foreach (var key in map.Keys)
if (key != keyName)
yield return key;
if (audit)
foreach (var key in auditColumns)
yield return key;
}
}
#endregion
// partial methods that allow custom coding (for all entities) before and after all db operations
partial void OnInsertingAll(ref string sql);
partial void OnInsertedAll();
partial void OnUpdatingAll(ref string sql);
partial void OnUpdatedAll();
partial void OnDeletingAll(ref string sql);
partial void OnDeletedAll();
// virtual methods that allow custom coding (by entity type) before and after all db operations
protected virtual void OnInserting(ref string sql) { }
protected virtual void OnInserted() { }
protected virtual void OnUpdating(ref string sql) { }
protected virtual void OnUpdated() { }
protected virtual void OnDeleting(ref string sql) { }
protected virtual void OnDeleted() { }
// inserts current entity instance
public virtual void Insert()
{
string sql = sqlInsert;
OnInsertingAll(ref sql);
OnInserting(ref sql);
this[keyName] = db.Insert(sql, Take());
OnInserted();
OnInsertedAll();
}
// updates current entity instance
public virtual void Update()
{
string sql = sqlUpdate;
OnUpdatingAll(ref sql);
OnUpdating(ref sql);
db.Update(sql, Take());
OnUpdated();
OnUpdatedAll();
}
// deletes current entity instance
public virtual void Delete()
{
string sql = sqlDelete;
OnDeletingAll(ref sql);
OnDeleting(ref sql);
db.Delete(sql, Take());
OnDeleted();
OnDeletedAll();
}
#region Validation
protected virtual void Validate() { }
// executes validations and returns a boolean result
public bool IsValid
{
get
{
Errors.Clear();
Validate();
return Errors.Count == 0;
}
}
public Dictionary<string, string> Errors = new Dictionary<string, string>();
#endregion
#region Transacted actions
// inserts current entity instance as part of an ongoing transaction
public virtual void TransactedInsert(Db db)
{
string sql = sqlInsert;
OnInsertingAll(ref sql);
OnInserting(ref sql);
this[keyName] = db.TransactedInsert(sql, Take());
OnInserted();
OnInsertedAll();
}
// updates current entity instance as part of an ongoing transaction
public virtual void TransactedUpdate(Db db)
{
string sql = sqlUpdate;
OnUpdatingAll(ref sql);
OnUpdating(ref sql);
db.TransactedUpdate(sql, Take());
OnUpdated();
OnUpdatedAll();
}
// deletes current entity instance as part of an ongoing transaction
public virtual void TransactedDelete(Db db)
{
string sql = sqlDelete;
OnDeletingAll(ref sql);
OnDeleting(ref sql);
db.TransactedDelete(sql, Take());
OnDeleted();
OnDeletedAll();
}
#endregion
// holds an object property and its default value
class SchemaMap
{
public PropertyInfo Prop { get; set; }
public object Default { get; set; }
}
}
// entity extension
static class EntityExtensions
{
public static string TrimEnd(this StringBuilder sb)
{
return sb.ToString().TrimEnd(new char[] { ',', ' ', '|' });
}
public static string Bracket(this string item)
{
return "[" + item + "]";
}
public static bool IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s);
}
public static object OrNow(this object value)
{
if (value != null && value.ToString() == "getdate()")
return DateTime.Now;
return value;
}
}
#endregion
#region Repository Layer
// repository. base class to all repositories
public partial class Repository<T> where T : Entity<T>, new()
{
static T t = new T();
public virtual T Single(int? id)
{
return t.Single(id);
}
public virtual T Single(string where = null, params object[] parms)
{
return t.Single(where, parms);
}
public virtual IEnumerable<T> All(string ids)
{
return t.All(ids);
}
public virtual IEnumerable<T> All(string where = null, string orderBy = null, int top = 0, params object[] parms)
{
return t.All(where, orderBy, top, parms);
}
public virtual IEnumerable<T> Paged(out int totalRows, string where = null, string orderBy = null, int page = 0, int pageSize = 20, params object[] parms)
{
return t.Paged(out totalRows, where, orderBy, page, pageSize, parms);
}
public virtual void Insert(T t)
{
t.Insert();
}
public virtual void Update(T t)
{
t.Update();
}
public virtual void Delete(T t)
{
t.Delete();
}
public virtual object Scalar(string operation, string column, string where = null, params object[] parms)
{
return t.Scalar(operation, column, where, parms);
}
public virtual int Count(string where = null, params object[] parms)
{
return t.Count(where, parms);
}
public virtual object Max(string column = null, string where = null, params object[] parms)
{
return t.Max(column, where, parms);
}
public virtual object Min(string column = null, string where = null, params object[] parms)
{
return t.Min(column, where, parms);
}
public virtual object Sum(string column, string where = null, params object[] parms)
{
return t.Sum(column, where, parms);
}
public virtual IEnumerable<T> Query(string sql, params object[] parms)
{
return t.Query(sql, parms);
}
public virtual void Execute(string sql, params object[] parms)
{
t.Execute(sql, parms);
}
}
#endregion
#region Unit Of Work Pattern
// manages local transactions
public partial class UnitOfWork : IDisposable
{
protected Db db { get; set; }
public UnitOfWork(Db db)
{
this.db = db;
db.BeginTransaction();
}
public virtual void Insert<T>(T entity) where T : Entity<T>, new()
{
entity.TransactedInsert(db);
}
public virtual void Update<T>(T entity) where T : Entity<T>, new()
{
entity.TransactedUpdate(db);
}
public virtual void Delete<T>(T entity) where T : Entity<T>, new()
{
entity.TransactedDelete(db);
}
public virtual void Dispose()
{
db.EndTransaction();
}
}
// manages distributed transactions.
public partial class UnitOfWorkDistributed : IDisposable
{
protected TransactionScope scope;
public UnitOfWorkDistributed()
{
// TransactionScope requires that MSDTC is running.
// first ensure that MSDTC runs, then uncomment line below
// scope = new TransactionScope();
}
public virtual void Complete()
{
if (scope != null) scope.Complete();
scope = null;
}
public virtual void Dispose()
{
Complete();
}
}
#endregion
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using Lucene.Net.Support;
using TermPositions = Lucene.Net.Index.TermPositions;
namespace Lucene.Net.Search
{
sealed class SloppyPhraseScorer:PhraseScorer
{
private int slop;
private PhrasePositions[] repeats;
private PhrasePositions[] tmpPos; // for flipping repeating pps.
private bool checkedRepeats;
internal SloppyPhraseScorer(Weight weight, TermPositions[] tps, int[] offsets, Similarity similarity, int slop, byte[] norms):base(weight, tps, offsets, similarity, norms)
{
this.slop = slop;
}
/// <summary> Score a candidate doc for all slop-valid position-combinations (matches)
/// encountered while traversing/hopping the PhrasePositions.
/// <br/> The score contribution of a match depends on the distance:
/// <br/> - highest score for distance=0 (exact match).
/// <br/> - score gets lower as distance gets higher.
/// <br/>Example: for query "a b"~2, a document "x a b a y" can be scored twice:
/// once for "a b" (distance=0), and once for "b a" (distance=2).
/// <br/>Possibly not all valid combinations are encountered, because for efficiency
/// we always propagate the least PhrasePosition. This allows to base on
/// PriorityQueue and move forward faster.
/// As result, for example, document "a b c b a"
/// would score differently for queries "a b c"~4 and "c b a"~4, although
/// they really are equivalent.
/// Similarly, for doc "a b c b a f g", query "c b"~2
/// would get same score as "g f"~2, although "c b"~2 could be matched twice.
/// We may want to fix this in the future (currently not, for performance reasons).
/// </summary>
protected internal override float PhraseFreq()
{
int end = InitPhrasePositions();
float freq = 0.0f;
bool done = (end < 0);
while (!done)
{
PhrasePositions pp = pq.Pop();
int start = pp.position;
int next = pq.Top().position;
bool tpsDiffer = true;
for (int pos = start; pos <= next || !tpsDiffer; pos = pp.position)
{
if (pos <= next && tpsDiffer)
start = pos; // advance pp to min window
if (!pp.NextPosition())
{
done = true; // ran out of a term -- done
break;
}
PhrasePositions pp2 = null;
tpsDiffer = !pp.repeats || (pp2 = TermPositionsDiffer(pp)) == null;
if (pp2 != null && pp2 != pp)
{
pp = Flip(pp, pp2); // flip pp to pp2
}
}
int matchLength = end - start;
if (matchLength <= slop)
freq += Similarity.SloppyFreq(matchLength); // score match
if (pp.position > end)
end = pp.position;
pq.Add(pp); // restore pq
}
return freq;
}
// flip pp2 and pp in the queue: pop until finding pp2, insert back all but pp2, insert pp back.
// assumes: pp!=pp2, pp2 in pq, pp not in pq.
// called only when there are repeating pps.
private PhrasePositions Flip(PhrasePositions pp, PhrasePositions pp2)
{
int n = 0;
PhrasePositions pp3;
//pop until finding pp2
while ((pp3 = pq.Pop()) != pp2)
{
tmpPos[n++] = pp3;
}
//insert back all but pp2
for (n--; n >= 0; n--)
{
pq.InsertWithOverflow(tmpPos[n]);
}
//insert pp back
pq.Add(pp);
return pp2;
}
/// <summary> Init PhrasePositions in place.
/// There is a one time initialization for this scorer:
/// <br/>- Put in repeats[] each pp that has another pp with same position in the doc.
/// <br/>- Also mark each such pp by pp.repeats = true.
/// <br/>Later can consult with repeats[] in termPositionsDiffer(pp), making that check efficient.
/// In particular, this allows to score queries with no repetitions with no overhead due to this computation.
/// <br/>- Example 1 - query with no repetitions: "ho my"~2
/// <br/>- Example 2 - query with repetitions: "ho my my"~2
/// <br/>- Example 3 - query with repetitions: "my ho my"~2
/// <br/>Init per doc w/repeats in query, includes propagating some repeating pp's to avoid false phrase detection.
/// </summary>
/// <returns> end (max position), or -1 if any term ran out (i.e. done)
/// </returns>
/// <throws> IOException </throws>
private int InitPhrasePositions()
{
int end = 0;
// no repeats at all (most common case is also the simplest one)
if (checkedRepeats && repeats == null)
{
// build queue from list
pq.Clear();
for (PhrasePositions pp = first; pp != null; pp = pp.next)
{
pp.FirstPosition();
if (pp.position > end)
end = pp.position;
pq.Add(pp); // build pq from list
}
return end;
}
// position the pp's
for (PhrasePositions pp = first; pp != null; pp = pp.next)
pp.FirstPosition();
// one time initializatin for this scorer
if (!checkedRepeats)
{
checkedRepeats = true;
// check for repeats
HashMap<PhrasePositions, object> m = null;
for (PhrasePositions pp = first; pp != null; pp = pp.next)
{
int tpPos = pp.position + pp.offset;
for (PhrasePositions pp2 = pp.next; pp2 != null; pp2 = pp2.next)
{
int tpPos2 = pp2.position + pp2.offset;
if (tpPos2 == tpPos)
{
if (m == null)
{
m = new HashMap<PhrasePositions, object>();
}
pp.repeats = true;
pp2.repeats = true;
m[pp] = null;
m[pp2] = null;
}
}
}
if (m != null)
{
repeats = m.Keys.ToArray();
}
}
// with repeats must advance some repeating pp's so they all start with differing tp's
if (repeats != null)
{
for (int i = 0; i < repeats.Length; i++)
{
PhrasePositions pp = repeats[i];
PhrasePositions pp2;
while ((pp2 = TermPositionsDiffer(pp)) != null)
{
if (!pp2.NextPosition())
// out of pps that do not differ, advance the pp with higher offset
return - 1; // ran out of a term -- done
}
}
}
// build queue from list
pq.Clear();
for (PhrasePositions pp = first; pp != null; pp = pp.next)
{
if (pp.position > end)
end = pp.position;
pq.Add(pp); // build pq from list
}
if (repeats != null)
{
tmpPos = new PhrasePositions[pq.Size()];
}
return end;
}
/// <summary> We disallow two pp's to have the same TermPosition, thereby verifying multiple occurrences
/// in the query of the same word would go elsewhere in the matched doc.
/// </summary>
/// <returns> null if differ (i.e. valid) otherwise return the higher offset PhrasePositions
/// out of the first two PPs found to not differ.
/// </returns>
private PhrasePositions TermPositionsDiffer(PhrasePositions pp)
{
// efficiency note: a more efficient implementation could keep a map between repeating
// pp's, so that if pp1a, pp1b, pp1c are repeats term1, and pp2a, pp2b are repeats
// of term2, pp2a would only be checked against pp2b but not against pp1a, pp1b, pp1c.
// However this would complicate code, for a rather rare case, so choice is to compromise here.
int tpPos = pp.position + pp.offset;
for (int i = 0; i < repeats.Length; i++)
{
PhrasePositions pp2 = repeats[i];
if (pp2 == pp)
continue;
int tpPos2 = pp2.position + pp2.offset;
if (tpPos2 == tpPos)
return pp.offset > pp2.offset?pp:pp2; // do not differ: return the one with higher offset.
}
return null;
}
}
}
| |
//#define LOG
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
namespace ICSimulator
{
public abstract class Router
{
public Coord coord;
public int ID { get { return coord.ID; } }
public bool enable;
public Link[] linkOut = new Link[4];
public Link[] linkIn = new Link[4];
public Link[] LLinkIn;
public Link[] LLinkOut;
public Link[] GLinkIn;
public Link[] GLinkOut;
public Router[] neigh = new Router[4];
public int neighbors;
public int RouterType = -1;
protected string routerName;
protected Node m_n;
// Keep track of the current router's average queue length over the
// last INJ_RATE_WIN cycles
public const int AVG_QLEN_WIN=1000;
public float avg_qlen;
public int[] qlen_win;
public int qlen_ptr;
public int qlen_count;
public ulong m_lastInj;
public ulong last_starve, starve_interval;
public ulong m_inject = 0;
public ulong Inject { get { return m_inject; } }
// --------------------------------------------------------------------
public struct PreferredDirection
{
public int xDir;
public int yDir;
}
public Router(Coord myCoord)
{
coord = myCoord;
m_n = Simulator.network.nodes[ID];
routerName = "Router";
neighbors = 0;
m_lastInj = 0;
last_starve = 0;
starve_interval = 0;
qlen_win = new int[AVG_QLEN_WIN];
}
public Router()
{
routerName = "Router";
qlen_win = new int[AVG_QLEN_WIN];
}
public void setNode(Node n)
{
m_n = n;
}
/********************************************************
* PUBLIC API
********************************************************/
// called from Network
public void doStep()
{
statsInput();
_doStep();
//statsOutput();
}
protected abstract void _doStep(); // called from Network
public virtual void Scalable_doStep() {return;}
public abstract bool canInjectFlit(Flit f); // called from Processor
public abstract void InjectFlit(Flit f); // called from Processor
public virtual int rank(Flit f1, Flit f2) { return 0; }
// finally, subclasses should call myProcessor.ejectFlit() whenever a flit
// arrives (or is part of a reassembled packet ready to be delivered, or whatever)
// also, subclasses should call statsInput() before removing
// inputs, statsOutput() after placing outputs, and
// statsInjectFlit(f) if a flit is injected,
// and statsEjectFlit(f) if a flit is ejected.
// Buffered hierarchical ring: check downstream ring/ejection buffer and see if it's available
public virtual bool creditAvailable(Flit f) {return false;}
// Whether it wants to into the global ring or loca ring
public virtual bool productive(Flit f, int level) {return false;}
// for flush/retry mechanisms: clear all router state.
public virtual void flush() { }
// only work for 4x4 network
public static bool [] starved = new bool [Config.N + 16];
public static bool [] now_starved = new bool [Config.N + 16];
public static Queue<bool[]> starveDelay = new Queue<bool[]>();
public static Queue<bool[]> throttleDelay = new Queue<bool[]>();
public static bool [] throttle = new bool [Config.N];
public static int n = 0;
public static int working = -1;
public static void livelockFreedom()
{
bool [] starvetmp = new bool [Config.N + 16];
bool [] throttletmp = new bool [Config.N];
for (int i = 0; i < Config.N + 16; i++)
starvetmp[i] = starved[i];
starveDelay.Enqueue(starvetmp);
if (starveDelay.Count > Config.starveDelay)
now_starved = starveDelay.Dequeue();
// else
// Console.WriteLine("starveDelay.Count:{0}", starveDelay.Count);
// Console.WriteLine("n = {0}", n);
if (now_starved[n])
{
/* Console.WriteLine("cycle: {0}", Simulator.CurrentRound);
for (int i = 0; i < 24; i++)
Console.WriteLine("starved[{0}] = {1}\tnow_starved[{2}] = {3}", i, starved[i], i, now_starved[i]);
Console.WriteLine("\n");
for (int j = 0; j < starveDelay.Count; j++)
{
for (int i = 0; i < 24; i++)
Console.WriteLine("now_starved[{0}] = {1}", i, now_starved[i]);
now_starved = starveDelay.Dequeue();
}
*/
// Console.ReadKey(true);
if (throttletmp[(n+1) % Config.N] == false)
Simulator.stats.starveTriggered.Add(1);
Simulator.stats.allNodeThrottled.Add(1);
for (int i = 0; i < Config.N; i++)
if (i != n)
throttletmp[i] = true;
working = n;
}
else
working = -1;
if (working == -1)
{
for (int i = 0; i < Config.N; i++)
throttletmp[i] = false;
n = (n == Config.N + 8 - 1) ? 0 : n + 1;
}
throttleDelay.Enqueue(throttletmp);
if (throttleDelay.Count > Config.starveDelay)
throttle = throttleDelay.Dequeue();
// for (int i = 0; i < Config.N; i++)
// Console.WriteLine("delay {0}. throttle[{1}] : {2}", Config.starveDelay, i, throttle[i]);
// Console.WriteLine("\n");
// Console.ReadKey(true);
}
/********************************************************
* ROUTING HELPERS
********************************************************/
protected PreferredDirection determineDirection(Flit f)
{
return determineDirection(f, new Coord(0, 0));
}
protected PreferredDirection determineDirection(Flit f, Coord current)
{
PreferredDirection pd;
pd.xDir = Simulator.DIR_NONE;
pd.yDir = Simulator.DIR_NONE;
if (f.state == Flit.State.Placeholder) return pd;
//if (f.packet.ID == 238)
// Console.WriteLine("packet 238 at ID ({0},{1}), wants ({2},{3})", current.x, current.y, f.packet.dest.x, f.packet.dest.y);
return determineDirection(f.dest);
}
protected PreferredDirection determineDirection(Coord c)
{
PreferredDirection pd;
pd.xDir = Simulator.DIR_NONE;
pd.yDir = Simulator.DIR_NONE;
if(Config.torus) {
int x_sdistance = Math.Abs(c.x - coord.x);
int x_wdistance = Config.network_nrX - Math.Abs(c.x - coord.x);
int y_sdistance = Math.Abs(c.y - coord.y);
int y_wdistance = Config.network_nrY - Math.Abs(c.y - coord.y);
bool x_dright, y_ddown;
x_dright = coord.x < c.x;
y_ddown = c.y < coord.y;
if(c.x == coord.x)
pd.xDir = Simulator.DIR_NONE;
else if(x_sdistance < x_wdistance)
pd.xDir = (x_dright) ? Simulator.DIR_RIGHT : Simulator.DIR_LEFT;
else
pd.xDir = (x_dright) ? Simulator.DIR_LEFT : Simulator.DIR_RIGHT;
if(c.y == coord.y)
pd.yDir = Simulator.DIR_NONE;
else if(y_sdistance < y_wdistance)
pd.yDir = (y_ddown) ? Simulator.DIR_DOWN : Simulator.DIR_UP;
else
pd.yDir = (y_ddown) ? Simulator.DIR_UP : Simulator.DIR_DOWN;
} else {
if (c.x > coord.x)
pd.xDir = Simulator.DIR_RIGHT;
else if (c.x < coord.x)
pd.xDir = Simulator.DIR_LEFT;
else
pd.xDir = Simulator.DIR_NONE;
if (c.y > coord.y)
pd.yDir = Simulator.DIR_UP;
else if (c.y < coord.y)
pd.yDir = Simulator.DIR_DOWN;
else
pd.yDir = Simulator.DIR_NONE;
}
if (Config.dor_only && pd.xDir != Simulator.DIR_NONE)
pd.yDir = Simulator.DIR_NONE;
return pd;
}
// returns true if the direction is good for this packet.
protected bool isDirectionProductive(Coord dest, int direction)
{
bool answer = false;
switch (direction)
{
case Simulator.DIR_UP: answer = (dest.y > coord.y); break;
case Simulator.DIR_RIGHT: answer = (dest.x > coord.x); break;
case Simulator.DIR_LEFT: answer = (dest.x < coord.x); break;
case Simulator.DIR_DOWN: answer = (dest.y < coord.y); break;
default: throw new Exception("This function shouldn't be called in this case!");
}
return answer;
}
protected int dimension_order_route(Flit f)
{
if (f.packet.dest.x < coord.x)
return Simulator.DIR_LEFT;
else if (f.packet.dest.x > coord.x)
return Simulator.DIR_RIGHT;
else if (f.packet.dest.y < coord.y)
return Simulator.DIR_DOWN;
else if (f.packet.dest.y > coord.y)
return Simulator.DIR_UP;
else //if the destination's coordinates are equal to the router's coordinates
return Simulator.DIR_UP;
}
/********************************************************
* STATISTICS
********************************************************/
protected int incomingFlits;
private void statsInput()
{
//int goldenCount = 0;
incomingFlits = 0;
if (Config.topology == Topology.Mesh)
for (int i = 0; i < 4; i++)
if (linkIn[i] != null && linkIn[i].Out != null)
Simulator.stats.flitsToRouter.Add(1);
if (Config.topology == Topology.HR_8drop || Config.topology == Topology.MeshOfRings)
{
if (this is Router_Node)
for (int i = 0; i < 2; i++)
if (linkIn[i].Out != null)
Simulator.stats.flitsToHRnode.Add(1);
if (this is Router_Bridge)
{
if (RouterType == 1)
{
for (int i = 0; i < 2; i++)
if (LLinkIn[i].Out != null)
Simulator.stats.flitsToHRbridge.Add(1);
for (int i = 0; i < 4; i++)
if (GLinkIn[i].Out != null)
Simulator.stats.flitsToHRbridge.Add(1);
}
else if (RouterType == 2)
{
for (int i = 0; i < 4; i++)
if (LLinkIn[i].Out != null)
Simulator.stats.flitsToHRbridge.Add(1);
for (int i = 0; i < 8; i++)
if (GLinkIn[i].Out != null)
Simulator.stats.flitsToHRbridge.Add(1);
}
else
throw new Exception("The RouterType should only be 1 or 2");
}
}
/* if (Config.ScalableRingClustered == false && Config.RingClustered == false && Config.TorusSingleRing == false && Config.HierarchicalRing == false && Config.Simple_HR == false)
{
for (int i = 0; i < 4; i++)
{
if (linkIn[i] != null && linkIn[i].Out != null)
{
linkIn[i].Out.Deflected = false;
if (Simulator.network.golden.isGolden(linkIn[i].Out))
goldenCount++;
incomingFlits++;
}
}
}*/
// Simulator.stats.golden_pernode.Add(goldenCount);
// Simulator.stats.golden_bycount[goldenCount].Add();
//
// Simulator.stats.traversals_pernode[incomingFlits].Add();
}
private void statsOutput()
{
int deflected = 0;
int unproductive = 0;
int traversals = 0;
int links = (Config.RingClustered || Config.ScalableRingClustered)? 2:4;
for (int i = 0; i < links; i++)
{
if (linkOut[i] != null && linkOut[i].In != null)
{
if (linkOut[i].In.Deflected)
{
// deflected! (may still be productive, depending on deflection definition/DOR used)
deflected++;
linkOut[i].In.nrOfDeflections++;
Simulator.stats.deflect_flit_byloc[ID].Add();
if (linkOut[i].In.packet != null)
{
Simulator.stats.deflect_flit_bysrc[linkOut[i].In.packet.src.ID].Add();
Simulator.stats.deflect_flit_byreq[linkOut[i].In.packet.requesterID].Add();
}
}
if (!isDirectionProductive(linkOut[i].In.dest, i))
{
//unproductive!
unproductive++;
Simulator.stats.unprod_flit_byloc[ID].Add();
if (linkOut[i].In.packet != null)
Simulator.stats.unprod_flit_bysrc[linkOut[i].In.packet.src.ID].Add();
}
traversals++;
//linkOut[i].In.deflectTest();
}
}
Simulator.stats.deflect_flit.Add(deflected);
Simulator.stats.deflect_flit_byinc[incomingFlits].Add(deflected);
Simulator.stats.unprod_flit.Add(unproductive);
Simulator.stats.unprod_flit_byinc[incomingFlits].Add(unproductive);
Simulator.stats.flit_traversals.Add(traversals);
int qlen = m_n.RequestQueueLen;
qlen_count -= qlen_win[qlen_ptr];
qlen_count += qlen;
// Compute the average queue length
qlen_win[qlen_ptr] = qlen;
if(++qlen_ptr >= AVG_QLEN_WIN) qlen_ptr=0;
avg_qlen = (float)qlen_count / (float)AVG_QLEN_WIN;
}
protected void statsInjectFlit(Flit f)
{
//if (f.packet.src.ID == 3) Console.WriteLine("inject flit: packet {0}, seq {1}",
// f.packet.ID, f.flitNr);
Simulator.stats.inject_flit.Add();
if (f.isHeadFlit) Simulator.stats.inject_flit_head.Add();
if (f.packet != null)
{
Simulator.stats.inject_flit_bysrc[f.packet.src.ID].Add();
//Simulator.stats.inject_flit_srcdest[f.packet.src.ID, f.packet.dest.ID].Add();
}
if (f.packet != null && f.packet.injectionTime == ulong.MaxValue)
f.packet.injectionTime = Simulator.CurrentRound;
f.injectionTime = Simulator.CurrentRound;
ulong hoq = Simulator.CurrentRound - m_lastInj;
m_lastInj = Simulator.CurrentRound;
Simulator.stats.hoq_latency.Add(hoq);
Simulator.stats.hoq_latency_bysrc[coord.ID].Add(hoq);
m_inject++;
}
protected void statsEjectFlit(Flit f)
{
//if (f.packet.src.ID == 3) Console.WriteLine("eject flit: packet {0}, seq {1}",
// f.packet.ID, f.flitNr);
// per-flit latency stats
ulong net_latency = Simulator.CurrentRound - f.injectionTime;
ulong total_latency = Simulator.CurrentRound - f.packet.creationTime;
ulong inj_latency = total_latency - net_latency;
Simulator.stats.flit_inj_latency.Add(inj_latency);
Simulator.stats.flit_net_latency.Add(net_latency);
Simulator.stats.flit_total_latency.Add(total_latency);
Simulator.stats.ejectTrial.Add(f.ejectTrial);
Simulator.stats.minNetLatency.Add(f.firstEjectTrial - f.injectionTime);
if (f.ejectTrial > 1)
{
Simulator.stats.destDeflectedNetLatency.Add(net_latency);
Simulator.stats.destDeflectedMinLatency.Add(f.firstEjectTrial - f.injectionTime);
Simulator.stats.multiEjectTrialFlits.Add();
}
else if (f.ejectTrial == 1)
Simulator.stats.singleEjectTrialFlits.Add();
//else if (this is Router_Flit)
// throw new Exception("The eject trial is incorrect");
if (Config.N == 16)
{
// if (net_latency > 10)
// Console.WriteLine("src: {0}, dest:{1}, latency:{2}", f.packet.src.ID, f.packet.dest.ID, net_latency);
if (f.packet.dest.ID / 4 == f.packet.src.ID / 4)
{
Simulator.stats.flitLocal.Add(1);
Simulator.stats.netLatency_local.Add(net_latency);
}
else if (Math.Abs(f.packet.dest.ID / 4 - f.packet.src.ID / 4) != 2) // one hop
{
Simulator.stats.flit1hop.Add(1);
Simulator.stats.netLatency_1hop.Add(net_latency);
Simulator.stats.timeInBuffer1hop.Add(f.timeSpentInBuffer);
Simulator.stats.timeInTheDestRing.Add(f.timeInTheDestRing);
Simulator.stats.timeInTheSourceRing.Add(f.timeInTheSourceRing);
Simulator.stats.timeInGR1hop.Add(f.timeInGR);
}
else // 2 hop
{
Simulator.stats.flit2hop.Add(1);
Simulator.stats.netLatency_2hop.Add(net_latency);
Simulator.stats.timeInBuffer2hop.Add(f.timeSpentInBuffer);
Simulator.stats.timeInTheDestRing.Add(f.timeInTheDestRing);
Simulator.stats.timeInTheTransitionRing.Add(f.timeInTheTransitionRing);
Simulator.stats.timeInGR2hop.Add(f.timeInGR);
Simulator.stats.timeInTheSourceRing.Add(f.timeInTheSourceRing);
}
Simulator.stats.timeWaitToInject.Add(f.timeWaitToInject);
}
if (Config.N == 64)
{
if (f.packet.dest.ID / 4 == f.packet.src.ID / 4)
Simulator.stats.flitLocal.Add(1);
else if (f.packet.dest.ID /16 == f.packet.src.ID / 16)
Simulator.stats.flitL1Global.Add(1);
}
Simulator.stats.eject_flit.Add();
Simulator.stats.eject_flit_bydest[f.packet.dest.ID].Add();
int minpath = Math.Abs(f.packet.dest.x - f.packet.src.x) + Math.Abs(f.packet.dest.y - f.packet.src.y);
Simulator.stats.minpath.Add(minpath);
Simulator.stats.minpath_bysrc[f.packet.src.ID].Add(minpath);
//f.dumpDeflections();
Simulator.stats.deflect_perdist[f.distance].Add(f.nrOfDeflections);
if(f.nrOfDeflections!=0)
Simulator.stats.deflect_perflit_byreq[f.packet.requesterID].Add(f.nrOfDeflections);
}
protected void statsEjectPacket(Packet p)
{
ulong net_latency = Simulator.CurrentRound - p.injectionTime;
ulong total_latency = Simulator.CurrentRound - p.creationTime;
Simulator.stats.net_latency.Add(net_latency);
Simulator.stats.total_latency.Add(total_latency);
Simulator.stats.net_latency_bysrc[p.src.ID].Add(net_latency);
Simulator.stats.net_latency_bydest[p.dest.ID].Add(net_latency);
//Simulator.stats.net_latency_srcdest[p.src.ID, p.dest.ID].Add(net_latency);
Simulator.stats.total_latency_bysrc[p.src.ID].Add(total_latency);
Simulator.stats.total_latency_bydest[p.dest.ID].Add(total_latency);
//Simulator.stats.total_latency_srcdest[p.src.ID, p.dest.ID].Add(total_latency);
}
public override string ToString()
{
return routerName + " (" + coord.x + "," + coord.y + ")";
}
public string getRouterName()
{
return routerName;
}
public Router neighbor(int dir)
{
int x, y;
switch (dir)
{
case Simulator.DIR_UP: x = coord.x; y = coord.y + 1; break;
case Simulator.DIR_DOWN: x = coord.x; y = coord.y - 1; break;
case Simulator.DIR_RIGHT: x = coord.x + 1; y = coord.y; break;
case Simulator.DIR_LEFT: x = coord.x - 1; y = coord.y; break;
default: return null;
}
// mesh, not torus: detect edge
if (x < 0 || x >= Config.network_nrX || y < 0 || y >= Config.network_nrY) return null;
return Simulator.network.routers[Coord.getIDfromXY(x, y)];
}
public void close()
{
}
public virtual void visitFlits(Flit.Visitor fv)
{
}
public void statsStarve(Flit f)
{
Simulator.stats.starve_flit.Add();
Simulator.stats.starve_flit_bysrc[f.packet.src.ID].Add();
if (last_starve == Simulator.CurrentRound - 1) {
starve_interval++;
} else {
Simulator.stats.starve_interval_bysrc[f.packet.src.ID].Add(starve_interval);
starve_interval = 0;
}
last_starve = Simulator.CurrentRound;
}
public int linkUtil()
{
int count = 0;
for (int i = 0; i < 4; i++)
if (linkIn[i] != null && linkIn[i].Out != null)
count++;
return count;
}
public double linkUtilNeighbors()
{
int tot = 0, used = 0;
for (int dir = 0; dir < 4; dir++)
{
Router n = neighbor(dir);
if (n == null) continue;
tot += n.neighbors;
used += n.linkUtil();
}
return (double)used / tot;
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
CrossPlatformInputManager.SwitchActiveInputMethod (CrossPlatformInputManager.ActiveInputMethod.Hardware); // Default input method was MOBILE (da fuck?)
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace UnityTest
{
[CustomEditor (typeof (AssertionComponent))]
public class AssertionComponentEditor : Editor
{
private readonly DropDownControl<Type> comparerDropDown = new DropDownControl<Type>();
private readonly PropertyPathSelector thisPathSelector = new PropertyPathSelector ("Compare");
private readonly PropertyPathSelector otherPathSelector = new PropertyPathSelector("Compare to");
private bool focusBackToEdit;
#region GUI Contents
private readonly GUIContent guiCheckAfterTimeGuiContent = new GUIContent ("Check after (seconds)", "After how many seconds the assertion should be checked");
private readonly GUIContent guiRepeatCheckTimeGuiContent = new GUIContent ("Repeat check", "Should the check be repeated.");
private readonly GUIContent guiRepeatEveryTimeGuiContent = new GUIContent ("Frequency of repetitions", "How often should the check be done");
private readonly GUIContent guiCheckAfterFramesGuiContent = new GUIContent ("Check after (frames)", "After how many frames the assertion should be checked");
private readonly GUIContent guiRepeatCheckFrameGuiContent = new GUIContent ("Repeat check", "Should the check be repeated.");
#endregion
public AssertionComponentEditor()
{
comparerDropDown.convertForButtonLabel = type => type.Name;
comparerDropDown.convertForGUIContent = type => type.Name;
comparerDropDown.ignoreConvertForGUIContent = types => false;
comparerDropDown.tooltip = "Comparer that will be used to compare values and determine the result of assertion.";
}
public override void OnInspectorGUI ()
{
var script = (AssertionComponent) target;
EditorGUILayout.BeginHorizontal ();
var obj = DrawComparerSelection (script);
script.checkMethods = (CheckMethod)EditorGUILayout.EnumMaskField (script.checkMethods,
EditorStyles.popup,
GUILayout.ExpandWidth (false));
EditorGUILayout.EndHorizontal ();
if(script.IsCheckMethodSelected (CheckMethod.AfterPeriodOfTime))
{
DrawOptionsForAfterPeriodOfTime (script);
}
if (script.IsCheckMethodSelected(CheckMethod.Update))
{
DrawOptionsForOnUpdate (script);
}
if (obj)
{
EditorGUILayout.Space ();
thisPathSelector.Draw(script.Action.go, script.Action,
script.Action.thisPropertyPath, script.Action.GetAccepatbleTypesForA (),
go =>
{
script.Action.go = go;
AssertionExplorerWindow.Reload();
},
s =>
{
script.Action.thisPropertyPath = s;
AssertionExplorerWindow.Reload();
});
EditorGUILayout.Space ();
DrawCustomFields (script);
EditorGUILayout.Space ();
if (script.Action is ComparerBase)
{
DrawCompareToType (script.Action as ComparerBase);
}
}
}
private void DrawOptionsForAfterPeriodOfTime (AssertionComponent script)
{
EditorGUILayout.Space ();
script.checkAfterTime = EditorGUILayout.FloatField (guiCheckAfterTimeGuiContent,
script.checkAfterTime);
if (script.checkAfterTime < 0)
script.checkAfterTime = 0;
script.repeatCheckTime = EditorGUILayout.Toggle (guiRepeatCheckTimeGuiContent,
script.repeatCheckTime);
if (script.repeatCheckTime)
{
script.repeatEveryTime = EditorGUILayout.FloatField (guiRepeatEveryTimeGuiContent,
script.repeatEveryTime);
if (script.repeatEveryTime < 0)
script.repeatEveryTime = 0;
}
}
private void DrawOptionsForOnUpdate (AssertionComponent script)
{
EditorGUILayout.Space ();
script.checkAfterFrames = EditorGUILayout.IntField (guiCheckAfterFramesGuiContent,
script.checkAfterFrames);
if (script.checkAfterFrames < 1)
script.checkAfterFrames = 1;
script.repeatCheckFrame = EditorGUILayout.Toggle (guiRepeatCheckFrameGuiContent,
script.repeatCheckFrame);
if (script.repeatCheckFrame)
{
script.repeatEveryFrame = EditorGUILayout.IntField (guiRepeatEveryTimeGuiContent,
script.repeatEveryFrame);
if (script.repeatEveryFrame < 1)
script.repeatEveryFrame = 1;
}
}
private void DrawCompareToType (ComparerBase comparer)
{
comparer.compareToType = (ComparerBase.CompareToType) EditorGUILayout.EnumPopup ("Compare to type",
comparer.compareToType,
EditorStyles.popup);
if (comparer.compareToType == ComparerBase.CompareToType.CompareToConstantValue)
{
try
{
DrawConstCompareField(comparer);
}
catch (NotImplementedException)
{
Debug.LogWarning("This comparer can't compare to static value");
comparer.compareToType = ComparerBase.CompareToType.CompareToObject;
}
}
else if (comparer.compareToType == ComparerBase.CompareToType.CompareToObject)
{
DrawObjectCompareField(comparer);
}
}
private void DrawObjectCompareField(ComparerBase comparer)
{
otherPathSelector.Draw(comparer.other, comparer,
comparer.otherPropertyPath, comparer.GetAccepatbleTypesForB(),
go =>
{
comparer.other = go;
AssertionExplorerWindow.Reload ();
},
s =>
{
comparer.otherPropertyPath = s;
AssertionExplorerWindow.Reload ();
}
);
}
private void DrawConstCompareField(ComparerBase comparer)
{
if (comparer.ConstValue == null)
{
comparer.ConstValue = comparer.GetDefaultConstValue();
}
var so = new SerializedObject(comparer);
var sp = so.FindProperty ("constantValueGeneric");
if (sp != null)
{
EditorGUILayout.PropertyField (sp, new GUIContent("Constant"), true);
so.ApplyModifiedProperties ();
}
}
private bool DrawComparerSelection (AssertionComponent script)
{
var types = typeof(ActionBase).Assembly.GetTypes();
var allComparers = types.Where(type => type.IsSubclassOf(typeof(ActionBase)) && !type.IsAbstract).ToArray();
if (script.Action == null)
script.Action = (ActionBase)CreateInstance(allComparers.First());
comparerDropDown.Draw(script.Action.GetType (), allComparers,
type =>
{
if (script.Action == null || script.Action.GetType().Name != type.Name)
{
script.Action = (ActionBase)CreateInstance(type);
AssertionExplorerWindow.Reload ();
}
});
return script.Action != null;
}
private void DrawCustomFields (AssertionComponent script)
{
foreach (var prop in script.Action.GetType ().GetFields (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
var type = prop.FieldType;
if (!type.IsSerializable)
continue;
var so = new SerializedObject(script.Action);
var sp = so.FindProperty(prop.Name);
if (sp != null)
{
EditorGUILayout.PropertyField (sp);
so.ApplyModifiedProperties ();
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization;
namespace Odachi.Validation
{
/// <summary>
/// Collection of validation messages.
/// </summary>
[DataContract]
public class ValidationState : ICollection<ValidationMessage>
{
public ValidationState()
{
_messages = new Dictionary<string, IList<ValidationMessage>>();
}
private IDictionary<string, IList<ValidationMessage>> _messages;
public int Count => _messages.Sum(p => p.Value.Count);
/// <summary>
/// Returns validation messages for given field name. Returns zero results if there are no results.
/// </summary>
public IEnumerable<ValidationMessage> this[string key]
{
get
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return _messages.TryGetValue(key, out var result) ? result : Enumerable.Empty<ValidationMessage>();
}
}
/// <summary>
/// Adds a message for given key.
/// </summary>
public void Add(ValidationSeverity severity, string key, string text)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (text == null)
throw new ArgumentNullException(nameof(text));
Add(new ValidationMessage()
{
Severity = severity,
Key = key,
Text = text,
});
}
/// <summary>
/// Adds a message for given key.
/// </summary>
public void Add(ValidationMessage message)
{
if (!_messages.TryGetValue(message.Key, out var propertyState))
_messages.Add(message.Key, propertyState = new List<ValidationMessage>());
propertyState.Add(message);
}
/// <summary>
/// Determines whether collection contains given message.
/// </summary>
public bool Contains(ValidationMessage message)
{
return _messages.Any(p => p.Value.Contains(message));
}
/// <summary>
/// Remove all messages for given key.
/// </summary>
public void Remove(string key)
{
_messages.Remove(key);
}
/// <summary>
/// Remove given message.
/// </summary>
public bool Remove(ValidationMessage message)
{
if (!_messages.TryGetValue(message.Key, out var propertyState))
return false;
return propertyState.Remove(message);
}
/// <summary>
/// Remove all messages.
/// </summary>
public void Clear()
{
_messages.Clear();
}
#region Warnings
/// <summary>
/// Returns whether there are any warnings.
/// </summary>
public bool HasWarnings => _messages.Any(s => s.Value.Any(m => m.Severity == ValidationSeverity.Warning));
/// <summary>
/// Adds warning into the dictionary.
/// </summary>
public void AddWarning(string key, string message)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (message == null)
throw new ArgumentNullException(nameof(message));
Add(ValidationSeverity.Warning, key, message);
}
/// <summary>
/// Returns all warning messages for given key.
/// </summary>
public IEnumerable<ValidationMessage> GetWarningMessages(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (!_messages.TryGetValue(key, out var propertyState))
{
yield break;
}
foreach (var message in propertyState)
{
if (message.Severity != ValidationSeverity.Warning)
{
continue;
}
yield return message;
}
}
/// <summary>
/// Returns first warning message or null for given key.
/// </summary>
public ValidationMessage GetWarningMessage(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return GetWarningMessages(key).FirstOrDefault();
}
/// <summary>
/// Returns first warning message text or null for given key.
/// </summary>
public string GetWarningText(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return GetWarningMessages(key).FirstOrDefault()?.Text;
}
#endregion
#region Errors
/// <summary>
/// Returns whether there are any errors.
/// </summary>
public bool HasErrors => _messages.Any(s => s.Value.Any(m => m.Severity == ValidationSeverity.Error));
/// <summary>
/// Adds error into the dictionary.
/// </summary>
public void AddError(string key, string message)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (message == null)
throw new ArgumentNullException(nameof(message));
Add(ValidationSeverity.Error, key, message);
}
/// <summary>
/// Returns all error messages for given key.
/// </summary>
public IEnumerable<ValidationMessage> GetErrorMessages(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (!_messages.TryGetValue(key, out var propertyState))
{
yield break;
}
foreach (var message in propertyState)
{
if (message.Severity != ValidationSeverity.Error)
{
continue;
}
yield return message;
}
}
/// <summary>
/// Returns first error message or null for given key.
/// </summary>
public ValidationMessage GetErrorMessage(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return GetErrorMessages(key).FirstOrDefault();
}
/// <summary>
/// Returns first error message text or null for given key.
/// </summary>
public string GetErrorText(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return GetErrorMessages(key).FirstOrDefault()?.Text;
}
#endregion
#region ICollection
public void CopyTo(ValidationMessage[] array, int arrayIndex)
{
foreach (var pair in _messages)
{
foreach (var message in pair.Value)
{
array[arrayIndex++] = message;
}
}
}
bool ICollection<ValidationMessage>.IsReadOnly => false;
#endregion
#region IEnumerable
public IEnumerator<ValidationMessage> GetEnumerator()
{
return _messages.SelectMany(p => p.Value).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Printing;
using System.Reflection;
using System.Text;
using PCSComUtils.Common;
using PCSUtils.Utils;
using C1.Win.C1Preview;
using C1.C1Report;
using PCSUtils.Framework.ReportFrame;
using C1PrintPreviewDialog = PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog;
namespace PurchasingPriceTrendInYear
{
/// <summary>
/// Summary description for PurchasingPriceTrendInYear.
/// </summary>
public class PurchasingPriceTrendInYear : MarshalByRefObject, IDynamicReport
{
#region IDynamicReport Members
private string mConnectionString;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
private ReportBuilder mReportBuilder;
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
private C1PrintPreviewControl mViewer;
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mViewer; }
set { mViewer = value; }
}
private object mResult;
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
private bool mUseEngine;
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport
/// or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseEngine; }
set { mUseEngine = value; }
}
private string mReportFolder;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mReportFolder; }
set { mReportFolder = value; }
}
private string mLayoutFile;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get { return mLayoutFile; }
set { mLayoutFile = value; }
}
/// <summary>
///
/// </summary>
/// <param name="pstrMethod">name of the method to call (which declare in the DynamicReport C# file)</param>
/// <param name="pobjParameters">Array of parameters provide to call the Method with method name = pstrMethod</param>
/// <returns></returns>
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
#endregion
public DataTable ExecuteReport(string pstrCCNID, string pstrYear, string pstrProductID)
{
int intYear = Convert.ToInt32(pstrYear);
#region report table
DataTable dtbData = new DataTable();
dtbData.Columns.Add(new DataColumn("Category", typeof (string)));
dtbData.Columns.Add(new DataColumn("PartNo", typeof (string)));
dtbData.Columns.Add(new DataColumn("PartName", typeof (string)));
dtbData.Columns.Add(new DataColumn("Model", typeof (string)));
for (int i = 1; i <= 12; i++)
{
DateTime dtmDate = new DateTime(intYear, i, 1);
string strColName = "M" + dtmDate.Month.ToString();
dtbData.Columns.Add(new DataColumn(strColName, typeof (decimal)));
}
#endregion
#region data
DataTable dtbReportData = GetReportData(pstrCCNID, pstrYear, pstrProductID);
string strLastProductID = string.Empty;
foreach (DataRow drowData in dtbReportData.Rows)
{
string strProductID = drowData["ProductID"].ToString();
if (strLastProductID == strProductID)
continue;
strLastProductID = strProductID;
string strFilter = "ProductID = '" + strProductID + "'";
DataRow[] drowProducts = dtbReportData.Select(strFilter, "SMonth ASC");
foreach (DataRow drowItem in drowProducts)
{
DataRow drowReport = dtbData.NewRow();
// general information
drowReport["Category"] = drowItem["Category"];
drowReport["PartNo"] = drowItem["PartNo"];
drowReport["PartName"] = drowItem["PartName"];
drowReport["Model"] = drowItem["Model"];
int intMonth = Convert.ToInt32(drowItem["SMonth"]);
DateTime dtmDate = new DateTime(intYear, intMonth, 1);
string strColName = "M" + dtmDate.Month.ToString();
try
{
drowReport[strColName] = Convert.ToDecimal(drowItem["Price"]);
}
catch{}
// insert to result table
dtbData.Rows.Add(drowReport);
}
}
#endregion
#region report
C1Report rptReport = new C1Report();
mLayoutFile = "PurchasingPriceTrendInYear.xml";
rptReport.Load(mReportFolder + "\\" + mLayoutFile, rptReport.GetReportInfo(mReportFolder + "\\" + mLayoutFile)[0]);
rptReport.Layout.PaperSize = PaperKind.A3;
#region report parameter
try
{
rptReport.Fields["fldCCN"].Text = GetCCN(pstrCCNID);
}
catch{}
try
{
rptReport.Fields["fldMonth"].Text = pstrYear;
}
catch{}
try
{
if (pstrProductID.Length > 0 && pstrProductID.Split(",".ToCharArray()).Length > 0)
rptReport.Fields["fldPartParam"].Text = "Multi-Selection";
else if (pstrProductID.Length > 0)
rptReport.Fields["fldPartParam"].Text = GetPartNo(pstrProductID);
}
catch{}
#endregion
// set datasource object that provides data to report.
rptReport.DataSource.Recordset = dtbData;
// render report
rptReport.Render();
// render the report into the PrintPreviewControl
C1PrintPreviewDialog ppvViewer = new C1PrintPreviewDialog();
ppvViewer.FormTitle = "Purchase Report Import Part By Month";
ppvViewer.ReportViewer.Document = rptReport.Document;
ppvViewer.Show();
#endregion
return dtbData;
}
private DataTable GetReportData(string pstrCCNID, string pstrYear, string pstrProductID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT DISTINCT SUM(ISNULL(CIFAmount,0))/SUM(ISNULL(InvoiceQuantity, 0)) AS Price,"
+ " PO_InvoiceDetail.ProductID, DATEPART(month, PostDate) AS SMonth,"
+ " ITM_Category.Code AS Category, ITM_Product.Code AS PartNo,"
+ " ITM_Product.Description AS PartName, ITM_Product.Revision AS Model"
+ " FROM PO_InvoiceDetail JOIN PO_InvoiceMaster"
+ " ON PO_InvoiceDetail.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID"
+ " JOIN PO_PurchaseOrderMaster"
+ " ON PO_InvoiceDetail.PurchaseOrderMasterID = PO_PurchaseOrderMaster.PurchaseOrderMasterID"
+ " JOIN MST_Party"
+ " ON PO_PurchaseOrderMaster.MakerID = MST_Party.PartyID"
+ " JOIN ITM_Product"
+ " ON PO_InvoiceDetail.ProductID = ITM_Product.ProductID"
+ " LEFT JOIN ITM_Category"
+ " ON ITM_Product.CategoryID = ITM_Category.CategoryID"
+ " WHERE PO_InvoiceMaster.CCNID = " + pstrCCNID
+ " AND DATEPART(year, PostDate) = " + pstrYear
+ " AND MST_Party.CountryID <> (SELECT CountryID FROM MST_CCN WHERE CCNID = " + pstrCCNID + ")"
+ " AND MST_Party.Type <> 0";
if (pstrProductID.Length > 0)
strSql += " AND PO_InvoiceDetail.ProductID IN (" + pstrProductID + ")";
strSql += " GROUP BY ITM_Category.Code, PO_InvoiceDetail.ProductID, ITM_Product.Code,"
+ " ITM_Product.Description, ITM_Product.Revision, DATEPART(month, PostDate)"
+ " ORDER BY ITM_Category.Code, ITM_Product.Code, ITM_Product.Description,"
+ " ITM_Product.Revision, DATEPART(month, PostDate)";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
DataTable dtbData = new DataTable();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetCCN(string pstrCCNID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT Code + ' (' + Description + ')' FROM MST_CCN WHERE CCNID = " + pstrCCNID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private string GetPartNo(string pstrProductID)
{
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT Code + ' (' + Description + ')' FROM ITM_Product WHERE ProductID = " + pstrProductID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
return objResult.ToString();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
}
}
| |
/* ====================================================================
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.Collections.Generic;
using System.Collections.ObjectModel;
using NPOI.SS.Formula.Function;
namespace NPOI.SS.Formula.Atp
{
using System;
using System.Collections;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Udf;
public class NotImplemented : FreeRefFunction
{
private String _functionName;
public NotImplemented(String functionName)
{
_functionName = functionName;
}
public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
{
throw new NotImplementedFunctionException(_functionName);
}
}
public class AnalysisToolPak : UDFFinder
{
public static UDFFinder instance = new AnalysisToolPak();
private static Hashtable _functionsByName = CreateFunctionsMap();
private AnalysisToolPak()
{
// no instances of this class
}
public override FreeRefFunction FindFunction(String name)
{
// functions that are available in Excel 2007+ have a prefix _xlfn.
// if you save such a .xlsx workbook as .xls
if (name.StartsWith("_xlfn.")) name = name.Substring(6);
return (FreeRefFunction)_functionsByName[name.ToUpper()];
}
private static Hashtable CreateFunctionsMap()
{
Hashtable m = new Hashtable(100);
r(m, "ACCRINT", null);
r(m, "ACCRINTM", null);
r(m, "AMORDEGRC", null);
r(m, "AMORLINC", null);
r(m, "AVERAGEIF", null);
r(m, "AVERAGEIFS", null);
r(m, "BAHTTEXT", null);
r(m, "BESSELI", null);
r(m, "BESSELJ", null);
r(m, "BESSELK", null);
r(m, "BESSELY", null);
r(m, "BIN2DEC", Bin2Dec.instance);
r(m, "BIN2HEX", null);
r(m, "BIN2OCT", null);
r(m, "COMPLEX", Complex.Instance);
r(m, "CONVERT", null);
r(m, "COUNTIFS", null);
r(m, "COUPDAYBS", null);
r(m, "COUPDAYS", null);
r(m, "COUPDAYSNC", null);
r(m, "COUPNCD", null);
r(m, "COUPNUM", null);
r(m, "COUPPCD", null);
r(m, "CUBEKPIMEMBER", null);
r(m, "CUBEMEMBER", null);
r(m, "CUBEMEMBERPROPERTY", null);
r(m, "CUBERANKEDMEMBER", null);
r(m, "CUBESET", null);
r(m, "CUBESETCOUNT", null);
r(m, "CUBEVALUE", null);
r(m, "CUMIPMT", null);
r(m, "CUMPRINC", null);
r(m, "DEC2BIN", Dec2Bin.instance);
r(m, "DEC2HEX", Dec2Hex.instance);
r(m, "DEC2OCT", null);
r(m, "DELTA", Delta.instance);
r(m, "DISC", null);
r(m, "DOLLARDE", null);
r(m, "DOLLARFR", null);
r(m, "DURATION", null);
r(m, "EDATE", EDate.Instance);
r(m, "EFFECT", null);
r(m, "EOMONTH", EOMonth.instance);
r(m, "ERF", null);
r(m, "ERFC", null);
r(m, "FACTDOUBLE", FactDouble.instance);
r(m, "FVSCHEDULE", null);
r(m, "GCD", null);
r(m, "GESTEP", null);
r(m, "HEX2BIN", null);
r(m, "HEX2DEC", Hex2Dec.instance);
r(m, "HEX2OCT", null);
r(m, "IFERROR", IfError.Instance);
r(m, "IMABS", null);
r(m, "IMAGINARY", Imaginary.instance);
r(m, "IMARGUMENT", null);
r(m, "IMCONJUGATE", null);
r(m, "IMCOS", null);
r(m, "IMDIV", null);
r(m, "IMEXP", null);
r(m, "IMLN", null);
r(m, "IMLOG10", null);
r(m, "IMLOG2", null);
r(m, "IMPOWER", null);
r(m, "IMPRODUCT", null);
r(m, "IMREAL", ImReal.instance);
r(m, "IMSIN", null);
r(m, "IMSQRT", null);
r(m, "IMSUB", null);
r(m, "IMSUM", null);
r(m, "INTRATE", null);
r(m, "ISEVEN", ParityFunction.IS_EVEN);
r(m, "ISODD", ParityFunction.IS_ODD);
r(m, "JIS", null);
r(m, "LCM", null);
r(m, "MDURATION", null);
r(m, "MROUND", MRound.Instance);
r(m, "MULTINOMIAL", null);
r(m, "NETWORKDAYS", NetworkdaysFunction.instance);
r(m, "NOMINAL", null);
r(m, "OCT2BIN", null);
r(m, "OCT2DEC", Oct2Dec.instance);
r(m, "OCT2HEX", null);
r(m, "ODDFPRICE", null);
r(m, "ODDFYIELD", null);
r(m, "ODDLPRICE", null);
r(m, "ODDLYIELD", null);
r(m, "PRICE", null);
r(m, "PRICEDISC", null);
r(m, "PRICEMAT", null);
r(m, "QUOTIENT", Quotient.instance);
r(m, "RANDBETWEEN", RandBetween.Instance);
r(m, "RECEIVED", null);
r(m, "RTD", null);
r(m, "SERIESSUM", null);
r(m, "SQRTPI", null);
r(m, "SUMIFS", Sumifs.instance);
r(m, "TBILLEQ", null);
r(m, "TBILLPRICE", null);
r(m, "TBILLYIELD", null);
r(m, "WEEKNUM", WeekNum.instance);
r(m, "WORKDAY", WorkdayFunction.instance);
r(m, "XIRR", null);
r(m, "XNPV", null);
r(m, "YEARFRAC", YearFrac.instance);
r(m, "YIELD", null);
r(m, "YIELDDISC", null);
r(m, "YIELDMAT", null);
r(m, "COUNTIFS", Countifs.instance);
return m;
}
private static void r(Hashtable m, String functionName, FreeRefFunction pFunc)
{
FreeRefFunction func = pFunc == null ? new NotImplemented(functionName) : pFunc;
m[functionName] = func;
}
public static bool IsATPFunction(String name)
{
//AnalysisToolPak inst = (AnalysisToolPak)instance;
return AnalysisToolPak._functionsByName.ContainsKey(name);
}
/**
* Returns a collection of ATP function names implemented by POI.
*
* @return an array of supported functions
* @since 3.8 beta6
*/
public static ReadOnlyCollection<String> GetSupportedFunctionNames()
{
AnalysisToolPak inst = (AnalysisToolPak)instance;
List<String> lst = new List<String>();
foreach (String name in AnalysisToolPak._functionsByName.Keys)
{
FreeRefFunction func = (FreeRefFunction)AnalysisToolPak._functionsByName[(name)];
if (func != null && !(func is NotImplemented))
{
lst.Add(name);
}
}
return lst.AsReadOnly(); //Collections.unmodifiableCollection(lst);
}
/**
* Returns a collection of ATP function names NOT implemented by POI.
*
* @return an array of not supported functions
* @since 3.8 beta6
*/
public static ReadOnlyCollection<String> GetNotSupportedFunctionNames()
{
AnalysisToolPak inst = (AnalysisToolPak)instance;
List<String> lst = new List<String>();
foreach (String name in AnalysisToolPak._functionsByName.Keys)
{
FreeRefFunction func = (FreeRefFunction)AnalysisToolPak._functionsByName[(name)];
if (func != null && (func is NotImplemented))
{
lst.Add(name);
}
}
return lst.AsReadOnly(); //Collections.unmodifiableCollection(lst);
}
/**
* Register a ATP function in runtime.
*
* @param name the function name
* @param func the functoin to register
* @throws ArgumentException if the function is unknown or already registered.
* @since 3.8 beta6
*/
public static void RegisterFunction(String name, FreeRefFunction func)
{
AnalysisToolPak inst = (AnalysisToolPak)instance;
if (!IsATPFunction(name))
{
FunctionMetadata metaData = FunctionMetadataRegistry.GetFunctionByName(name);
if (metaData != null)
{
throw new ArgumentException(name + " is a built-in Excel function. " +
"Use FunctoinEval.RegisterFunction(String name, Function func) instead.");
}
else
{
throw new ArgumentException(name + " is not a function from the Excel Analysis Toolpack.");
}
}
FreeRefFunction f = inst.FindFunction(name);
if (f != null && !(f is NotImplemented))
{
throw new ArgumentException("POI already implememts " + name +
". You cannot override POI's implementations of Excel functions");
}
if (_functionsByName.ContainsKey(name))
_functionsByName[name] = func;
else
_functionsByName.Add(name, func);
}
}
}
| |
/*
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.
*/
//INSTANT C# NOTE: Formerly VB.NET project-level imports:
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using Microsoft.VisualBasic.Compatibility.VB6;
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace AlgorithmicColorRamp
{
internal partial class frmAlgorithmicColorRamp : System.Windows.Forms.Form
{
// This form allows a user to set properties determining the constraints of a
// AlgoritmicColorRamp, which is then used to populate an existing ClassBreaksRenderer
// on an existing FeatureLayer.
//
//
// The m_lngClasses variable is set by the calling function, to indicate the
// number of random colors required by the classbreaksrenderer.
//
public int m_lngClasses;
//
// The m_enumNewColors variable holds the colors to be returned to the calling function.
//
public IEnumColors m_enumNewColors;
//
// The m_lngColors variable holds the index of the last color displayed in the array.
//
private int m_lngColors;
private System.Windows.Forms.Button[] Buttons = new System.Windows.Forms.Button[3];
private System.Windows.Forms.Label[] LabelsIndex = new System.Windows.Forms.Label[11];
private System.Windows.Forms.TextBox[] TextBoxColors = new System.Windows.Forms.TextBox[11];
private void cmbAlgorithm_SelectedIndexChanged(object eventSender, System.EventArgs eventArgs)
{
if (cmbAlgorithm.SelectedIndex > -1)
UpdateRamp();
}
private void cmdCancel_Click(object eventSender, System.EventArgs eventArgs)
{
//
// User pressed Cancel, so we set the colors enumeration to nothing and
// unload the form.
//
m_enumNewColors = null;
this.Close();
}
private void cmdEnumColorsNext_Click(object eventSender, System.EventArgs eventArgs)
{
//
// Increase the indicator variable m_lngColors by 10, so we can display the
// next ten colors to the user.
//
if (m_enumNewColors != null)
{
m_lngColors = m_lngColors + 10;
HideColors();
LooRGBColors();
}
}
private void cmdEnumColorsFirst_Click(object eventSender, System.EventArgs eventArgs)
{
//
// Reset the indicator variable to zero.
//
if (m_enumNewColors != null)
{
m_lngColors = 0;
HideColors();
LooRGBColors();
}
}
private void cmdOK_Click(object eventSender, System.EventArgs eventArgs)
{
//
// Check we have a colors enumeration.
//
if (m_enumNewColors == null)
MessageBox.Show("You have not created a new color ramp." + "Your layer symbology will be unchanged.", "No Ramp Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
this.Hide();
}
private void frmAlgorithmicColorRamp_Load(object eventSender, System.EventArgs eventArgs)
{
//
// Initialize the controls.
//
SetupControls();
}
private void UpdateRamp()
{
//
// Create a new AlgorithmicColorRamp object, and get it's
// IAlgorithmicColorRamp interface.
//
IAlgorithmicColorRamp AlgortihmicColorRamp = null;
AlgortihmicColorRamp = new ESRI.ArcGIS.Display.AlgorithmicColorRamp();
//
// Set the size of the color ramp to the number of classes
// to be renderered.
//
AlgortihmicColorRamp.Size = m_lngClasses;
//
// Set the color ramps properties.
//
IRgbColor RGBColor = null;
RGBColor = new RgbColor();
RGBColor.RGB = System.Drawing.ColorTranslator.ToOle(txtStartColor.BackColor);
AlgortihmicColorRamp.FromColor = RGBColor;
RGBColor.RGB = System.Drawing.ColorTranslator.ToOle(txtEndColor.BackColor);
AlgortihmicColorRamp.ToColor = RGBColor;
AlgortihmicColorRamp.Algorithm = (esriColorRampAlgorithm)cmbAlgorithm.SelectedIndex;
bool boolRamp = false;
if (AlgortihmicColorRamp.Size > 0)
{
boolRamp = true;
AlgortihmicColorRamp.CreateRamp(out boolRamp);
if (boolRamp)
{
m_enumNewColors = AlgortihmicColorRamp.Colors;
m_enumNewColors.Reset();
cmdOK.Enabled = true;
//
// Check if we should be showing the colors.
//
if (chkShowColors.CheckState == System.Windows.Forms.CheckState.Checked)
{
//
// Populate the Colors textbox array and it's labels.
//
m_lngColors = 0;
ShowColorsArray();
}
}
}
}
private void SetupControls()
{
LabelsIndex[0] = Label1;
LabelsIndex[1] = Label2;
LabelsIndex[2] = Label3;
LabelsIndex[3] = Label4;
LabelsIndex[4] = Label5;
LabelsIndex[5] = Label6;
LabelsIndex[6] = Label7;
LabelsIndex[7] = Label8;
LabelsIndex[8] = Label9;
LabelsIndex[9] = Label10;
TextBoxColors[0] = TextBox1;
TextBoxColors[1] = TextBox2;
TextBoxColors[2] = TextBox3;
TextBoxColors[3] = TextBox4;
TextBoxColors[4] = TextBox5;
TextBoxColors[5] = TextBox6;
TextBoxColors[6] = TextBox7;
TextBoxColors[7] = TextBox8;
TextBoxColors[8] = TextBox9;
TextBoxColors[9] = TextBox10;
HideColors();
txtStartColor.Text = "";
txtEndColor.Text = "";
txtStartColor.BackColor = System.Drawing.ColorTranslator.FromOle(0XFF);
txtEndColor.BackColor = System.Drawing.ColorTranslator.FromOle(0XFF);
//MsgBox("Before ", MsgBoxStyle.Information, "SetupControls ")
Buttons[0] = Button1;
Buttons[1] = Button2;
//MsgBox("After ", MsgBoxStyle.Information, "SetupControls")
cmbAlgorithm.Items.Clear();
cmbAlgorithm.Items.Insert(0, "0 - esriHSVAlgorithm");
cmbAlgorithm.Items.Insert(1, "1 - esriCIELabAlgorithm");
cmbAlgorithm.Items.Insert(2, "2 - esriLabLChAlgorithm");
cmbAlgorithm.SelectedIndex = 0;
cmdOK.Enabled = false;
chkShowColors.CheckState = System.Windows.Forms.CheckState.Unchecked;
UpdateRamp();
chkShowColors_CheckStateChanged(chkShowColors, new System.EventArgs());
}
private void ShowColorsArray()
{
if (m_enumNewColors == null)
return;
else
{
//
// Iterate and show all colors in the ColorRamp.
//
HideColors();
LooRGBColors(); //m_lngColors
}
}
private void LooRGBColors()
{
//
// Move to the required Color to show. We only have space to show ten colors
// at a time on the form. So when we wish to show the next ten colors,
// (colors 11-20, 21-30 etc) we iterate the colors enumeration appropriately.
//
int lngMoveNext = 0;
m_enumNewColors.Reset();
while (lngMoveNext < m_lngColors)
{
m_enumNewColors.Next();
lngMoveNext = lngMoveNext + 1;
}
//
// Show colors in textboxes as necessary.
//
IColor colNew = null;
int lngCount = 0;
for (lngCount = 0; lngCount <= 9; lngCount++)
{
//commented the control array txtColor - OLD
//With txtColor(lngCount)
// colNew = m_enumNewColors.Next
// '
// ' If getting the next color returns nothing, we have got to
// ' the end of the colors enumeration.
// '
// If colNew Is Nothing Then
// Exit For
// End If
// .BackColor = System.Drawing.ColorTranslator.FromOle(colNew.RGB)
// .Visible = True
//End With
colNew = m_enumNewColors.Next();
//
// If getting the next color returns nothing, we have got to
// the end of the colors enumeration.
//
if (colNew == null)
break;
TextBoxColors[lngCount].BackColor = System.Drawing.ColorTranslator.FromOle(colNew.RGB);
TextBoxColors[lngCount].Visible = true;
//Commented the control array lblIndex - OLD
//With lblIndex(lngCount)
// .Text = CStr(lngCount + m_lngColors)
// .Visible = True
//End With
//LabelsIndex[lngCount].Text = System.Convert().ToString(lngCount + m_lngColors);
LabelsIndex[lngCount].Text = Convert.ToString (lngCount+m_lngColors);
LabelsIndex[lngCount].Visible = true;
}
}
private void HideColors()
{
//
// Hide all Color textboxes.
//
short i = 0;
for (i = 0; i <= 9; i++)
{
//txtColor(i).Visible = False '- OLD control array
TextBoxColors[i].Visible = false;
//lblIndex(i).Visible = False '- OLD control array
LabelsIndex[i].Visible = false;
}
}
private void frmAlgorithmicColorRamp_FormClosing(object eventSender, System.Windows.Forms.FormClosingEventArgs eventArgs)
{
bool Cancel = eventArgs.Cancel;
System.Windows.Forms.CloseReason UnloadMode = eventArgs.CloseReason;
if (m_enumNewColors == null)
{
//
// User has exited the Form without setting a new ColorRamp.
//
MessageBox.Show("You have not created a new ColorRamp." + System.Environment.NewLine + "Your symbology will not be changed.", "ColorRamp not set", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
eventArgs.Cancel = Cancel;
}
private void chkShowColors_Click(object sender, System.EventArgs e)
{
if (chkShowColors.CheckState == System.Windows.Forms.CheckState.Checked)
{
this.Width = (int)Support.TwipsToPixelsX(3705);
ShowColorsArray();
}
else
this.Width = (int)Support.TwipsToPixelsX(2355);
}
private void chkShowColors_CheckStateChanged(object eventSender, System.EventArgs eventArgs)
{
//
// Show and hide the colors array.
//
if (chkShowColors.CheckState == System.Windows.Forms.CheckState.Checked)
{
this.Width = (int)Support.TwipsToPixelsX(3705);
ShowColorsArray();
}
else
this.Width = (int)Support.TwipsToPixelsX(2355);
}
private void frmAlgorithmicColorRamp_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
}
private void Button1_Click(object sender, System.EventArgs e)
{
IColorSelector ColorSelector = null;
if (Buttons[0] == sender)
{
// Create color selector object.
ColorSelector = new ColorSelectorClass();
// Open the selector dialog.
if (ColorSelector.DoModal(this.Handle.ToInt32()))
{
//
// A Color was selected (if the above method returned false,
// this indicates that the user pressed Cancel).
txtStartColor.BackColor = System.Drawing.ColorTranslator.FromOle(ColorSelector.Color.RGB);
}
UpdateRamp();
}
else
{
ColorSelector = new ColorSelectorClass();
if (ColorSelector.DoModal(this.Handle.ToInt32()))
txtEndColor.BackColor = System.Drawing.ColorTranslator.FromOle(ColorSelector.Color.RGB);
UpdateRamp();
}
}
private void Label9_Click(object sender, System.EventArgs e)
{
}
private void _txtColor_0_TextChanged(object sender, System.EventArgs e)
{
}
}
} //end of root namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.DeriveBytesTests
{
public class PasswordDeriveBytesTests
{
// Note some tests were copied from Rfc2898DeriveBytes (and modified accordingly).
private static readonly byte[] s_testSalt = new byte[] { 9, 5, 5, 5, 1, 2, 1, 2 };
private static readonly byte[] s_testSaltB = new byte[] { 0, 4, 0, 4, 1, 9, 7, 5 };
private const string TestPassword = "PasswordGoesHere";
private const string TestPasswordB = "FakePasswordsAreHard";
private const int DefaultIterationCount = 100;
[Fact]
public static void Ctor_NullPasswordBytes()
{
using (var pdb = new PasswordDeriveBytes((byte[])null, s_testSalt))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(s_testSalt, pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_NullPasswordString()
{
Assert.Throws<ArgumentNullException>(() => new PasswordDeriveBytes((string)null, s_testSalt));
}
[Fact]
public static void Ctor_NullSalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, null))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(null, pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_EmptySalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, Array.Empty<byte>()))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(Array.Empty<byte>(), pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_DiminishedSalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, new byte[7]))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(7, pdb.Salt.Length);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_TooFewIterations()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 0));
}
[Fact]
public static void Ctor_NegativeIterations()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", int.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", int.MinValue / 2));
}
[Fact]
public static void Ctor_DefaultIterations()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Equal(DefaultIterationCount, deriveBytes.IterationCount);
}
}
[Fact]
public static void Ctor_IterationsRespected()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 1))
{
Assert.Equal(1, deriveBytes.IterationCount);
}
}
[Fact]
public static void Ctor_CspParameters()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 100, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, "SHA1", 100, new CspParameters())) { }
}
[Fact]
public static void Ctor_CspParameters_Null()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 100, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, "SHA1", 100, null)) { }
}
[Fact]
public static void Ctor_SaltCopied()
{
byte[] saltIn = (byte[])s_testSalt.Clone();
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, saltIn, "SHA1", DefaultIterationCount))
{
byte[] saltOut = deriveBytes.Salt;
Assert.NotSame(saltIn, saltOut);
Assert.Equal(saltIn, saltOut);
// Right now we know that at least one of the constructor and get_Salt made a copy, if it was
// only get_Salt then this next part would fail.
saltIn[0] = unchecked((byte)~saltIn[0]);
// Have to read the property again to prove it's detached.
Assert.NotEqual(saltIn, deriveBytes.Salt);
}
}
[Fact]
public static void GetSaltCopies()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", DefaultIterationCount))
{
first = deriveBytes.Salt;
second = deriveBytes.Salt;
}
Assert.NotSame(first, second);
Assert.Equal(first, second);
}
[Fact]
public static void SetSaltAfterGetBytes_Throws()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
deriveBytes.GetBytes(1);
Assert.Throws<CryptographicException>(() => deriveBytes.Salt = s_testSalt);
}
}
[Fact]
public static void SetSaltAfterGetBytes_Reset()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
deriveBytes.GetBytes(1);
deriveBytes.Reset();
deriveBytes.Salt = s_testSaltB;
Assert.Equal(s_testSaltB, deriveBytes.Salt);
}
}
[Fact]
public static void MinimumAcceptableInputs()
{
byte[] output;
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, new byte[8], "SHA1", 1))
{
output = deriveBytes.GetBytes(1);
}
Assert.Equal(1, output.Length);
Assert.Equal(0xF8, output[0]);
}
[Fact]
public static void GetBytes_ZeroLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<ArgumentException>(() => deriveBytes.GetBytes(0));
}
}
[Fact]
public static void GetBytes_NegativeLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(-1));
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(int.MinValue));
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(int.MinValue / 2));
}
}
[Fact]
public static void GetBytes_NotIdempotent()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
first = deriveBytes.GetBytes(32);
second = deriveBytes.GetBytes(32);
}
Assert.NotEqual(first, second);
}
[Fact]
public static void GetBytes_StableIfReset()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
first = deriveBytes.GetBytes(32);
deriveBytes.Reset();
second = deriveBytes.GetBytes(32);
}
Assert.Equal(first, second);
}
[Fact]
public static void GetBytes_StreamLike_ExtraBytes()
{
byte[] first;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// SHA1 default
Assert.Equal("SHA1", deriveBytes.HashName);
// Request double of SHA1 hash size
first = deriveBytes.GetBytes(40);
}
byte[] second = new byte[first.Length];
// Reset
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Make two passes over the hash
byte[] secondFirstHalf = deriveBytes.GetBytes(first.Length / 2);
// Since we requested 20 bytes there are no 'extra' bytes left over to cause the "_extraCount" bug
// in GetBytes(); that issue is tested in GetBytes_StreamLike_Bug_Compat.
// Request 20 'extra' bytes in one call
byte[] secondSecondHalf = deriveBytes.GetBytes(first.Length - secondFirstHalf.Length);
Buffer.BlockCopy(secondFirstHalf, 0, second, 0, secondFirstHalf.Length);
Buffer.BlockCopy(secondSecondHalf, 0, second, secondFirstHalf.Length, secondSecondHalf.Length);
}
Assert.Equal(first, second);
}
[Fact]
public static void GetBytes_StreamLike_Bug_Compat()
{
byte[] first;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Equal("SHA1", deriveBytes.HashName);
// Request 20 bytes (SHA1 hash size) plus 12 extra bytes
first = deriveBytes.GetBytes(32);
}
byte[] second = new byte[first.Length];
// Reset
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Ask for half now (16 bytes)
byte[] firstHalf = deriveBytes.GetBytes(first.Length / 2);
// Ask for the other half now (16 bytes)
byte[] lastHalf = deriveBytes.GetBytes(first.Length - firstHalf.Length);
// lastHalf should contain the last 4 bytes from the SHA1 hash plus 12 extra bytes
// but due to the _extraCount bug it doesn't.
// Merge the two buffers into the second array
Buffer.BlockCopy(firstHalf, 0, second, 0, firstHalf.Length);
Buffer.BlockCopy(lastHalf, 0, second, firstHalf.Length, lastHalf.Length);
}
// Fails due to _extraCount bug (the bug is fixed in Rfc2898DeriveBytes)
Assert.NotEqual(first, second);
// However, the first 16 bytes will be equal because the _extraCount bug does
// not affect the first call, only the subsequent GetBytes() call.
byte[] first_firstHalf = new byte[first.Length / 2];
byte[] second_firstHalf = new byte[first.Length / 2];
Buffer.BlockCopy(first, 0, first_firstHalf, 0, first_firstHalf.Length);
Buffer.BlockCopy(second, 0, second_firstHalf, 0, second_firstHalf.Length);
Assert.Equal(first_firstHalf, second_firstHalf);
}
[Fact]
public static void GetBytes_Boundary()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Boundary case success
deriveBytes.GetBytes(1000 * 20);
// Boundary case failure
Assert.Throws<CryptographicException>(() => deriveBytes.GetBytes(1));
}
}
[Fact]
public static void GetBytes_KnownValues_MD5_32()
{
TestKnownValue_GetBytes(
HashAlgorithmName.MD5,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("F8D88E9DAFC828DA2400F5144271C2F630A1C061C654FC9DE2E7900E121461B9"));
}
[Fact]
public static void GetBytes_KnownValues_SHA256_40()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA256,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("3774A17468276057717A90C25B72915921D8F8C046F7868868DBB99BB4C4031CADE9E26BE77BEA39"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("12F2497EC3EB78B0EA32AABFD8B9515FBC800BEEB6316A4DDF4EA62518341488A116DA3BBC26C685"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_2()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSalt,
DefaultIterationCount + 1,
ByteUtils.HexToByteArray("FB6199E4D9BB017D2F3AF6964F3299971607C6B984934A9E43140631957429160C33A6630EF12E31"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_3()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSaltB,
DefaultIterationCount,
ByteUtils.HexToByteArray("DCA4851AB3C9960CF387E64DE7A1B2E09616BEA6A4666AAFAC31F1670F23530E38BD4BF4D9248A08"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_4()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPasswordB,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("1DCA2A3405E93D9E3F7CD10653444F2FD93F5BE32C4B1BEDDF94D0D67461CBE86B5BDFEB32071E96"));
}
[Fact]
public static void CryptDeriveKey_KnownValues_TripleDes()
{
byte[] key = TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"TripleDES",
192,
s_testSalt,
ByteUtils.HexToByteArray("97628A641949D99DCED35DB0ABCE20F21FF4DA9B46E00BCE"));
// Verify key is valid
using (var alg = new TripleDESCryptoServiceProvider())
{
alg.Key = key;
alg.IV = new byte[8];
alg.Padding = PaddingMode.None;
alg.Mode = CipherMode.CBC;
byte[] plainText = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "9DC863445642B88AC46B3B107CB5A0ACC1596A176962EE8F".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Fact]
public static void CryptDeriveKey_KnownValues_RC2()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("B0695D8D98F5844B9650A9F68EFF105B"));
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA256,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("CF4A1CA60093E71D6B740DBB962B3C66"));
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.MD5,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("84F4B6854CDF896A86FB493B852B6E1F"));
}
[Fact]
public static void CryptDeriveKey_KnownValues_RC2_NoSalt()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"RC2",
128,
null, // Salt is not used here so we should get same key value
ByteUtils.HexToByteArray("B0695D8D98F5844B9650A9F68EFF105B"));
}
[Fact]
public static void CryptDeriveKey_KnownValues_DES()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"DES",
64,
s_testSalt,
ByteUtils.HexToByteArray("B0685D8C98F4854A"));
}
[Fact]
public static void CryptDeriveKey_Invalid_KeyLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 127, s_testSalt));
Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 129, s_testSalt));
}
}
[Fact]
public static void CryptDeriveKey_Invalid_Algorithm()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("BADALG", "SHA1", 128, s_testSalt));
}
}
[Fact]
public static void CryptDeriveKey_Invalid_HashAlgorithm()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "BADALG", 128, s_testSalt));
}
}
[Fact]
public static void CryptDeriveKey_Invalid_IV()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, null));
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, new byte[1]));
}
}
private static byte[] TestKnownValue_CryptDeriveKey(HashAlgorithmName hashName, string password, string alg, int keySize, byte[] salt, byte[] expected)
{
byte[] output;
byte[] iv = new byte[8];
using (var deriveBytes = new PasswordDeriveBytes(password, salt))
{
output = deriveBytes.CryptDeriveKey(alg, hashName.Name, keySize, iv);
}
Assert.Equal(expected, output);
// For these tests, the returned IV is always zero
Assert.Equal(new byte[8], iv);
return output;
}
private static void TestKnownValue_GetBytes(HashAlgorithmName hashName, string password, byte[] salt, int iterationCount, byte[] expected)
{
byte[] output;
using (var deriveBytes = new PasswordDeriveBytes(password, salt, hashName.Name, iterationCount))
{
output = deriveBytes.GetBytes(expected.Length);
}
Assert.Equal(expected, output);
}
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) 2014-2016 the original author or authors. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Robotlegs.Bender.Extensions.EventManagement.API;
using Robotlegs.Bender.Extensions.ViewManagement.Support;
using Robotlegs.Bender.Framework.Impl;
using Robotlegs.Bender.Framework.API;
namespace Robotlegs.Bender.Extensions.Matching
{
[TestFixture]
public class TypeMatcherTest
{
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private static readonly List<Type> ALL_OF = new List<Type>{typeof(uint), typeof(float)};
private static readonly List<Type> ALL_OF_2 = new List<Type>{typeof(object), typeof(IConfig)};
private static readonly List<Type> ANY_OF = new List<Type>{typeof(Context), typeof(IEventDispatcher)};
private static readonly List<Type> ANY_OF_2 = new List<Type>{typeof(SupportContainer), typeof(SupportView)};
private static readonly List<Type> NONE_OF = new List<Type>{typeof(byte[]), typeof(string)};
private static readonly List<Type> NONE_OF_2 = new List<Type>{typeof(ITypeFilter), typeof(ITypeMatcher)};
private static readonly List<Type> EMPTY_CLASS_VECTOR = new List<Type>{};
private TypeMatcher instance;
/*============================================================================*/
/* Test Setup and Teardown */
/*============================================================================*/
[SetUp]
public void setUp()
{
instance = new TypeMatcher();
}
[TearDown]
public void tearDown()
{
instance = null;
}
/*============================================================================*/
/* Tests */
/*============================================================================*/
[Test]
public void can_be_instantiated()
{
Assert.That(instance, Is.InstanceOf<TypeMatcher>());
}
[Test]
public void implements_ITypeMatcher()
{
Assert.That(instance, Is.InstanceOf<ITypeMatcher>());
}
[Test]
public void not_supplying_allOf_causes_no_errors()
{
TypeFilter expectedFilter = new TypeFilter(new List<Type>{}, ANY_OF, NONE_OF);
instance.AnyOf(ANY_OF.ToArray()).NoneOf(NONE_OF.ToArray());
assertMatchesTypeFilter(expectedFilter, instance.CreateTypeFilter());
}
[Test]
public void not_supplying_anyOf_causes_no_errors()
{
TypeFilter expectedFilter = new TypeFilter(ALL_OF, new List<Type>{}, NONE_OF);
instance.AllOf(ALL_OF.ToArray()).NoneOf(NONE_OF.ToArray());
assertMatchesTypeFilter(expectedFilter, instance.CreateTypeFilter());
}
[Test]
public void not_supplying_noneOf_causes_no_errors()
{
TypeFilter expectedFilter = new TypeFilter(ALL_OF, ANY_OF, new List<Type>{});
instance.AnyOf(ANY_OF.ToArray()).AllOf(ALL_OF.ToArray());
assertMatchesTypeFilter(expectedFilter, instance.CreateTypeFilter());
}
[Test]
public void supplying_all_any_and_none_in_different_order_populates_them_in_typeFilter()
{
TypeFilter expectedFilter = new TypeFilter(ALL_OF, ANY_OF, NONE_OF);
instance.NoneOf(NONE_OF.ToArray()).AllOf(ALL_OF.ToArray()).AnyOf(ANY_OF.ToArray());
assertMatchesTypeFilter(expectedFilter, instance.CreateTypeFilter());
}
[Test]
public void supplying_all_any_and_none_populates_them_in_typeFilter()
{
TypeFilter expectedFilter = new TypeFilter(ALL_OF, ANY_OF, NONE_OF);
instance.AllOf(ALL_OF.ToArray()).AnyOf(ANY_OF.ToArray()).NoneOf(NONE_OF.ToArray());
assertMatchesTypeFilter(expectedFilter, instance.CreateTypeFilter());
}
[Test]
public void supplying_multiple_all_values_includes_all_given_in_typeFilter()
{
TypeFilter expectedFilter = new TypeFilter(Concat(ALL_OF, ALL_OF_2) as List<Type>, ANY_OF, NONE_OF);
instance.AllOf(ALL_OF.ToArray()).AnyOf(ANY_OF.ToArray()).NoneOf(NONE_OF.ToArray()).AllOf(ALL_OF_2.ToArray());
assertMatchesTypeFilter(expectedFilter, instance.CreateTypeFilter());
}
[Test]
public void supplying_multiple_any_values_includes_all_given_in_typeFilter()
{
TypeFilter expectedFilter = new TypeFilter(ALL_OF, Concat(ANY_OF, ANY_OF_2), NONE_OF);
instance.AllOf(ALL_OF.ToArray()).AnyOf(ANY_OF.ToArray()).NoneOf(NONE_OF.ToArray()).AnyOf(ANY_OF_2.ToArray());
assertMatchesTypeFilter(expectedFilter, instance.CreateTypeFilter());
}
[Test]
public void supplying_multiple_none_values_includes_all_given_in_typeFilter()
{
TypeFilter expectedFilter = new TypeFilter(ALL_OF, ANY_OF, Concat(NONE_OF, NONE_OF_2));
instance.AllOf(ALL_OF.ToArray()).AnyOf(ANY_OF.ToArray()).NoneOf(NONE_OF.ToArray()).NoneOf(NONE_OF_2.ToArray());
assertMatchesTypeFilter(expectedFilter, instance.CreateTypeFilter());
}
[Test]
public void throws_TypeMatcherError_if_allOf_changed_after_filter_requested()
{
Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() =>
{
instance.AnyOf(ANY_OF.ToArray());
instance.CreateTypeFilter();
instance.AllOf(ALL_OF.ToArray());
}
));
}
[Test]
public void throws_TypeMatcherError_if_allOf_changed_after_lock()
{
Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() =>
{
instance.AnyOf(ANY_OF.ToArray());
instance.Lock();
instance.AllOf(ALL_OF.ToArray());
}
));
}
[Test]
public void throws_TypeMatcherError_if_anyOf_changed_after_filter_requested()
{
Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() =>
{
instance.NoneOf(NONE_OF.ToArray());
instance.CreateTypeFilter();
instance.AnyOf(ALL_OF.ToArray());
}
));
}
[Test]
public void throws_TypeMatcherError_if_anyOf_changed_after_lock()
{
Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() =>
{
instance.NoneOf(NONE_OF.ToArray());
instance.Lock();
instance.AnyOf(ALL_OF.ToArray());
}
));
}
[Test]
public void throws_TypeMatcherError_if_noneOf_changed_after_filter_requested()
{
Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() =>
{
instance.AllOf(ALL_OF.ToArray());
instance.CreateTypeFilter();
instance.NoneOf(ALL_OF.ToArray());
}
));
}
[Test]
public void throws_TypeMatcherError_if_noneOf_changed_after_lock()
{
Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() =>
{
instance.AllOf(ALL_OF.ToArray());
instance.Lock();
instance.NoneOf(ALL_OF.ToArray());
}
));
}
[Test]
public void throws_TypeMatcherError_if_conditions_empty_and_filter_requested()
{
Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() =>
{
TypeMatcher emptyInstance = new TypeMatcher();
emptyInstance.AllOf(EMPTY_CLASS_VECTOR.ToArray()).AnyOf(EMPTY_CLASS_VECTOR.ToArray()).NoneOf(EMPTY_CLASS_VECTOR.ToArray());
emptyInstance.CreateTypeFilter();
}
));
}
[Test]
public void throws_TypeMatcherError_if_empty_and_filter_requested()
{
Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() =>
{
TypeMatcher emptyInstance = new TypeMatcher();
emptyInstance.CreateTypeFilter();
}
));
}
[Test]
public void clone_returns_open_copy_when_not_locked()
{
instance.AllOf(ALL_OF.ToArray()).AnyOf(ANY_OF.ToArray());
TypeMatcher clone = instance.Clone();
clone.NoneOf(NONE_OF.ToArray());
TypeFilter expectedFilter = new TypeFilter(ALL_OF, ANY_OF, NONE_OF);
assertMatchesTypeFilter(expectedFilter, clone.CreateTypeFilter());
}
[Test]
public void clone_returns_open_copy_when_locked()
{
instance.AllOf(ALL_OF.ToArray()).AnyOf(ANY_OF.ToArray());
instance.Lock();
TypeMatcher clone = instance.Clone();
clone.NoneOf(NONE_OF.ToArray());
TypeFilter expectedFilter = new TypeFilter(ALL_OF, ANY_OF, NONE_OF);
assertMatchesTypeFilter(expectedFilter, clone.CreateTypeFilter());
}
/*============================================================================*/
/* Protected Functions */
/*============================================================================*/
protected void assertMatchesTypeFilter(ITypeFilter expected, ITypeFilter actual)
{
Assert.That (actual.AllOfTypes, Is.EquivalentTo (expected.AllOfTypes), "Expected AllOfTypes to match");
Assert.That (actual.AnyOfTypes, Is.EquivalentTo (expected.AnyOfTypes), "Expected AnyOfTypes to match");
Assert.That (actual.NoneOfTypes, Is.EquivalentTo (expected.NoneOfTypes), "Expected NoneOfTypes to match");
}
private static List<Type> Concat(List<Type> list1, List<Type> list2)
{
List<Type> returnList = new List<Type> ();
foreach (Type t in list1)
returnList.Add(t);
foreach (Type t in list2)
returnList.Add(t);
return returnList;
}
private static List<Type> ShallowClone(List<Type> list1)
{
List<Type> returnList = new List<Type> ();
foreach (Type t in list1)
returnList.Add(t);
return returnList;
}
}
}
| |
#region using
using ConstantContactBO;
using ConstantContactUtility;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity.Core;
using System.Text;
using System.Web.UI;
#endregion using
namespace WebApplication
{
/// <summary>
/// This class contains API Key, Username and Password used to acces Constant resources.
/// Also, it contains definition for State/Province and Country.
/// It exposes methods to retrieve the user Contact List collection from the Constant
/// server with or withoud the pre-filtering enabled
///
/// </summary>
public static class ConstantContact
{
#region Authentication constants
/// <summary>
/// API Application Key and is used to identify the application making an API request
/// </summary>
private static readonly string apiKey = ConfigurationManager.AppSettings["ConstantContactApiKey"];
/// <summary>
/// Constant Contact Customer's user name
/// </summary>
private static readonly string username = ConfigurationManager.AppSettings["ConstantContactUserName"];
/// <summary>
/// Constant Contact Customer's password
/// </summary>
private static readonly string password = ConfigurationManager.AppSettings["ConstantContactPassword"];
#endregion Authentication constants
#region Constants
/// <summary>
/// United States country code
/// </summary>
public const string UnitedStatesCountryCode = "us";
/// <summary>
/// Canada country code
/// </summary>
public const string CanadaCountryCode = "ca";
#endregion Constants
#region Fields
/// <summary>
/// Authentication data
/// </summary>
private static readonly AuthenticationData authenticationData;
#endregion Fields
#region Properties
/// <summary>
/// Authentication data
/// </summary>
public static AuthenticationData AuthenticationData
{
get { return authenticationData; }
}
#endregion Properties
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
static ConstantContact()
{
authenticationData = new AuthenticationData(apiKey, username, password);
}
#endregion Constructor
#region Contact List
/// <summary>
/// Get User Contact List collection
///
/// </summary>
/// <param name="clientScript"></param>
/// <returns></returns>
public static List<ContactList> GetUserContactListCollection(ClientScriptManager clientScript)
{
List<ContactList> list = null;
try
{
string nextChunk;
// get first chunk of user Contact Lists from the server
IList<ContactList> currentContactLists = Utility.GetUserContactListCollection(AuthenticationData,
out nextChunk);
// apply the prefilter to the list collection
IEnumerable<ContactList> prefilteredContactList = PrefilterContactLists(currentContactLists);
// store the prefiltered collection
list = new List<ContactList>(prefilteredContactList);
while (!string.IsNullOrEmpty(nextChunk))
{
string currentChunk = nextChunk;
currentContactLists.Clear();
// get current chunk of user Contact Lists from the server
currentContactLists = Utility.GetUserContactListCollection(AuthenticationData, currentChunk,
out nextChunk);
// apply the prefilter to the list collection
prefilteredContactList = PrefilterContactLists(currentContactLists);
// store the prefiltered collection
list.AddRange(prefilteredContactList);
}
// sort contact list by Sort Order field
list.Sort(Utility.CompareContactListsBySortOrder);
}
catch (ConstantException ce)
{
#region display alert message
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(@"<script language='javascript'>");
stringBuilder.AppendFormat(@"alert('{0}')", ce.Message);
stringBuilder.Append(@"</script>");
clientScript.RegisterStartupScript(typeof(Page), "AlertMessage", stringBuilder.ToString());
#endregion display alert message
}
return list;
}
#endregion Contact List
#region Prefiltering
/// <summary>
/// Prefilter the Contact Lists
/// </summary>
/// <param name="contactLists"></param>
/// <returns></returns>
public static IEnumerable<ContactList> PrefilterContactLists(IEnumerable<ContactList> contactLists)
{
return contactLists;
//// define the collection of lists name do you want
//string[] prefilterNames = new string[] { "List 1", "List 2", "List 3" };
//foreach (ContactList contactList in contactLists)
//{
// foreach (string contactListName in prefilterNames)
// {
// if (string.Equals(contactList.Name, contactListName, System.StringComparison.Ordinal))
// {
// yield return contactList;
// }
// }
//}
}
#endregion Prefiltering
#region State/Province & Country definition
/// <summary>
/// Gets the Country collection
/// </summary>
/// <returns>Array of strings containing Country names</returns>
public static DataTable GetCountryCollection()
{
DataTable countryTable = new DataTable();
countryTable.Columns.Add("Name");
countryTable.Columns.Add("Code");
#region Country Names and Codes
AddCountryToDataTable(countryTable, string.Empty, string.Empty);
AddCountryToDataTable(countryTable, "United States", UnitedStatesCountryCode);
AddCountryToDataTable(countryTable, "Canada", CanadaCountryCode);
AddCountryToDataTable(countryTable, "Afghanistan", "af");
AddCountryToDataTable(countryTable, "Aland Islands", "ax");
AddCountryToDataTable(countryTable, "Albania", "al");
AddCountryToDataTable(countryTable, "Algeria", "dz");
AddCountryToDataTable(countryTable, "American Samoa", "as");
AddCountryToDataTable(countryTable, "Andorra", "ad");
AddCountryToDataTable(countryTable, "Angola", "ao");
AddCountryToDataTable(countryTable, "Anguilla", "ai");
AddCountryToDataTable(countryTable, "Antarctica", "aq");
AddCountryToDataTable(countryTable, "Antigua and Barbuda", "ag");
AddCountryToDataTable(countryTable, "Argentina", "ar");
AddCountryToDataTable(countryTable, "Armenia", "am");
AddCountryToDataTable(countryTable, "Aruba", "aw");
AddCountryToDataTable(countryTable, "Australia", "au");
AddCountryToDataTable(countryTable, "Austria", "at");
AddCountryToDataTable(countryTable, "Azerbaijan", "az");
AddCountryToDataTable(countryTable, "Bahamas", "bs");
AddCountryToDataTable(countryTable, "Bahrain", "bh");
AddCountryToDataTable(countryTable, "Bangladesh", "bd");
AddCountryToDataTable(countryTable, "Barbados", "bb");
AddCountryToDataTable(countryTable, "Belarus", "by");
AddCountryToDataTable(countryTable, "Belgium", "be");
AddCountryToDataTable(countryTable, "Belize", "bz");
AddCountryToDataTable(countryTable, "Benin", "bj");
AddCountryToDataTable(countryTable, "Bermuda", "bm");
AddCountryToDataTable(countryTable, "Bhutan", "bt");
AddCountryToDataTable(countryTable, "Bolivia", "bo");
AddCountryToDataTable(countryTable, "Bosnia and Herzegovina", "ba");
AddCountryToDataTable(countryTable, "Botswana", "bw");
AddCountryToDataTable(countryTable, "Bouvet Island", "bv");
AddCountryToDataTable(countryTable, "Brazil", "br");
AddCountryToDataTable(countryTable, "British Indian Ocean Territory", "io");
AddCountryToDataTable(countryTable, "Brunei Darussalam", "bn");
AddCountryToDataTable(countryTable, "Bulgaria", "bg");
AddCountryToDataTable(countryTable, "Burkina Faso", "bf");
AddCountryToDataTable(countryTable, "Burundi", "bi");
AddCountryToDataTable(countryTable, "Cambodia", "kh");
AddCountryToDataTable(countryTable, "Cameroon", "cm");
AddCountryToDataTable(countryTable, "Cape Verde", "cv");
AddCountryToDataTable(countryTable, "Cayman Islands", "ky");
AddCountryToDataTable(countryTable, "Central African Republic", "cf");
AddCountryToDataTable(countryTable, "Chad", "td");
AddCountryToDataTable(countryTable, "Chile", "cl");
AddCountryToDataTable(countryTable, "China", "cn");
AddCountryToDataTable(countryTable, "Christmas Island", "cx");
AddCountryToDataTable(countryTable, "Cocos (Keeling) Islands", "cc");
AddCountryToDataTable(countryTable, "Colombia", "co");
AddCountryToDataTable(countryTable, "Comoros", "km");
AddCountryToDataTable(countryTable, "Congo", "cg");
AddCountryToDataTable(countryTable, "Congo, Democratic Republic of", "cd");
AddCountryToDataTable(countryTable, "Cook Islands", "ck");
AddCountryToDataTable(countryTable, "Costa Rica", "cr");
AddCountryToDataTable(countryTable, "Cote D'Ivoire", "ci");
AddCountryToDataTable(countryTable, "Croatia", "hr");
AddCountryToDataTable(countryTable, "Cyprus", "cy");
AddCountryToDataTable(countryTable, "Czech Republic", "cz");
AddCountryToDataTable(countryTable, "Denmark", "dk");
AddCountryToDataTable(countryTable, "Djibouti", "dj");
AddCountryToDataTable(countryTable, "Dominica", "dm");
AddCountryToDataTable(countryTable, "Dominican Republic", "do");
AddCountryToDataTable(countryTable, "East Timor", "tl"); //remark:updated from server response
AddCountryToDataTable(countryTable, "Ecuador", "ec");
AddCountryToDataTable(countryTable, "Egypt", "eg");
AddCountryToDataTable(countryTable, "El Salvador", "sv");
AddCountryToDataTable(countryTable, "England", "U1"); //remark: updated from server response
AddCountryToDataTable(countryTable, "Equatorial Guinea", "gq");
AddCountryToDataTable(countryTable, "Eritrea", "er");
AddCountryToDataTable(countryTable, "Estonia", "ee");
AddCountryToDataTable(countryTable, "Ethiopia", "et");
AddCountryToDataTable(countryTable, "Faroe Islands", "fo");
AddCountryToDataTable(countryTable, "Faukland Islands", "fk");
AddCountryToDataTable(countryTable, "Fiji", "fj");
AddCountryToDataTable(countryTable, "Finland", "fi");
AddCountryToDataTable(countryTable, "France", "fr");
AddCountryToDataTable(countryTable, "French Guyana", "gf");
AddCountryToDataTable(countryTable, "French Polynesia", "pf");
AddCountryToDataTable(countryTable, "French Southern Territories", "tf");
AddCountryToDataTable(countryTable, "Gabon", "ga");
AddCountryToDataTable(countryTable, "Gambia", "gm");
AddCountryToDataTable(countryTable, "Georgia", "ge");
AddCountryToDataTable(countryTable, "Germany", "de");
AddCountryToDataTable(countryTable, "Ghana", "gh");
AddCountryToDataTable(countryTable, "Gibraltar", "gi");
AddCountryToDataTable(countryTable, "Greece", "gr");
AddCountryToDataTable(countryTable, "Greenland", "gl");
AddCountryToDataTable(countryTable, "Grenada", "gd");
AddCountryToDataTable(countryTable, "Guadeloupe", "gp");
AddCountryToDataTable(countryTable, "Guam", "gu");
AddCountryToDataTable(countryTable, "Guatemala", "gt");
AddCountryToDataTable(countryTable, "Guernsey", "gg");
AddCountryToDataTable(countryTable, "Guinea", "gn");
AddCountryToDataTable(countryTable, "Guinea-Bissau", "gw");
AddCountryToDataTable(countryTable, "Guyana", "gy");
AddCountryToDataTable(countryTable, "Haiti", "ht");
AddCountryToDataTable(countryTable, "Heard and McDonald Islands", "hm");
AddCountryToDataTable(countryTable, "Honduras", "hn");
AddCountryToDataTable(countryTable, "Hong Kong", "hk");
AddCountryToDataTable(countryTable, "Hungary", "hu");
AddCountryToDataTable(countryTable, "Iceland", "is");
AddCountryToDataTable(countryTable, "India", "in");
AddCountryToDataTable(countryTable, "Indonesia", "id");
AddCountryToDataTable(countryTable, "Iraq", "iq");
AddCountryToDataTable(countryTable, "Ireland", "ie");
AddCountryToDataTable(countryTable, "Isle of Man", "im");
AddCountryToDataTable(countryTable, "Israel", "il");
AddCountryToDataTable(countryTable, "Italy", "it");
AddCountryToDataTable(countryTable, "Jamaica", "jm");
AddCountryToDataTable(countryTable, "Japan", "jp");
AddCountryToDataTable(countryTable, "Jersey", "je");
AddCountryToDataTable(countryTable, "Jordan", "jo");
AddCountryToDataTable(countryTable, "Kazakhstan", "kz");
AddCountryToDataTable(countryTable, "Kenya", "ke");
AddCountryToDataTable(countryTable, "Kiribati", "ki");
AddCountryToDataTable(countryTable, "Kuwait", "kw");
AddCountryToDataTable(countryTable, "Kyrgyzstan", "kg");
AddCountryToDataTable(countryTable, "Laos", "la");
AddCountryToDataTable(countryTable, "Latvia", "lv");
AddCountryToDataTable(countryTable, "Lebanon", "lb");
AddCountryToDataTable(countryTable, "Lesotho", "ls");
AddCountryToDataTable(countryTable, "Liberia", "lr");
AddCountryToDataTable(countryTable, "Libya", "ly");
AddCountryToDataTable(countryTable, "Liechtenstein", "li");
AddCountryToDataTable(countryTable, "Lithuania", "lt");
AddCountryToDataTable(countryTable, "Luxembourg", "lu");
AddCountryToDataTable(countryTable, "Macao", "mo");
AddCountryToDataTable(countryTable, "Macedonia", "mk");
AddCountryToDataTable(countryTable, "Madagascar", "mg");
AddCountryToDataTable(countryTable, "Malawi", "mw");
AddCountryToDataTable(countryTable, "Malaysia", "my");
AddCountryToDataTable(countryTable, "Maldives", "mv");
AddCountryToDataTable(countryTable, "Mali", "ml");
AddCountryToDataTable(countryTable, "Malta", "mt");
AddCountryToDataTable(countryTable, "Marshall Islands", "mh");
AddCountryToDataTable(countryTable, "Martinique", "mq");
AddCountryToDataTable(countryTable, "Mauritania", "mr");
AddCountryToDataTable(countryTable, "Mauritius", "mu");
AddCountryToDataTable(countryTable, "Mayotte", "yt");
AddCountryToDataTable(countryTable, "Mexico", "mx");
AddCountryToDataTable(countryTable, "Micronesia", "fm");
AddCountryToDataTable(countryTable, "Moldova", "md");
AddCountryToDataTable(countryTable, "Monaco", "mc");
AddCountryToDataTable(countryTable, "Mongolia", "mn");
AddCountryToDataTable(countryTable, "Montenegro", "me");
AddCountryToDataTable(countryTable, "Montserrat", "ms");
AddCountryToDataTable(countryTable, "Morocco", "ma");
AddCountryToDataTable(countryTable, "Mozambique", "mz");
AddCountryToDataTable(countryTable, "Myanmar", "mm");
AddCountryToDataTable(countryTable, "Namibia", "na");
AddCountryToDataTable(countryTable, "Nauru", "nr");
AddCountryToDataTable(countryTable, "Nepal", "np");
AddCountryToDataTable(countryTable, "Netherlands", "nl");
AddCountryToDataTable(countryTable, "Netherlands Antilles", "an");
AddCountryToDataTable(countryTable, "Neutral Zone", "nt"); //remark:updated from server response
AddCountryToDataTable(countryTable, "New Caledonia", "nc");
AddCountryToDataTable(countryTable, "New Zealand", "nz");
AddCountryToDataTable(countryTable, "Nicaragua", "ni");
AddCountryToDataTable(countryTable, "Niger", "ne");
AddCountryToDataTable(countryTable, "Nigeria", "ng");
AddCountryToDataTable(countryTable, "Niue", "nu");
AddCountryToDataTable(countryTable, "Norfolk Island", "nf");
AddCountryToDataTable(countryTable, "Northern Ireland", "U4"); //remark:updated from server response
AddCountryToDataTable(countryTable, "Northern Mariana Islands", "mp");
AddCountryToDataTable(countryTable, "Norway", "no");
AddCountryToDataTable(countryTable, "Oman", "om");
AddCountryToDataTable(countryTable, "Pakistan", "pk");
AddCountryToDataTable(countryTable, "Palau", "pw");
AddCountryToDataTable(countryTable, "Palestinian Territory, Occupied", "ps");
AddCountryToDataTable(countryTable, "Panama", "pa");
AddCountryToDataTable(countryTable, "Papua New Guinea", "pg");
AddCountryToDataTable(countryTable, "Paraguay", "py");
AddCountryToDataTable(countryTable, "Peru", "pe");
AddCountryToDataTable(countryTable, "Philippines", "ph");
AddCountryToDataTable(countryTable, "Pitcairn", "pn");
AddCountryToDataTable(countryTable, "Poland", "pl");
AddCountryToDataTable(countryTable, "Portugal", "pt");
AddCountryToDataTable(countryTable, "Puerto Rico", "pr");
AddCountryToDataTable(countryTable, "Qatar", "qa");
AddCountryToDataTable(countryTable, "Reunion", "re");
AddCountryToDataTable(countryTable, "Romania", "ro");
AddCountryToDataTable(countryTable, "Russian Federation", "ru");
AddCountryToDataTable(countryTable, "Rwanda", "rw");
AddCountryToDataTable(countryTable, "Saint Barthelemy", "bl");
AddCountryToDataTable(countryTable, "Saint Helena", "sh");
AddCountryToDataTable(countryTable, "Saint Kitts and Nevis", "kn");
AddCountryToDataTable(countryTable, "Saint Lucia", "lc");
AddCountryToDataTable(countryTable, "Saint Martin", "mf");
AddCountryToDataTable(countryTable, "Saint Pierre and Miquelon", "pm");
AddCountryToDataTable(countryTable, "Saint Vincent & the Grenadines", "vc");
AddCountryToDataTable(countryTable, "Samoa", "ws");
AddCountryToDataTable(countryTable, "San Marino", "sm");
AddCountryToDataTable(countryTable, "Sao Tome and Principe", "st");
AddCountryToDataTable(countryTable, "Saudi Arabia", "sa");
AddCountryToDataTable(countryTable, "Scotland", "U3"); //remark:updated from server response
AddCountryToDataTable(countryTable, "Senegal", "sn");
AddCountryToDataTable(countryTable, "Serbia", "rs");
AddCountryToDataTable(countryTable, "Seychelles", "sc");
AddCountryToDataTable(countryTable, "Sierra Leone", "sl");
AddCountryToDataTable(countryTable, "Singapore", "sg");
AddCountryToDataTable(countryTable, "Slovakia", "sk");
AddCountryToDataTable(countryTable, "Slovenia", "si");
AddCountryToDataTable(countryTable, "Solomon Islands", "sb");
AddCountryToDataTable(countryTable, "Somalia", "so");
AddCountryToDataTable(countryTable, "South Africa", "za");
AddCountryToDataTable(countryTable, "South Georgia & S. Sandwich Is.", "gs");
AddCountryToDataTable(countryTable, "South Korea", "kr");
AddCountryToDataTable(countryTable, "Spain", "es");
AddCountryToDataTable(countryTable, "Sri Lanka", "lk");
AddCountryToDataTable(countryTable, "Suriname", "sr");
AddCountryToDataTable(countryTable, "Svalbard and Jan Mayen", "sj");
AddCountryToDataTable(countryTable, "Swaziland", "sz");
AddCountryToDataTable(countryTable, "Sweden", "se");
AddCountryToDataTable(countryTable, "Switzerland", "ch");
AddCountryToDataTable(countryTable, "Taiwan", "tw");
AddCountryToDataTable(countryTable, "Tajikistan", "tj");
AddCountryToDataTable(countryTable, "Tanzania", "tz");
AddCountryToDataTable(countryTable, "Thailand", "th");
AddCountryToDataTable(countryTable, "Togo", "tg");
AddCountryToDataTable(countryTable, "Tokelau", "tk");
AddCountryToDataTable(countryTable, "Tonga", "to");
AddCountryToDataTable(countryTable, "Trinidad and Tobago", "tt");
AddCountryToDataTable(countryTable, "Tunisia", "tn");
AddCountryToDataTable(countryTable, "Turkey", "tr");
AddCountryToDataTable(countryTable, "Turkmenistan", "tm");
AddCountryToDataTable(countryTable, "Turks and Caicos Islands", "tc");
AddCountryToDataTable(countryTable, "Tuvalu", "tv");
AddCountryToDataTable(countryTable, "Uganda", "ug");
AddCountryToDataTable(countryTable, "Ukraine", "ua");
AddCountryToDataTable(countryTable, "United Arab Emirates", "ae");
AddCountryToDataTable(countryTable, "United Kingdom", "gb");
AddCountryToDataTable(countryTable, "United States Minor Outlying Is.", "um");
AddCountryToDataTable(countryTable, "Uruguay", "uy");
AddCountryToDataTable(countryTable, "Uzbekistan", "uz");
AddCountryToDataTable(countryTable, "Vanuatu", "vu");
AddCountryToDataTable(countryTable, "Vatican City State", "va");
AddCountryToDataTable(countryTable, "Venezuela", "ve");
AddCountryToDataTable(countryTable, "Viet Nam", "vn");
AddCountryToDataTable(countryTable, "Virgin Islands, British", "vg");
AddCountryToDataTable(countryTable, "Virgin Islands, U.S.", "vi");
AddCountryToDataTable(countryTable, "Wales", "u2");
AddCountryToDataTable(countryTable, "Wallis and Futuna", "wf");
AddCountryToDataTable(countryTable, "Western Sahara", "eh");
AddCountryToDataTable(countryTable, "Yemen", "ye");
AddCountryToDataTable(countryTable, "Zambia", "zm");
AddCountryToDataTable(countryTable, "Zimbabwe", "zw");
#endregion Country Names and Codes
return countryTable;
}
/// <summary>
/// Gets the State/Province (US/Canada) collection
/// </summary>
/// <returns>Array of strings representing State/Provice (US/Canada) names</returns>
public static DataTable GetStateCollection()
{
DataTable provinceTable = new DataTable();
provinceTable.Columns.Add("Name");
provinceTable.Columns.Add("Code");
provinceTable.Columns.Add("CountryCode");
#region State / Province Names and Codes
AddProvinceToDataTable(provinceTable, string.Empty, string.Empty, string.Empty);
AddProvinceToDataTable(provinceTable, "Alabama", "AL", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Alaska", "AK", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Alberta", "AB", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "Arizona", "AZ", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Arkansas", "AR", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Armed Forces Americas", "AA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Armed Forces Europe", "AE", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Armed Forces Pacific", "AP", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "British Columbia", "BC", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "California", "CA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Colorado", "CO", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Connecticut", "CT", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Delaware", "DE", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "District of Columbia", "DC", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Florida", "FL", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Georgia", "GA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Hawaii", "HI", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Idaho", "ID", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Illinois", "IL", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Indiana", "IN", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Iowa", "IA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Kansas", "KS", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Kentucky", "KY", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Louisiana", "LA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Maine", "ME", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Manitoba", "MB", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "Maryland", "MD", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Massachusetts", "MA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Michigan", "MI", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Minnesota", "MN", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Mississippi", "MS", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Missouri", "MO", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Montana", "MT", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Nebraska", "NE", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Nevada", "NV", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "New Brunswick", "NB", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "New Hampshire", "NH", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "New Jersey", "NJ", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "New Mexico", "NM", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "New York", "NY", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Newfoundland and Labrador", "NL", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "North Carolina", "NC", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "North Dakota", "ND", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Northwest Territories", "NT", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "Nova Scotia", "NS", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "Nunavut", "NU", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "Ohio", "OH", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Oklahoma", "OK", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Ontario", "ON", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "Oregon", "OR", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Pennsylvania", "PA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Prince Edward Island", "PE", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "Quebec", "QC", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "Rhode Island", "RI", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Saskatchewan", "SK", CanadaCountryCode);
AddProvinceToDataTable(provinceTable, "South Carolina", "SC", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "South Dakota", "SD", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Tennessee", "TN", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Texas", "TX", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Utah", "UT", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Vermont", "VT", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Virginia", "VA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Washington", "WA", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "West Virginia", "WV", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Wisconsin", "WI", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Wyoming", "WY", UnitedStatesCountryCode);
AddProvinceToDataTable(provinceTable, "Yukon Territory", "YT", CanadaCountryCode);
#endregion State / Province Names and Codes
return provinceTable;
}
/// <summary>
/// Creates a new row for the data table using specified name and code
/// </summary>
/// <param name="table"></param>
/// <param name="name"></param>
/// <param name="code"></param>
private static void AddCountryToDataTable(DataTable table, string name, string code)
{
DataRow row = table.NewRow();
row["Name"] = name;
row["Code"] = code;
table.Rows.Add(row);
}
/// <summary>
/// Creates a new row for the data table using specified name and code and country code
/// </summary>
/// <param name="table"></param>
/// <param name="name"></param>
/// <param name="code"></param>
/// <param name="countryCode"></param>
private static void AddProvinceToDataTable(DataTable table, string name, string code, string countryCode)
{
DataRow row = table.NewRow();
row["Name"] = name;
row["Code"] = code;
row["CountryCode"] = countryCode;
table.Rows.Add(row);
}
#endregion State/Province & Country definition
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using Microsoft.DotNet.Cli.Build.Framework;
using Microsoft.DotNet.InternalAbstractions;
using static Microsoft.DotNet.Cli.Build.Framework.BuildHelpers;
namespace Microsoft.DotNet.Cli.Build
{
public class DebTargets
{
[Target(nameof(GenerateSdkDeb))]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult GenerateDebs(BuildTargetContext c)
{
return c.Success();
}
[Target(nameof(InstallSharedFramework))]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult GenerateSdkDeb(BuildTargetContext c)
{
// Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools
// So we need to skip this target if the tools aren't present.
// https://github.com/dotnet/core-setup/issues/167
if (DebuildNotPresent())
{
c.Info("Debuild not present, skipping target: {nameof(RemovePackages)}");
return c.Success();
}
var channel = c.BuildContext.Get<string>("Channel").ToLower();
var packageName = CliMonikers.GetSdkDebianPackageName(c);
var version = c.BuildContext.Get<BuildVersion>("BuildVersion").NuGetVersion;
var debFile = c.BuildContext.Get<string>("SdkInstallerFile");
var manPagesDir = Path.Combine(Dirs.RepoRoot, "Documentation", "manpages");
var previousVersionURL = $"https://dotnetcli.blob.core.windows.net/dotnet/{channel}/Installers/Latest/dotnet-ubuntu-x64.latest.deb";
var sdkPublishRoot = c.BuildContext.Get<string>("CLISDKRoot");
var sharedFxDebianPackageName = Monikers.GetDebianSharedFrameworkPackageName(CliDependencyVersions.SharedFrameworkVersion);
var objRoot = Path.Combine(Dirs.Output, "obj", "debian", "sdk");
if (Directory.Exists(objRoot))
{
Directory.Delete(objRoot, true);
}
Directory.CreateDirectory(objRoot);
Cmd(Path.Combine(Dirs.RepoRoot, "scripts", "package", "package-debian.sh"),
"-v", version,
"-i", sdkPublishRoot,
"-o", debFile,
"-p", packageName,
"-b", Monikers.CLISdkBrandName,
"-m", manPagesDir,
"--framework-debian-package-name", sharedFxDebianPackageName,
"--framework-nuget-name", Monikers.SharedFrameworkName,
"--framework-nuget-version", CliDependencyVersions.SharedFrameworkVersion,
"--previous-version-url", previousVersionURL,
"--obj-root", objRoot)
.Execute()
.EnsureSuccessful();
return c.Success();
}
[Target(nameof(InstallSDK),
nameof(RunE2ETest),
nameof(RemovePackages))]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult TestDebInstaller(BuildTargetContext c)
{
return c.Success();
}
[Target]
public static BuildTargetResult InstallSharedHost(BuildTargetContext c)
{
// Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools
// So we need to skip this target if the tools aren't present.
// https://github.com/dotnet/core-setup/issues/167
if (DebuildNotPresent())
{
c.Info("Debuild not present, skipping target: {nameof(RemovePackages)}");
return c.Success();
}
InstallPackage(c.BuildContext.Get<string>("SharedHostInstallerFile"));
return c.Success();
}
[Target(nameof(InstallSharedHost))]
public static BuildTargetResult InstallHostFxr(BuildTargetContext c)
{
// Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools
// So we need to skip this target if the tools aren't present.
// https://github.com/dotnet/core-setup/issues/167
if (DebuildNotPresent())
{
c.Info("Debuild not present, skipping target: {nameof(RemovePackages)}");
return c.Success();
}
InstallPackage(c.BuildContext.Get<string>("HostFxrInstallerFile"));
return c.Success();
}
[Target(nameof(InstallHostFxr))]
public static BuildTargetResult InstallSharedFramework(BuildTargetContext c)
{
// Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools
// So we need to skip this target if the tools aren't present.
// https://github.com/dotnet/core-setup/issues/167
if (DebuildNotPresent())
{
c.Info("Debuild not present, skipping target: {nameof(RemovePackages)}");
return c.Success();
}
InstallPackage(c.BuildContext.Get<string>("SharedFrameworkInstallerFile"));
return c.Success();
}
[Target(nameof(InstallSharedFramework))]
public static BuildTargetResult InstallSDK(BuildTargetContext c)
{
// Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools
// So we need to skip this target if the tools aren't present.
// https://github.com/dotnet/core-setup/issues/167
if (DebuildNotPresent())
{
c.Info("Debuild not present, skipping target: {nameof(RemovePackages)}");
return c.Success();
}
InstallPackage(c.BuildContext.Get<string>("SdkInstallerFile"));
return c.Success();
}
[Target]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult RunE2ETest(BuildTargetContext c)
{
// Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools
// So we need to skip this target if the tools aren't present.
// https://github.com/dotnet/core-setup/issues/167
if (DebuildNotPresent())
{
c.Info("Debuild not present, skipping target: {nameof(RemovePackages)}");
return c.Success();
}
Directory.SetCurrentDirectory(Path.Combine(Dirs.RepoRoot, "test", "EndToEnd"));
Cmd("dotnet", "build")
.Execute()
.EnsureSuccessful();
var testResultsPath = Path.Combine(Dirs.Output, "obj", "debian", "test", "debian-endtoend-testResults.xml");
Cmd("dotnet", "test", "-xml", testResultsPath)
.Execute()
.EnsureSuccessful();
return c.Success();
}
[Target]
[BuildPlatforms(BuildPlatform.Ubuntu)]
public static BuildTargetResult RemovePackages(BuildTargetContext c)
{
// Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools
// So we need to skip this target if the tools aren't present.
// https://github.com/dotnet/core-setup/issues/167
if (DebuildNotPresent())
{
c.Info("Debuild not present, skipping target: {nameof(RemovePackages)}");
return c.Success();
}
IEnumerable<string> orderedPackageNames = new List<string>()
{
CliMonikers.GetSdkDebianPackageName(c),
Monikers.GetDebianSharedFrameworkPackageName(CliDependencyVersions.SharedFrameworkVersion),
Monikers.GetDebianHostFxrPackageName(CliDependencyVersions.HostFxrVersion),
Monikers.GetDebianSharedHostPackageName(c)
};
foreach(var packageName in orderedPackageNames)
{
RemovePackage(packageName);
}
return c.Success();
}
private static void InstallPackage(string packagePath)
{
Cmd("sudo", "dpkg", "-i", packagePath)
.Execute()
.EnsureSuccessful();
}
private static void RemovePackage(string packageName)
{
Cmd("sudo", "dpkg", "-r", packageName)
.Execute()
.EnsureSuccessful();
}
private static bool DebuildNotPresent()
{
return Cmd("/usr/bin/env", "debuild", "-h").Execute().ExitCode != 0;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.