context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/firestore/v1beta1/document.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Firestore.V1Beta1 {
/// <summary>Holder for reflection information generated from google/firestore/v1beta1/document.proto</summary>
public static partial class DocumentReflection {
#region Descriptor
/// <summary>File descriptor for google/firestore/v1beta1/document.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DocumentReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cidnb29nbGUvZmlyZXN0b3JlL3YxYmV0YTEvZG9jdW1lbnQucHJvdG8SGGdv",
"b2dsZS5maXJlc3RvcmUudjFiZXRhMRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9u",
"cy5wcm90bxocZ29vZ2xlL3Byb3RvYnVmL3N0cnVjdC5wcm90bxofZ29vZ2xl",
"L3Byb3RvYnVmL3RpbWVzdGFtcC5wcm90bxoYZ29vZ2xlL3R5cGUvbGF0bG5n",
"LnByb3RvIooCCghEb2N1bWVudBIMCgRuYW1lGAEgASgJEj4KBmZpZWxkcxgC",
"IAMoCzIuLmdvb2dsZS5maXJlc3RvcmUudjFiZXRhMS5Eb2N1bWVudC5GaWVs",
"ZHNFbnRyeRIvCgtjcmVhdGVfdGltZRgDIAEoCzIaLmdvb2dsZS5wcm90b2J1",
"Zi5UaW1lc3RhbXASLwoLdXBkYXRlX3RpbWUYBCABKAsyGi5nb29nbGUucHJv",
"dG9idWYuVGltZXN0YW1wGk4KC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIu",
"CgV2YWx1ZRgCIAEoCzIfLmdvb2dsZS5maXJlc3RvcmUudjFiZXRhMS5WYWx1",
"ZToCOAEiuAMKBVZhbHVlEjAKCm51bGxfdmFsdWUYCyABKA4yGi5nb29nbGUu",
"cHJvdG9idWYuTnVsbFZhbHVlSAASFwoNYm9vbGVhbl92YWx1ZRgBIAEoCEgA",
"EhcKDWludGVnZXJfdmFsdWUYAiABKANIABIWCgxkb3VibGVfdmFsdWUYAyAB",
"KAFIABI1Cg90aW1lc3RhbXBfdmFsdWUYCiABKAsyGi5nb29nbGUucHJvdG9i",
"dWYuVGltZXN0YW1wSAASFgoMc3RyaW5nX3ZhbHVlGBEgASgJSAASFQoLYnl0",
"ZXNfdmFsdWUYEiABKAxIABIZCg9yZWZlcmVuY2VfdmFsdWUYBSABKAlIABIu",
"Cg9nZW9fcG9pbnRfdmFsdWUYCCABKAsyEy5nb29nbGUudHlwZS5MYXRMbmdI",
"ABI7CgthcnJheV92YWx1ZRgJIAEoCzIkLmdvb2dsZS5maXJlc3RvcmUudjFi",
"ZXRhMS5BcnJheVZhbHVlSAASNwoJbWFwX3ZhbHVlGAYgASgLMiIuZ29vZ2xl",
"LmZpcmVzdG9yZS52MWJldGExLk1hcFZhbHVlSABCDAoKdmFsdWVfdHlwZSI9",
"CgpBcnJheVZhbHVlEi8KBnZhbHVlcxgBIAMoCzIfLmdvb2dsZS5maXJlc3Rv",
"cmUudjFiZXRhMS5WYWx1ZSKaAQoITWFwVmFsdWUSPgoGZmllbGRzGAEgAygL",
"Mi4uZ29vZ2xlLmZpcmVzdG9yZS52MWJldGExLk1hcFZhbHVlLkZpZWxkc0Vu",
"dHJ5Gk4KC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIuCgV2YWx1ZRgCIAEo",
"CzIfLmdvb2dsZS5maXJlc3RvcmUudjFiZXRhMS5WYWx1ZToCOAFCuwEKHGNv",
"bS5nb29nbGUuZmlyZXN0b3JlLnYxYmV0YTFCDURvY3VtZW50UHJvdG9QAVpB",
"Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9maXJlc3Rv",
"cmUvdjFiZXRhMTtmaXJlc3RvcmWiAgRHQ0ZTqgIeR29vZ2xlLkNsb3VkLkZp",
"cmVzdG9yZS5WMUJldGExygIeR29vZ2xlXENsb3VkXEZpcmVzdG9yZVxWMWJl",
"dGExYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Type.LatlngReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.Document), global::Google.Cloud.Firestore.V1Beta1.Document.Parser, new[]{ "Name", "Fields", "CreateTime", "UpdateTime" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.Value), global::Google.Cloud.Firestore.V1Beta1.Value.Parser, new[]{ "NullValue", "BooleanValue", "IntegerValue", "DoubleValue", "TimestampValue", "StringValue", "BytesValue", "ReferenceValue", "GeoPointValue", "ArrayValue", "MapValue" }, new[]{ "ValueType" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.ArrayValue), global::Google.Cloud.Firestore.V1Beta1.ArrayValue.Parser, new[]{ "Values" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Firestore.V1Beta1.MapValue), global::Google.Cloud.Firestore.V1Beta1.MapValue.Parser, new[]{ "Fields" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, })
}));
}
#endregion
}
#region Messages
/// <summary>
/// A Firestore document.
///
/// Must not exceed 1 MiB - 4 bytes.
/// </summary>
public sealed partial class Document : pb::IMessage<Document> {
private static readonly pb::MessageParser<Document> _parser = new pb::MessageParser<Document>(() => new Document());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Document> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.DocumentReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Document() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Document(Document other) : this() {
name_ = other.name_;
fields_ = other.fields_.Clone();
CreateTime = other.createTime_ != null ? other.CreateTime.Clone() : null;
UpdateTime = other.updateTime_ != null ? other.UpdateTime.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Document Clone() {
return new Document(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The resource name of the document, for example
/// `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "fields" field.</summary>
public const int FieldsFieldNumber = 2;
private static readonly pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value>.Codec _map_fields_codec
= new pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Cloud.Firestore.V1Beta1.Value.Parser), 18);
private readonly pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value> fields_ = new pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value>();
/// <summary>
/// The document's fields.
///
/// The map keys represent field names.
///
/// A simple field name contains only characters `a` to `z`, `A` to `Z`,
/// `0` to `9`, or `_`, and must not start with `0` to `9` or `_`. For example,
/// `foo_bar_17`.
///
/// Field names matching the regular expression `__.*__` are reserved. Reserved
/// field names are forbidden except in certain documented contexts. The map
/// keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be
/// empty.
///
/// Field paths may be used in other contexts to refer to structured fields
/// defined here. For `map_value`, the field path is represented by the simple
/// or quoted field names of the containing fields, delimited by `.`. For
/// example, the structured field
/// `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be
/// represented by the field path `foo.x&y`.
///
/// Within a field path, a quoted field name starts and ends with `` ` `` and
/// may contain any character. Some characters, including `` ` ``, must be
/// escaped using a `\`. For example, `` `x&y` `` represents `x&y` and
/// `` `bak\`tik` `` represents `` bak`tik ``.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value> Fields {
get { return fields_; }
}
/// <summary>Field number for the "create_time" field.</summary>
public const int CreateTimeFieldNumber = 3;
private global::Google.Protobuf.WellKnownTypes.Timestamp createTime_;
/// <summary>
/// Output only. The time at which the document was created.
///
/// This value increases monotonically when a document is deleted then
/// recreated. It can also be compared to values from other documents and
/// the `read_time` of a query.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp CreateTime {
get { return createTime_; }
set {
createTime_ = value;
}
}
/// <summary>Field number for the "update_time" field.</summary>
public const int UpdateTimeFieldNumber = 4;
private global::Google.Protobuf.WellKnownTypes.Timestamp updateTime_;
/// <summary>
/// Output only. The time at which the document was last changed.
///
/// This value is initally set to the `create_time` then increases
/// monotonically with each change to the document. It can also be
/// compared to values from other documents and the `read_time` of a query.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp UpdateTime {
get { return updateTime_; }
set {
updateTime_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Document);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Document other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (!Fields.Equals(other.Fields)) return false;
if (!object.Equals(CreateTime, other.CreateTime)) return false;
if (!object.Equals(UpdateTime, other.UpdateTime)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
hash ^= Fields.GetHashCode();
if (createTime_ != null) hash ^= CreateTime.GetHashCode();
if (updateTime_ != null) hash ^= UpdateTime.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 (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
fields_.WriteTo(output, _map_fields_codec);
if (createTime_ != null) {
output.WriteRawTag(26);
output.WriteMessage(CreateTime);
}
if (updateTime_ != null) {
output.WriteRawTag(34);
output.WriteMessage(UpdateTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
size += fields_.CalculateSize(_map_fields_codec);
if (createTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(CreateTime);
}
if (updateTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateTime);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Document other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
fields_.Add(other.fields_);
if (other.createTime_ != null) {
if (createTime_ == null) {
createTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
CreateTime.MergeFrom(other.CreateTime);
}
if (other.updateTime_ != null) {
if (updateTime_ == null) {
updateTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
UpdateTime.MergeFrom(other.UpdateTime);
}
}
[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: {
Name = input.ReadString();
break;
}
case 18: {
fields_.AddEntriesFrom(input, _map_fields_codec);
break;
}
case 26: {
if (createTime_ == null) {
createTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(createTime_);
break;
}
case 34: {
if (updateTime_ == null) {
updateTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(updateTime_);
break;
}
}
}
}
}
/// <summary>
/// A message that can hold any of the supported value types.
/// </summary>
public sealed partial class Value : pb::IMessage<Value> {
private static readonly pb::MessageParser<Value> _parser = new pb::MessageParser<Value>(() => new Value());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Value> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.DocumentReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value(Value other) : this() {
switch (other.ValueTypeCase) {
case ValueTypeOneofCase.NullValue:
NullValue = other.NullValue;
break;
case ValueTypeOneofCase.BooleanValue:
BooleanValue = other.BooleanValue;
break;
case ValueTypeOneofCase.IntegerValue:
IntegerValue = other.IntegerValue;
break;
case ValueTypeOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueTypeOneofCase.TimestampValue:
TimestampValue = other.TimestampValue.Clone();
break;
case ValueTypeOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueTypeOneofCase.BytesValue:
BytesValue = other.BytesValue;
break;
case ValueTypeOneofCase.ReferenceValue:
ReferenceValue = other.ReferenceValue;
break;
case ValueTypeOneofCase.GeoPointValue:
GeoPointValue = other.GeoPointValue.Clone();
break;
case ValueTypeOneofCase.ArrayValue:
ArrayValue = other.ArrayValue.Clone();
break;
case ValueTypeOneofCase.MapValue:
MapValue = other.MapValue.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Value Clone() {
return new Value(this);
}
/// <summary>Field number for the "null_value" field.</summary>
public const int NullValueFieldNumber = 11;
/// <summary>
/// A null value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.NullValue NullValue {
get { return valueTypeCase_ == ValueTypeOneofCase.NullValue ? (global::Google.Protobuf.WellKnownTypes.NullValue) valueType_ : 0; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.NullValue;
}
}
/// <summary>Field number for the "boolean_value" field.</summary>
public const int BooleanValueFieldNumber = 1;
/// <summary>
/// A boolean value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool BooleanValue {
get { return valueTypeCase_ == ValueTypeOneofCase.BooleanValue ? (bool) valueType_ : false; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.BooleanValue;
}
}
/// <summary>Field number for the "integer_value" field.</summary>
public const int IntegerValueFieldNumber = 2;
/// <summary>
/// An integer value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long IntegerValue {
get { return valueTypeCase_ == ValueTypeOneofCase.IntegerValue ? (long) valueType_ : 0L; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.IntegerValue;
}
}
/// <summary>Field number for the "double_value" field.</summary>
public const int DoubleValueFieldNumber = 3;
/// <summary>
/// A double value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double DoubleValue {
get { return valueTypeCase_ == ValueTypeOneofCase.DoubleValue ? (double) valueType_ : 0D; }
set {
valueType_ = value;
valueTypeCase_ = ValueTypeOneofCase.DoubleValue;
}
}
/// <summary>Field number for the "timestamp_value" field.</summary>
public const int TimestampValueFieldNumber = 10;
/// <summary>
/// A timestamp value.
///
/// Precise only to microseconds. When stored, any additional precision is
/// rounded down.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp TimestampValue {
get { return valueTypeCase_ == ValueTypeOneofCase.TimestampValue ? (global::Google.Protobuf.WellKnownTypes.Timestamp) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.TimestampValue;
}
}
/// <summary>Field number for the "string_value" field.</summary>
public const int StringValueFieldNumber = 17;
/// <summary>
/// A string value.
///
/// The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes.
/// Only the first 1,500 bytes of the UTF-8 representation are considered by
/// queries.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string StringValue {
get { return valueTypeCase_ == ValueTypeOneofCase.StringValue ? (string) valueType_ : ""; }
set {
valueType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueTypeCase_ = ValueTypeOneofCase.StringValue;
}
}
/// <summary>Field number for the "bytes_value" field.</summary>
public const int BytesValueFieldNumber = 18;
/// <summary>
/// A bytes value.
///
/// Must not exceed 1 MiB - 89 bytes.
/// Only the first 1,500 bytes are considered by queries.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString BytesValue {
get { return valueTypeCase_ == ValueTypeOneofCase.BytesValue ? (pb::ByteString) valueType_ : pb::ByteString.Empty; }
set {
valueType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueTypeCase_ = ValueTypeOneofCase.BytesValue;
}
}
/// <summary>Field number for the "reference_value" field.</summary>
public const int ReferenceValueFieldNumber = 5;
/// <summary>
/// A reference to a document. For example:
/// `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ReferenceValue {
get { return valueTypeCase_ == ValueTypeOneofCase.ReferenceValue ? (string) valueType_ : ""; }
set {
valueType_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueTypeCase_ = ValueTypeOneofCase.ReferenceValue;
}
}
/// <summary>Field number for the "geo_point_value" field.</summary>
public const int GeoPointValueFieldNumber = 8;
/// <summary>
/// A geo point value representing a point on the surface of Earth.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Type.LatLng GeoPointValue {
get { return valueTypeCase_ == ValueTypeOneofCase.GeoPointValue ? (global::Google.Type.LatLng) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.GeoPointValue;
}
}
/// <summary>Field number for the "array_value" field.</summary>
public const int ArrayValueFieldNumber = 9;
/// <summary>
/// An array value.
///
/// Cannot contain another array value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Firestore.V1Beta1.ArrayValue ArrayValue {
get { return valueTypeCase_ == ValueTypeOneofCase.ArrayValue ? (global::Google.Cloud.Firestore.V1Beta1.ArrayValue) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.ArrayValue;
}
}
/// <summary>Field number for the "map_value" field.</summary>
public const int MapValueFieldNumber = 6;
/// <summary>
/// A map value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Firestore.V1Beta1.MapValue MapValue {
get { return valueTypeCase_ == ValueTypeOneofCase.MapValue ? (global::Google.Cloud.Firestore.V1Beta1.MapValue) valueType_ : null; }
set {
valueType_ = value;
valueTypeCase_ = value == null ? ValueTypeOneofCase.None : ValueTypeOneofCase.MapValue;
}
}
private object valueType_;
/// <summary>Enum of possible cases for the "value_type" oneof.</summary>
public enum ValueTypeOneofCase {
None = 0,
NullValue = 11,
BooleanValue = 1,
IntegerValue = 2,
DoubleValue = 3,
TimestampValue = 10,
StringValue = 17,
BytesValue = 18,
ReferenceValue = 5,
GeoPointValue = 8,
ArrayValue = 9,
MapValue = 6,
}
private ValueTypeOneofCase valueTypeCase_ = ValueTypeOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ValueTypeOneofCase ValueTypeCase {
get { return valueTypeCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearValueType() {
valueTypeCase_ = ValueTypeOneofCase.None;
valueType_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Value);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Value other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (NullValue != other.NullValue) return false;
if (BooleanValue != other.BooleanValue) return false;
if (IntegerValue != other.IntegerValue) return false;
if (DoubleValue != other.DoubleValue) return false;
if (!object.Equals(TimestampValue, other.TimestampValue)) return false;
if (StringValue != other.StringValue) return false;
if (BytesValue != other.BytesValue) return false;
if (ReferenceValue != other.ReferenceValue) return false;
if (!object.Equals(GeoPointValue, other.GeoPointValue)) return false;
if (!object.Equals(ArrayValue, other.ArrayValue)) return false;
if (!object.Equals(MapValue, other.MapValue)) return false;
if (ValueTypeCase != other.ValueTypeCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) hash ^= NullValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) hash ^= BooleanValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) hash ^= IntegerValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) hash ^= DoubleValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) hash ^= TimestampValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) hash ^= StringValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.BytesValue) hash ^= BytesValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.ReferenceValue) hash ^= ReferenceValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) hash ^= GeoPointValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) hash ^= ArrayValue.GetHashCode();
if (valueTypeCase_ == ValueTypeOneofCase.MapValue) hash ^= MapValue.GetHashCode();
hash ^= (int) valueTypeCase_;
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 (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) {
output.WriteRawTag(8);
output.WriteBool(BooleanValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) {
output.WriteRawTag(16);
output.WriteInt64(IntegerValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) {
output.WriteRawTag(25);
output.WriteDouble(DoubleValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.ReferenceValue) {
output.WriteRawTag(42);
output.WriteString(ReferenceValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.MapValue) {
output.WriteRawTag(50);
output.WriteMessage(MapValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
output.WriteRawTag(66);
output.WriteMessage(GeoPointValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
output.WriteRawTag(74);
output.WriteMessage(ArrayValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
output.WriteRawTag(82);
output.WriteMessage(TimestampValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) {
output.WriteRawTag(88);
output.WriteEnum((int) NullValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) {
output.WriteRawTag(138, 1);
output.WriteString(StringValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BytesValue) {
output.WriteRawTag(146, 1);
output.WriteBytes(BytesValue);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (valueTypeCase_ == ValueTypeOneofCase.NullValue) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NullValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BooleanValue) {
size += 1 + 1;
}
if (valueTypeCase_ == ValueTypeOneofCase.IntegerValue) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(IntegerValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.DoubleValue) {
size += 1 + 8;
}
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TimestampValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.StringValue) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(StringValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.BytesValue) {
size += 2 + pb::CodedOutputStream.ComputeBytesSize(BytesValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.ReferenceValue) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ReferenceValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(GeoPointValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ArrayValue);
}
if (valueTypeCase_ == ValueTypeOneofCase.MapValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(MapValue);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Value other) {
if (other == null) {
return;
}
switch (other.ValueTypeCase) {
case ValueTypeOneofCase.NullValue:
NullValue = other.NullValue;
break;
case ValueTypeOneofCase.BooleanValue:
BooleanValue = other.BooleanValue;
break;
case ValueTypeOneofCase.IntegerValue:
IntegerValue = other.IntegerValue;
break;
case ValueTypeOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueTypeOneofCase.TimestampValue:
TimestampValue = other.TimestampValue;
break;
case ValueTypeOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueTypeOneofCase.BytesValue:
BytesValue = other.BytesValue;
break;
case ValueTypeOneofCase.ReferenceValue:
ReferenceValue = other.ReferenceValue;
break;
case ValueTypeOneofCase.GeoPointValue:
GeoPointValue = other.GeoPointValue;
break;
case ValueTypeOneofCase.ArrayValue:
ArrayValue = other.ArrayValue;
break;
case ValueTypeOneofCase.MapValue:
MapValue = other.MapValue;
break;
}
}
[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: {
BooleanValue = input.ReadBool();
break;
}
case 16: {
IntegerValue = input.ReadInt64();
break;
}
case 25: {
DoubleValue = input.ReadDouble();
break;
}
case 42: {
ReferenceValue = input.ReadString();
break;
}
case 50: {
global::Google.Cloud.Firestore.V1Beta1.MapValue subBuilder = new global::Google.Cloud.Firestore.V1Beta1.MapValue();
if (valueTypeCase_ == ValueTypeOneofCase.MapValue) {
subBuilder.MergeFrom(MapValue);
}
input.ReadMessage(subBuilder);
MapValue = subBuilder;
break;
}
case 66: {
global::Google.Type.LatLng subBuilder = new global::Google.Type.LatLng();
if (valueTypeCase_ == ValueTypeOneofCase.GeoPointValue) {
subBuilder.MergeFrom(GeoPointValue);
}
input.ReadMessage(subBuilder);
GeoPointValue = subBuilder;
break;
}
case 74: {
global::Google.Cloud.Firestore.V1Beta1.ArrayValue subBuilder = new global::Google.Cloud.Firestore.V1Beta1.ArrayValue();
if (valueTypeCase_ == ValueTypeOneofCase.ArrayValue) {
subBuilder.MergeFrom(ArrayValue);
}
input.ReadMessage(subBuilder);
ArrayValue = subBuilder;
break;
}
case 82: {
global::Google.Protobuf.WellKnownTypes.Timestamp subBuilder = new global::Google.Protobuf.WellKnownTypes.Timestamp();
if (valueTypeCase_ == ValueTypeOneofCase.TimestampValue) {
subBuilder.MergeFrom(TimestampValue);
}
input.ReadMessage(subBuilder);
TimestampValue = subBuilder;
break;
}
case 88: {
valueType_ = input.ReadEnum();
valueTypeCase_ = ValueTypeOneofCase.NullValue;
break;
}
case 138: {
StringValue = input.ReadString();
break;
}
case 146: {
BytesValue = input.ReadBytes();
break;
}
}
}
}
}
/// <summary>
/// An array value.
/// </summary>
public sealed partial class ArrayValue : pb::IMessage<ArrayValue> {
private static readonly pb::MessageParser<ArrayValue> _parser = new pb::MessageParser<ArrayValue>(() => new ArrayValue());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ArrayValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.DocumentReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue(ArrayValue other) : this() {
values_ = other.values_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ArrayValue Clone() {
return new ArrayValue(this);
}
/// <summary>Field number for the "values" field.</summary>
public const int ValuesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Firestore.V1Beta1.Value> _repeated_values_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Firestore.V1Beta1.Value.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Firestore.V1Beta1.Value> values_ = new pbc::RepeatedField<global::Google.Cloud.Firestore.V1Beta1.Value>();
/// <summary>
/// Values in the array.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Firestore.V1Beta1.Value> Values {
get { return values_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ArrayValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ArrayValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!values_.Equals(other.values_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= values_.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) {
values_.WriteTo(output, _repeated_values_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += values_.CalculateSize(_repeated_values_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ArrayValue other) {
if (other == null) {
return;
}
values_.Add(other.values_);
}
[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: {
values_.AddEntriesFrom(input, _repeated_values_codec);
break;
}
}
}
}
}
/// <summary>
/// A map value.
/// </summary>
public sealed partial class MapValue : pb::IMessage<MapValue> {
private static readonly pb::MessageParser<MapValue> _parser = new pb::MessageParser<MapValue>(() => new MapValue());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MapValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Firestore.V1Beta1.DocumentReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MapValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MapValue(MapValue other) : this() {
fields_ = other.fields_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MapValue Clone() {
return new MapValue(this);
}
/// <summary>Field number for the "fields" field.</summary>
public const int FieldsFieldNumber = 1;
private static readonly pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value>.Codec _map_fields_codec
= new pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Cloud.Firestore.V1Beta1.Value.Parser), 10);
private readonly pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value> fields_ = new pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value>();
/// <summary>
/// The map's fields.
///
/// The map keys represent field names. Field names matching the regular
/// expression `__.*__` are reserved. Reserved field names are forbidden except
/// in certain documented contexts. The map keys, represented as UTF-8, must
/// not exceed 1,500 bytes and cannot be empty.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, global::Google.Cloud.Firestore.V1Beta1.Value> Fields {
get { return fields_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MapValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MapValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Fields.Equals(other.Fields)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= Fields.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) {
fields_.WriteTo(output, _map_fields_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += fields_.CalculateSize(_map_fields_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MapValue other) {
if (other == null) {
return;
}
fields_.Add(other.fields_);
}
[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: {
fields_.AddEntriesFrom(input, _map_fields_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections;
using System.Data;
using PCSComMaterials.Inventory.DS;
using PCSComUtils.Common;
using PCSComUtils.PCSExc;
using System.Transactions;
using PCSComUtils.DataContext;
using PCSComUtils.DataAccess;
using System.Linq;
namespace PCSComMaterials.Inventory.BO
{
public class IVMiscellaneousIssueBO
{
private const string This = "PCSComMaterials.Inventory.BO.IVMiscellaneousIssueBO";
/// <summary>
/// Adds the and return id.
/// </summary>
/// <param name="pobjMaster">The pobj master.</param>
/// <param name="pdstData">The PDST data.</param>
/// <param name="serverDate">The server date.</param>
/// <returns></returns>
public int AddAndReturnId(object pobjMaster, DataSet pdstData, DateTime serverDate)
{
const string methodName = This + ".AddAndReturnId()";
try
{
using (var trans = new TransactionScope())
{
using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
{
var miscTranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.IVMiscellaneousIssue.ToString()).TranTypeID;
#region IV_MiscellaneousIssueMaster
var issueMaster = new IV_MiscellaneousIssueMaster();
var pobjMasterVO = (IV_MiscellaneousIssueMasterVO)pobjMaster;
issueMaster.CCNID = pobjMasterVO.CCNID;
issueMaster.Comment = pobjMasterVO.Comment;
if (pobjMasterVO.DesBinID > 0)
{
issueMaster.DesBinID = pobjMasterVO.DesBinID;
}
if (pobjMasterVO.DesLocationID > 0)
{
issueMaster.DesLocationID = pobjMasterVO.DesLocationID;
}
if (pobjMasterVO.DesMasLocationID > 0)
{
issueMaster.DesMasLocationID = pobjMasterVO.DesMasLocationID;
}
issueMaster.IssuePurposeID = pobjMasterVO.IssuePurposeID;
issueMaster.PartyID = null;
issueMaster.PostDate = pobjMasterVO.PostDate;
issueMaster.SourceBinID = pobjMasterVO.SourceBinID;
issueMaster.SourceLocationID = pobjMasterVO.SourceLocationID;
issueMaster.SourceMasLocationID = pobjMasterVO.SourceMasLocationID;
issueMaster.TransNo = pobjMasterVO.TransNo;
issueMaster.UserName = SystemProperty.UserName;
issueMaster.LastChange = serverDate;
#endregion
#region Insert IV_MiscellaneousIssueDetail
foreach (DataRow dr in pdstData.Tables[0].Rows)
{
if (dr.RowState == DataRowState.Deleted)
continue;
var objDetail = new IV_MiscellaneousIssueDetail
{
ProductID = Convert.ToInt32(dr[IV_MiscellaneousIssueDetailTable.PRODUCTID_FLD]),
Quantity = Convert.ToDecimal(dr[IV_MiscellaneousIssueDetailTable.QUANTITY_FLD]),
StockUMID = Convert.ToInt32(dr[IV_MiscellaneousIssueDetailTable.STOCKUMID_FLD])
};
if (dr[IV_MiscellaneousIssueDetailTable.LOT_FLD] != DBNull.Value)
{
objDetail.Lot = dr[IV_MiscellaneousIssueDetailTable.LOT_FLD].ToString();
}
if (dr[IV_MiscellaneousIssueDetailTable.AVAILABLEQTY_FLD] != DBNull.Value)
{
objDetail.AvailableQty = Convert.ToDecimal(dr[IV_MiscellaneousIssueDetailTable.AVAILABLEQTY_FLD]);
}
issueMaster.IV_MiscellaneousIssueDetails.Add(objDetail);
}
// temporary save master and detail to database
db.IV_MiscellaneousIssueMasters.InsertOnSubmit(issueMaster);
db.SubmitChanges();
#endregion
#region cache data
foreach (var issueDetail in issueMaster.IV_MiscellaneousIssueDetails)
{
var allowNegative = issueDetail.ITM_Product.AllowNegativeQty.GetValueOrDefault(false);
#region subtract from source cache
#region bin cache
var sourceBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueMaster.SourceLocationID && e.BinID == issueMaster.SourceBinID && e.ProductID == issueDetail.ProductID);
if (!allowNegative && (sourceBin == null || sourceBin.OHQuantity.GetValueOrDefault(0) < issueDetail.Quantity))
{
var productError = new Hashtable
{
{ ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
{ IV_BinCacheTable.OHQUANTITY_FLD, sourceBin == null ? 0 : sourceBin.OHQuantity.GetValueOrDefault(0) }
};
throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
}
if (sourceBin != null)
{
sourceBin.OHQuantity = sourceBin.OHQuantity.GetValueOrDefault(0) - issueDetail.Quantity;
}
else
{
// create new record
sourceBin = new IV_BinCache
{
BinID = issueMaster.SourceBinID.GetValueOrDefault(0),
CCNID = issueMaster.CCNID,
LocationID = issueMaster.SourceLocationID,
MasterLocationID = issueMaster.SourceMasLocationID,
ProductID = issueDetail.ProductID,
OHQuantity = -issueDetail.Quantity
};
db.IV_BinCaches.InsertOnSubmit(sourceBin);
}
#endregion
#region location cache
var sourceLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.SourceMasLocationID && e.LocationID == issueMaster.SourceLocationID && e.ProductID == issueDetail.ProductID);
if (!allowNegative && (sourceLocation == null || sourceLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.Quantity))
{
var productError = new Hashtable
{
{ ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
{ IV_BinCacheTable.OHQUANTITY_FLD, sourceLocation == null ? 0 : sourceLocation.OHQuantity.GetValueOrDefault(0) }
};
throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
}
if (sourceLocation != null)
{
sourceLocation.OHQuantity = sourceLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.Quantity;
}
else
{
// create new record
sourceLocation = new IV_LocationCache
{
CCNID = issueMaster.CCNID,
LocationID = issueMaster.SourceLocationID,
MasterLocationID = issueMaster.SourceMasLocationID,
ProductID = issueDetail.ProductID,
OHQuantity = -issueDetail.Quantity
};
db.IV_LocationCaches.InsertOnSubmit(sourceLocation);
}
#endregion
#region master location cache
var sourceMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.SourceMasLocationID && e.ProductID == issueDetail.ProductID);
if (!allowNegative && (sourceMasLocation == null || sourceMasLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.Quantity))
{
var productError = new Hashtable
{
{ ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
{ IV_BinCacheTable.OHQUANTITY_FLD, sourceMasLocation == null ? 0 : sourceMasLocation.OHQuantity.GetValueOrDefault(0) }
};
throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
}
if (sourceMasLocation != null)
{
sourceMasLocation.OHQuantity = sourceMasLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.Quantity;
}
else
{
// create new record
sourceMasLocation = new IV_MasLocCache
{
CCNID = issueMaster.CCNID,
MasterLocationID = issueMaster.SourceMasLocationID,
ProductID = issueDetail.ProductID,
OHQuantity = -issueDetail.Quantity
};
db.IV_MasLocCaches.InsertOnSubmit(sourceMasLocation);
}
#endregion
#region Transaction history
var sourceHistory = new MST_TransactionHistory
{
CCNID = pobjMasterVO.CCNID,
StockUMID = issueDetail.StockUMID,
MasterLocationID = pobjMasterVO.SourceMasLocationID,
ProductID = issueDetail.ProductID,
LocationID = pobjMasterVO.SourceLocationID,
BinID = pobjMasterVO.SourceBinID,
RefMasterID = issueMaster.MiscellaneousIssueMasterID,
RefDetailID = issueDetail.MiscellaneousIssueDetailID,
PostDate = pobjMasterVO.PostDate,
TransDate = serverDate,
Quantity = -issueDetail.Quantity,
UserName = SystemProperty.UserName,
TranTypeID = miscTranTypeId,
BinCommitQuantity = sourceBin.CommitQuantity,
BinOHQuantity = sourceBin.OHQuantity,
IssuePurposeID = issueMaster.IssuePurposeID,
LocationCommitQuantity = sourceLocation.CommitQuantity,
LocationOHQuantity = sourceLocation.OHQuantity,
MasLocCommitQuantity = sourceMasLocation.CommitQuantity,
MasLocOHQuantity = sourceMasLocation.OHQuantity
};
db.MST_TransactionHistories.InsertOnSubmit(sourceHistory);
#endregion
#endregion
#region add to destination cache
if (issueMaster.DesMasLocationID.GetValueOrDefault(0) > 0)
{
#region bin cache
var destBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueMaster.DesLocationID && e.BinID == issueMaster.DesBinID && e.ProductID == issueDetail.ProductID);
if (destBin != null)
{
destBin.OHQuantity = destBin.OHQuantity.GetValueOrDefault(0) + issueDetail.Quantity;
}
else
{
// create new record
destBin = new IV_BinCache
{
BinID = issueMaster.DesBinID.GetValueOrDefault(0),
CCNID = issueMaster.CCNID,
LocationID = issueMaster.DesLocationID.GetValueOrDefault(0),
MasterLocationID = issueMaster.DesMasLocationID.GetValueOrDefault(0),
ProductID = issueDetail.ProductID,
OHQuantity = issueDetail.Quantity
};
db.IV_BinCaches.InsertOnSubmit(destBin);
}
#endregion
#region location cache
var destLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.DesMasLocationID && e.LocationID == issueMaster.DesLocationID && e.ProductID == issueDetail.ProductID);
if (destLocation != null)
{
destLocation.OHQuantity = destLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.Quantity;
}
else
{
// create new record
destLocation = new IV_LocationCache
{
CCNID = issueMaster.CCNID,
LocationID = issueMaster.DesLocationID.GetValueOrDefault(0),
MasterLocationID = issueMaster.DesMasLocationID.GetValueOrDefault(0),
ProductID = issueDetail.ProductID,
OHQuantity = issueDetail.Quantity
};
db.IV_LocationCaches.InsertOnSubmit(destLocation);
}
#endregion
#region master location cache
var destMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.DesMasLocationID && e.ProductID == issueDetail.ProductID);
if (destMasLocation != null)
{
destMasLocation.OHQuantity = destMasLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.Quantity;
}
else
{
// create new record
destMasLocation = new IV_MasLocCache
{
CCNID = issueMaster.CCNID,
MasterLocationID = issueMaster.DesMasLocationID.GetValueOrDefault(0),
ProductID = issueDetail.ProductID,
OHQuantity = issueDetail.Quantity
};
db.IV_MasLocCaches.InsertOnSubmit(destMasLocation);
}
#endregion
#region Transaction history
var destHistory = new MST_TransactionHistory
{
CCNID = pobjMasterVO.CCNID,
StockUMID = issueDetail.StockUMID,
MasterLocationID = pobjMasterVO.DesMasLocationID,
ProductID = issueDetail.ProductID,
LocationID = pobjMasterVO.DesLocationID,
BinID = pobjMasterVO.DesBinID,
RefMasterID = issueMaster.MiscellaneousIssueMasterID,
RefDetailID = issueDetail.MiscellaneousIssueDetailID,
PostDate = pobjMasterVO.PostDate,
TransDate = serverDate,
Quantity = issueDetail.Quantity,
UserName = SystemProperty.UserName,
TranTypeID = miscTranTypeId,
BinCommitQuantity = destBin.CommitQuantity,
BinOHQuantity = destBin.OHQuantity,
IssuePurposeID = issueMaster.IssuePurposeID,
LocationCommitQuantity = destLocation.CommitQuantity,
LocationOHQuantity = destLocation.OHQuantity,
MasLocCommitQuantity = destMasLocation.CommitQuantity,
MasLocOHQuantity = destMasLocation.OHQuantity
};
db.MST_TransactionHistories.InsertOnSubmit(destHistory);
#endregion
}
#endregion
}
#endregion
db.SubmitChanges();
trans.Complete();
return issueMaster.MiscellaneousIssueMasterID;
}
}
}
catch (PCSBOException ex)
{
if (ex.mCode == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, methodName, ex);
if (ex.mCode == ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE)
throw;
throw new PCSDBException(ErrorCode.ERROR_DB, methodName, ex);
}
}
/// <summary>
/// Get all LocToLoc detail by MasterID
/// </summary>
/// <param name="pintcMasterId"></param>
/// <returns></returns>
public DataSet GetMiscellaneousByMaster(int pintcMasterId)
{
return new IV_MiscellaneousIssueDetailDS().GetMiscellaneousDetailByMaster(pintcMasterId);
}
/// <summary>
/// Get LocToLoc Master infor by ID
/// </summary>
/// <param name="pintMasterId"></param>
/// <returns></returns>
public DataRow GetMiscellaneousMasterInfor(int pintMasterId)
{
return new IV_MiscellaneousIssueMasterDS().GetMiscellaneousMasterInfor(pintMasterId);
}
/// <summary>
/// Deletes the transaction.
/// </summary>
/// <param name="miscIssueMasterId">The misc issue master id.</param>
public void DeleteTransaction(int miscIssueMasterId)
{
const string methodName = This + ".DeleteTransaction()";
try
{
using (var trans = new TransactionScope())
{
using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
{
var miscTranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.IVMiscellaneousIssue.ToString()).TranTypeID;
var deleteTranTypeId = db.MST_TranTypes.FirstOrDefault(t => t.Code == TransactionTypeEnum.DeleteTransaction.ToString()).TranTypeID;
var serverDate = db.GetServerDate();
#region IV_MiscellaneousIssueMaster
var issueMaster = db.IV_MiscellaneousIssueMasters.FirstOrDefault(e => e.MiscellaneousIssueMasterID == miscIssueMasterId);
if (issueMaster == null)
return;
#endregion
#region old transaction history to be updated
var oldSourceHistory = db.MST_TransactionHistories.Where(e => e.RefMasterID == miscIssueMasterId && e.TranTypeID == miscTranTypeId);
foreach (var history in oldSourceHistory)
{
// mark as delete transaction
history.TranTypeID = deleteTranTypeId;
history.UserName = SystemProperty.UserName;
}
#endregion
#region cache data
foreach (IV_MiscellaneousIssueDetail issueDetail in issueMaster.IV_MiscellaneousIssueDetails)
{
var allowNegative = issueDetail.ITM_Product.AllowNegativeQty.GetValueOrDefault(false);
#region subtract from destionation cache
if (issueMaster.DesMasLocationID.GetValueOrDefault(0) > 0)
{
#region bin cache
var destBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueMaster.DesLocationID && e.BinID == issueMaster.DesBinID && e.ProductID == issueDetail.ProductID);
if (!allowNegative && (destBin == null || destBin.OHQuantity.GetValueOrDefault(0) < issueDetail.Quantity))
{
var productError = new Hashtable
{
{ ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
{ IV_BinCacheTable.OHQUANTITY_FLD, destBin == null ? 0 : destBin.OHQuantity.GetValueOrDefault(0) }
};
throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
}
if (destBin != null)
{
destBin.OHQuantity = destBin.OHQuantity.GetValueOrDefault(0) - issueDetail.Quantity;
}
else
{
// create new record
destBin = new IV_BinCache
{
BinID = issueMaster.DesBinID.GetValueOrDefault(0),
CCNID = issueMaster.CCNID,
LocationID = issueMaster.DesLocationID.GetValueOrDefault(0),
MasterLocationID = issueMaster.DesMasLocationID.GetValueOrDefault(0),
ProductID = issueDetail.ProductID,
OHQuantity = -issueDetail.Quantity
};
db.IV_BinCaches.InsertOnSubmit(destBin);
}
#endregion
#region location cache
var destLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.DesMasLocationID && e.LocationID == issueMaster.DesLocationID && e.ProductID == issueDetail.ProductID);
if (!allowNegative && (destLocation == null || destLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.Quantity))
{
var productError = new Hashtable
{
{ ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
{ IV_BinCacheTable.OHQUANTITY_FLD, destLocation == null ? 0 : destLocation.OHQuantity.GetValueOrDefault(0) }
};
throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
}
if (destLocation != null)
{
destLocation.OHQuantity = destLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.Quantity;
}
else
{
// create new record
destLocation = new IV_LocationCache
{
CCNID = issueMaster.CCNID,
LocationID = issueMaster.DesLocationID.GetValueOrDefault(0),
MasterLocationID = issueMaster.DesMasLocationID.GetValueOrDefault(0),
ProductID = issueDetail.ProductID,
OHQuantity = -issueDetail.Quantity
};
db.IV_LocationCaches.InsertOnSubmit(destLocation);
}
#endregion
#region master location cache
var destMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.DesMasLocationID && e.ProductID == issueDetail.ProductID);
if (!allowNegative && (destMasLocation == null || destMasLocation.OHQuantity.GetValueOrDefault(0) < issueDetail.Quantity))
{
var productError = new Hashtable
{
{ ITM_ProductTable.PRODUCTID_FLD, issueDetail.ProductID },
{ IV_BinCacheTable.OHQUANTITY_FLD, destMasLocation == null ? 0 : destMasLocation.OHQuantity.GetValueOrDefault(0) }
};
throw new PCSBOException(ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE, issueDetail.ITM_Product.Code, new Exception(), productError);
}
if (destMasLocation != null)
{
destMasLocation.OHQuantity = destMasLocation.OHQuantity.GetValueOrDefault(0) - issueDetail.Quantity;
}
else
{
// create new record
destMasLocation = new IV_MasLocCache
{
CCNID = issueMaster.CCNID,
MasterLocationID = issueMaster.DesMasLocationID.GetValueOrDefault(0),
ProductID = issueDetail.ProductID,
OHQuantity = -issueDetail.Quantity
};
db.IV_MasLocCaches.InsertOnSubmit(destMasLocation);
}
#endregion
#region Transaction history
var destHistory = new MST_TransactionHistory
{
CCNID = issueMaster.CCNID,
StockUMID = issueDetail.StockUMID,
MasterLocationID = issueMaster.DesMasLocationID.GetValueOrDefault(0),
ProductID = issueDetail.ProductID,
LocationID = issueMaster.DesLocationID,
BinID = issueMaster.DesBinID,
RefMasterID = issueMaster.MiscellaneousIssueMasterID,
RefDetailID = issueDetail.MiscellaneousIssueDetailID,
PostDate = issueMaster.PostDate,
TransDate = serverDate,
Quantity = -issueDetail.Quantity,
UserName = SystemProperty.UserName,
TranTypeID = miscTranTypeId,
BinCommitQuantity = destBin.CommitQuantity,
BinOHQuantity = destBin.OHQuantity,
IssuePurposeID = issueMaster.IssuePurposeID,
LocationCommitQuantity = destLocation.CommitQuantity,
LocationOHQuantity = destLocation.OHQuantity,
MasLocCommitQuantity = destMasLocation.CommitQuantity,
MasLocOHQuantity = destMasLocation.OHQuantity
};
db.MST_TransactionHistories.InsertOnSubmit(destHistory);
#endregion
}
#endregion
#region add to source cache
#region bin cache
var sourceBin = db.IV_BinCaches.FirstOrDefault(e => e.LocationID == issueMaster.SourceLocationID && e.BinID == issueMaster.SourceBinID && e.ProductID == issueDetail.ProductID);
if (sourceBin != null)
{
sourceBin.OHQuantity = sourceBin.OHQuantity.GetValueOrDefault(0) + issueDetail.Quantity;
}
else
{
// create new record
sourceBin = new IV_BinCache
{
BinID = issueMaster.SourceBinID.GetValueOrDefault(0),
CCNID = issueMaster.CCNID,
LocationID = issueMaster.SourceLocationID,
MasterLocationID = issueMaster.SourceMasLocationID,
ProductID = issueDetail.ProductID,
OHQuantity = issueDetail.Quantity
};
db.IV_BinCaches.InsertOnSubmit(sourceBin);
}
#endregion
#region location cache
var sourceLocation = db.IV_LocationCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.SourceMasLocationID && e.LocationID == issueMaster.SourceLocationID && e.ProductID == issueDetail.ProductID);
if (sourceLocation != null)
{
sourceLocation.OHQuantity = sourceLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.Quantity;
}
else
{
// create new record
sourceLocation = new IV_LocationCache
{
CCNID = issueMaster.CCNID,
LocationID = issueMaster.SourceLocationID,
MasterLocationID = issueMaster.SourceMasLocationID,
ProductID = issueDetail.ProductID,
OHQuantity = issueDetail.Quantity
};
db.IV_LocationCaches.InsertOnSubmit(sourceLocation);
}
#endregion
#region master location cache
var sourceMasLocation = db.IV_MasLocCaches.FirstOrDefault(e => e.MasterLocationID == issueMaster.SourceMasLocationID && e.ProductID == issueDetail.ProductID);
if (sourceMasLocation != null)
{
sourceMasLocation.OHQuantity = sourceMasLocation.OHQuantity.GetValueOrDefault(0) + issueDetail.Quantity;
}
else
{
// create new record
sourceMasLocation = new IV_MasLocCache
{
CCNID = issueMaster.CCNID,
MasterLocationID = issueMaster.SourceMasLocationID,
ProductID = issueDetail.ProductID,
OHQuantity = issueDetail.Quantity
};
db.IV_MasLocCaches.InsertOnSubmit(sourceMasLocation);
}
#endregion
#region Transaction history
var sourceHistory = new MST_TransactionHistory
{
CCNID = issueMaster.CCNID,
StockUMID = issueDetail.StockUMID,
MasterLocationID = issueMaster.SourceMasLocationID,
ProductID = issueDetail.ProductID,
LocationID = issueMaster.SourceLocationID,
BinID = issueMaster.SourceBinID,
RefMasterID = issueMaster.MiscellaneousIssueMasterID,
RefDetailID = issueDetail.MiscellaneousIssueDetailID,
PostDate = issueMaster.PostDate,
TransDate = serverDate,
Quantity = issueDetail.Quantity,
UserName = SystemProperty.UserName,
TranTypeID = miscTranTypeId,
BinCommitQuantity = sourceBin.CommitQuantity,
BinOHQuantity = sourceBin.OHQuantity,
IssuePurposeID = issueMaster.IssuePurposeID,
LocationCommitQuantity = sourceLocation.CommitQuantity,
LocationOHQuantity = sourceLocation.OHQuantity,
MasLocCommitQuantity = sourceMasLocation.CommitQuantity,
MasLocOHQuantity = sourceMasLocation.OHQuantity
};
db.MST_TransactionHistories.InsertOnSubmit(sourceHistory);
#endregion
#endregion
db.IV_MiscellaneousIssueDetails.DeleteOnSubmit(issueDetail);
}
#endregion
db.IV_MiscellaneousIssueMasters.DeleteOnSubmit(issueMaster);
db.SubmitChanges();
trans.Complete();
}
}
}
catch (PCSBOException ex)
{
if (ex.mCode == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, methodName, ex);
if (ex.mCode == ErrorCode.MESSAGE_NOT_ENOUGH_COMPONENT_TO_COMPLETE)
throw;
throw new PCSDBException(ErrorCode.ERROR_DB, methodName, ex);
}
}
}
}
| |
// <copyright file="ChromiumDriverService.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.Globalization;
using System.Text;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Chromium
{
/// <summary>
/// Exposes the service provided by the native ChromiumDriver executable.
/// </summary>
public abstract class ChromiumDriverService : DriverService
{
private const string DefaultChromeDriverServiceExecutableName = "chromedriver";
private string logPath = string.Empty;
private string urlPathPrefix = string.Empty;
private string portServerAddress = string.Empty;
private string whitelistedIpAddresses = string.Empty;
private int adbPort = -1;
private bool enableVerboseLogging;
private bool enableAppendLog;
/// <summary>
/// Initializes a new instance of the <see cref="ChromiumDriverService"/> class.
/// </summary>
/// <param name="executablePath">The full path to the ChromeDriver executable.</param>
/// <param name="executableFileName">The file name of the ChromeDriver executable.</param>
/// <param name="port">The port on which the ChromeDriver executable should listen.</param>
/// <param name="downloadUrl">The url that ChromiumDriver should be downloaded from.</param>
protected ChromiumDriverService(string executablePath, string executableFileName, int port, Uri downloadUrl)
: base(executablePath, port, executableFileName, downloadUrl)
{
}
/// <summary>
/// Gets or sets the location of the log file written to by the ChromeDriver executable.
/// </summary>
public string LogPath
{
get { return this.logPath; }
set { this.logPath = value; }
}
/// <summary>
/// Gets or sets the base URL path prefix for commands (e.g., "wd/url").
/// </summary>
public string UrlPathPrefix
{
get { return this.urlPathPrefix; }
set { this.urlPathPrefix = value; }
}
/// <summary>
/// Gets or sets the address of a server to contact for reserving a port.
/// </summary>
public string PortServerAddress
{
get { return this.portServerAddress; }
set { this.portServerAddress = value; }
}
/// <summary>
/// Gets or sets the port on which the Android Debug Bridge is listening for commands.
/// </summary>
public int AndroidDebugBridgePort
{
get { return this.adbPort; }
set { this.adbPort = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to enable verbose logging for the ChromeDriver executable.
/// Defaults to <see langword="false"/>.
/// </summary>
public bool EnableVerboseLogging
{
get { return this.enableVerboseLogging; }
set { this.enableVerboseLogging = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to enable appending to an existing ChromeDriver log file.
/// Defaults to <see langword="false"/>.
/// </summary>
public bool EnableAppendLog
{
get { return this.enableAppendLog; }
set { this.enableAppendLog = value; }
}
/// <summary>
/// Gets or sets the comma-delimited list of IP addresses that are approved to
/// connect to this instance of the Chrome driver. Defaults to an empty string,
/// which means only the local loopback address can connect.
/// </summary>
public string WhitelistedIPAddresses
{
get { return this.whitelistedIpAddresses; }
set { this.whitelistedIpAddresses = value; }
}
/// <summary>
/// Gets the command-line arguments for the driver service.
/// </summary>
protected override string CommandLineArguments
{
get
{
StringBuilder argsBuilder = new StringBuilder(base.CommandLineArguments);
if (this.adbPort > 0)
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --adb-port={0}", this.adbPort);
}
if (this.SuppressInitialDiagnosticInformation)
{
argsBuilder.Append(" --silent");
}
if (this.enableVerboseLogging)
{
argsBuilder.Append(" --verbose");
}
if (this.enableAppendLog)
{
argsBuilder.Append(" --append-log");
}
if (!string.IsNullOrEmpty(this.logPath))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --log-path=\"{0}\"", this.logPath);
}
if (!string.IsNullOrEmpty(this.urlPathPrefix))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --url-base={0}", this.urlPathPrefix);
}
if (!string.IsNullOrEmpty(this.portServerAddress))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --port-server={0}", this.portServerAddress);
}
if (!string.IsNullOrEmpty(this.whitelistedIpAddresses))
{
argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " -whitelisted-ips={0}", this.whitelistedIpAddresses));
}
return argsBuilder.ToString();
}
}
/// <summary>
/// Returns the Chromium driver filename for the currently running platform
/// </summary>
/// <param name="fileName">The name of the Chromium executable. Default is "chromedriver".</param>
/// <returns>The file name of the Chromium driver service executable.</returns>
protected static string ChromiumDriverServiceFileName(string fileName = DefaultChromeDriverServiceExecutableName)
{
// Unfortunately, detecting the currently running platform isn't as
// straightforward as you might hope.
// See: http://mono.wikia.com/wiki/Detecting_the_execution_platform
// and https://msdn.microsoft.com/en-us/library/3a8hyw88(v=vs.110).aspx
const int PlatformMonoUnixValue = 128;
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
case PlatformID.Win32S:
case PlatformID.Win32Windows:
case PlatformID.WinCE:
fileName += ".exe";
break;
case PlatformID.MacOSX:
case PlatformID.Unix:
break;
// Don't handle the Xbox case. Let default handle it.
// case PlatformID.Xbox:
// break;
default:
if ((int)Environment.OSVersion.Platform == PlatformMonoUnixValue)
{
break;
}
throw new WebDriverException("Unsupported platform: " + Environment.OSVersion.Platform);
}
return fileName;
}
}
}
| |
namespace Kafka.Client.Utils
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Kafka.Client.Clusters;
using Kafka.Client.Consumers;
using Kafka.Client.Extensions;
using Kafka.Client.ZKClient;
using Kafka.Client.ZKClient.Exceptions;
using Kafka.Client.ZKClient.Serialize;
using Spring.Threading.Locks;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.Apache.Zookeeper.Data;
public static class ZkUtils
{
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const string ConsumersPath = "/consumers";
public const string BrokerIdsPath = "/brokers/ids";
public const string BrokerTopicsPath = "/brokers/topics";
public const string TopicConfigPath = "/config/topics";
public const string TopicConfigChangesPath = "/config/changes";
public const string ControllerPath = "/controller";
public const string ControllerEpochPath = "/controller_epoch";
public const string ReassignPartitionsPath = "/admin/reassign_partitions";
public const string DeleteTopicsPath = "/admin/delete_topics";
public const string PreferredReplicaLeaderElectionPath = "/admin/preferred_replica_election";
public static string GetTopicPath(string topic)
{
return BrokerTopicsPath + "/" + topic;
}
public static string GetTopicPartitionsPath(string topic)
{
return GetTopicPath(topic) + "/partitions";
}
public static string GetTopicConfigPath(string topic)
{
return TopicConfigPath + "/" + topic;
}
public static string GetDeleteTopicPath(string topic)
{
return DeleteTopicsPath + "/" + topic;
}
public static string GetTopicPartitionPath(string topic, int partitionId)
{
return GetTopicPartitionsPath(topic) + "/" + partitionId;
}
public static string GetTopicPartitionLeaderAndIsrPath(string topic, int partitionId)
{
return GetTopicPartitionPath(topic, partitionId) + "/" + "state";
}
public static List<int> GetSortedBrokerList(ZkClient zkClient)
{
return GetChildren(zkClient, BrokerIdsPath).Select(int.Parse).OrderBy(x => x).ToList();
}
public static List<Broker> GetAllBrokersInCluster(ZkClient zkClient)
{
var brokerIds = GetChildrenParentMayNotExist(zkClient, BrokerIdsPath).OrderBy(x => x).ToList();
return
brokerIds.Select(int.Parse)
.Select(id => GetBrokerInfo(zkClient, id))
.Where(x => x != null)
.ToList();
}
public static int? GetLeaderForPartition(ZkClient zkClient, string topic, int partition)
{
var leaderAndIsrOpt = ReadDataMaybeNull(zkClient, GetTopicPartitionLeaderAndIsrPath(topic, partition)).Item1;
if (leaderAndIsrOpt != null)
{
return JObject.Parse(leaderAndIsrOpt).SelectToken("leader").Value<int>();
}
return null;
}
public static string GetConsumerPartitionOwnerPath(string group, string topic, int partition)
{
var topicDirs = new ZKGroupTopicDirs(group, topic);
return topicDirs.ConsumerOwnerDir + "/" + partition;
}
/// <summary>
/// Get JSON partition to replica map from zookeeper.
/// </summary>
/// <param name="map"></param>
/// <returns></returns>
public static string ReplicaAssignmentZkData(Dictionary<string, List<int>> map)
{
return JObject.FromObject(new { version = 1, partitions = map }).ToString();
}
/// <summary>
/// make sure a persistent path exists in ZK. Create the path if not exist.
/// </summary>
/// <param name="client"></param>
/// <param name="path"></param>
public static void MakeSurePersistentPathExists(ZkClient client, string path)
{
if (!client.Exists(path))
{
client.CreatePersistent(path, true); // won't throw NoNodeException or NodeExistsException
}
}
/// <summary>
/// create the parent path
/// </summary>
/// <param name="client"></param>
/// <param name="path"></param>
private static void CreateParentPath(ZkClient client, string path)
{
var parentDir = path.Substring(0, path.LastIndexOf('/'));
if (parentDir.Length != 0)
{
client.CreatePersistent(parentDir, true);
}
}
/// <summary>
/// Create an ephemeral node with the given path and data. Create parents if necessary.
/// </summary>
/// <param name="client"></param>
/// <param name="path"></param>
/// <param name="data"></param>
private static void CreateEphemeralPath(ZkClient client, string path, string data)
{
try
{
client.CreateEphemeral(path, data);
}
catch (ZkNoNodeException)
{
CreateParentPath(client, path);
client.CreateEphemeral(path, data);
}
}
/// <summary>
/// Create an ephemeral node with the given path and data.
/// Throw NodeExistException if node already exists.
/// </summary>
/// <param name="client"></param>
/// <param name="path"></param>
/// <param name="data"></param>
public static void CreateEphemeralPathExpectConflict(ZkClient client, string path, string data)
{
try
{
CreateEphemeralPath(client, path, data);
}
catch (ZkNodeExistsException)
{
// this can happen when there is connection loss; make sure the Data is what we intend to write
string storedData = null;
try
{
storedData = ReadData(client, path).Item1;
}
catch (ZkNoNodeException)
{
// the node disappeared; treat as if node existed and let caller handles this
}
if (storedData == null || storedData != data)
{
Logger.InfoFormat("Conflict in {0} Data: {1}, stored Data: {2}", path, data, storedData);
throw;
}
else
{
// otherwise, the creation succeeded, return normally
Logger.InfoFormat("{0} exists with value {1} during connection loss", path, data);
}
}
}
/// <summary>
/// Create an ephemeral node with the given path and data.
/// Throw NodeExistsException if node already exists.
/// Handles the following ZK session timeout b_u_g
///
/// https://issues.apache.org/jira/browse/ZOOKEEPER-1740
///
/// Upon receiving a NodeExistsException, read the data from the conflicted path and
/// trigger the checker function comparing the read data and the expected data,
/// If the checker function returns true then the above b_u_g might be encountered, back off and retry;
/// otherwise re-throw the exception
/// </summary>
/// <param name="zkClient"></param>
/// <param name="path"></param>
/// <param name="data"></param>
/// <param name="expectedCallerData"></param>
/// <param name="checker"></param>
/// <param name="backoffTime"></param>
public static void CreateEphemeralPathExpectConflictHandleZKBug(
ZkClient zkClient,
string path,
string data,
object expectedCallerData,
Func<string, object, bool> checker,
int backoffTime)
{
while (true)
{
try
{
CreateEphemeralPathExpectConflict(zkClient, path, data);
return;
}
catch (ZkNodeExistsException)
{
// An ephemeral node may still exist even after its corresponding session has expired
// due to a Zookeeper ug, in this case we need to retry writing until the previous node is deleted
// and hence the write succeeds without ZkNodeExistsException
var writtenData = ReadDataMaybeNull(zkClient, path).Item1;
if (writtenData != null)
{
if (checker(writtenData, expectedCallerData))
{
Logger.InfoFormat(
"I wrote this conflicted ephemeral node [{0}] at {1} a while back in a different session, "
+ "hence I will backoff for this node to be deleted by Zookeeper and retry",
data,
path);
Thread.Sleep(backoffTime);
}
else
{
throw;
}
}
else
{
// the node disappeared; retry creating the ephemeral node immediately
}
}
}
}
/// <summary>
/// Create an persistent node with the given path and data. Create parents if necessary.
/// </summary>
public static void CreatePersistentPath(ZkClient client, string path, string data)
{
try
{
client.CreatePersistent(path, data);
}
catch (ZkNoNodeException e)
{
CreateParentPath(client, path);
client.CreatePersistent(path, data);
}
}
/// <summary>
/// Update the value of a persistent node with the given path and data.
/// create parrent directory if necessary. Never throw NodeExistException.
/// Return the updated path zkVersion
/// </summary>
/// <param name="client"></param>
/// <param name="path"></param>
/// <param name="data"></param>
public static void UpdatePersistentPath(ZkClient client, string path, string data)
{
try
{
client.WriteData(path, data);
}
catch (ZkNoNodeException)
{
CreateParentPath(client, path);
try
{
client.CreatePersistent(path, data);
}
catch (ZkNodeExistsException)
{
client.WriteData(path, data);
}
}
}
public static bool DeletePath(ZkClient client, string path)
{
try
{
return client.Delete(path);
}
catch (ZkNoNodeException)
{
// this can happen during a connection loss event, return normally
Logger.InfoFormat("{0} deleted during connection loss; This is ok. ", path);
return false;
}
}
public static void MaybeDeletePath(string zkUrl, string dir)
{
try
{
var zk = new ZkClient(zkUrl, 30 * 1000, 30 * 1000, new ZkStringSerializer());
zk.DeleteRecursive(dir);
zk.Dispose();
}
catch
{
// swallow
}
}
public static Tuple<string, Stat> ReadData(ZkClient client, string path)
{
var stat = new Stat();
var dataString = client.ReadData<string>(path, stat);
return Tuple.Create(dataString, stat);
}
public static Tuple<string, Stat> ReadDataMaybeNull(ZkClient client, string path)
{
var stat = new Stat();
try
{
var obj = client.ReadData<string>(path, stat);
return Tuple.Create(obj, stat);
}
catch (ZkNoNodeException)
{
return Tuple.Create((string)null, stat);
}
}
public static IEnumerable<string> GetChildren(ZkClient zkClient, string path)
{
return zkClient.GetChildren(path);
}
public static IEnumerable<string> GetChildrenParentMayNotExist(ZkClient client, string path)
{
try
{
return client.GetChildren(path);
}
catch (ZkNoNodeException)
{
return null;
}
}
public static bool PathExists(ZkClient client, string path)
{
return client.Exists(path);
}
public static Cluster GetCluster(ZkClient zkClient)
{
var cluster = new Cluster();
var nodes = GetChildrenParentMayNotExist(zkClient, BrokerIdsPath);
foreach (var node in nodes)
{
var brokerZkString = ReadData(zkClient, BrokerIdsPath + "/" + node).Item1;
cluster.Add(Broker.CreateBroker(int.Parse(node), brokerZkString));
}
return cluster;
}
public static IDictionary<string, IDictionary<int, List<int>>> GetPartitionAssignmentForTopics(
ZkClient zkClient, IList<string> topics)
{
IDictionary<string, IDictionary<int, List<int>>> ret = new Dictionary<string, IDictionary<int, List<int>>>();
foreach (var topic in topics)
{
var jsonPartitionMap = ReadDataMaybeNull(zkClient, GetTopicPath(topic)).Item1;
IDictionary<int, List<int>> partitionMap = new Dictionary<int, List<int>>();
if (jsonPartitionMap != null)
{
var m = JObject.Parse(jsonPartitionMap);
var replicaMap = (IDictionary<string, JToken>)m.Get("partitions");
if (replicaMap != null)
{
partitionMap = replicaMap.ToDictionary(
kvp => int.Parse(kvp.Key), kvp => kvp.Value.Values<int>().ToList());
}
}
Logger.DebugFormat("Partition map for /brokers/topics/{0} is {1}", topic, JObject.FromObject(partitionMap).ToString(Formatting.None));
ret[topic] = partitionMap;
}
return ret;
}
public static IDictionary<string, List<string>> GetConsumersPerTopic(ZkClient zkClient, string group)
{
var dirs = new ZKGroupDirs(group);
var consumers = GetChildrenParentMayNotExist(zkClient, dirs.ConsumerRegistryDir);
var consumerPerTopicMap = new Dictionary<string, List<string>>();
foreach (var consumer in consumers)
{
var topicCount = TopicCount.ConstructTopicCount(group, consumer, zkClient);
foreach (var topicAndConsumer in topicCount.GetConsumerThreadIdsPerTopic())
{
var topic = topicAndConsumer.Key;
var consumerThreadIdSet = topicAndConsumer.Value;
foreach (var consumerThreadId in consumerThreadIdSet)
{
var curConsumers = consumerPerTopicMap.Get(topic);
if (curConsumers != null)
{
curConsumers.Add(consumerThreadId);
}
else
{
consumerPerTopicMap[topic] = new List<string> { consumerThreadId };
}
}
}
}
consumerPerTopicMap = consumerPerTopicMap.ToDictionary(x => x.Key, x => x.Value.OrderBy(y => y).ToList());
return consumerPerTopicMap;
}
/// <summary>
/// This API takes in a broker id, queries zookeeper for the broker metadata and returns the metadata for that broker
/// or throws an exception if the broker dies before the query to zookeeper finishes
/// </summary>
/// <param name="zkClient">The zookeeper client connection</param>
/// <param name="brokerId">The broker id</param>
/// <returns>An optional Broker object encapsulating the broker metadata</returns>
public static Broker GetBrokerInfo(ZkClient zkClient, int brokerId)
{
var brokerInfo = ReadDataMaybeNull(zkClient, BrokerIdsPath + "/" + brokerId);
if (brokerInfo != null)
{
return Broker.CreateBroker(brokerId, brokerInfo.Item1);
}
else
{
return null;
}
}
}
internal class LeaderExistsOrChangedListener : IZkDataListener
{
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string topic;
private int partition;
private ReentrantLock leaderLock;
private ICondition leaderExistsOrChanged;
private int? oldLeaderOpt;
private ZkClient zkClient;
public LeaderExistsOrChangedListener(string topic, int partition, ReentrantLock leaderLock, ICondition leaderExistsOrChanged, int? oldLeaderOpt, ZkClient zkClient)
{
this.topic = topic;
this.partition = partition;
this.leaderLock = leaderLock;
this.leaderExistsOrChanged = leaderExistsOrChanged;
this.oldLeaderOpt = oldLeaderOpt;
this.zkClient = zkClient;
}
public void HandleDataChange(string dataPath, object data)
{
var dataPathSplited = dataPath.Split('/');
var t = dataPathSplited[dataPathSplited.Length - 4];
var p = int.Parse(dataPathSplited[dataPathSplited.Length - 2]);
this.leaderLock.Lock();
try
{
if (t == this.topic && p == this.partition)
{
if (this.oldLeaderOpt.HasValue == false)
{
Logger.DebugFormat(
"In leader existence listener on partition [{0}, {1}], leader has been created",
topic,
partition);
this.leaderExistsOrChanged.Signal();
}
else
{
var newLeaderOpt = ZkUtils.GetLeaderForPartition(this.zkClient, t, p);
if (newLeaderOpt.HasValue && newLeaderOpt.Value != this.oldLeaderOpt.Value)
{
Logger.DebugFormat("In leader change listener on partition [{0}, {1}], leader has been moved from {2} to {3}", topic, partition, oldLeaderOpt.Value, newLeaderOpt.Value);
this.leaderExistsOrChanged.Signal();
}
}
}
}
finally
{
this.leaderLock.Unlock();
}
}
public void HandleDataDeleted(string dataPath)
{
leaderLock.Lock();
try
{
leaderExistsOrChanged.Signal();
}
finally
{
leaderLock.Unlock();
}
}
}
public class ZkStringSerializer : IZkSerializer
{
public byte[] Serialize(object data)
{
return Encoding.UTF8.GetBytes(data.ToString());
}
public object Deserialize(byte[] bytes)
{
if (bytes == null)
{
return null;
}
return Encoding.UTF8.GetString(bytes);
}
}
public class ZKGroupDirs
{
public string Group { get; set; }
public ZKGroupDirs(string @group)
{
this.Group = @group;
}
public string ConsumerDir
{
get
{
return ZkUtils.ConsumersPath;
}
}
public string ConsumerGroupDir
{
get
{
return this.ConsumerDir + "/" + this.Group;
}
}
public string ConsumerRegistryDir
{
get
{
return this.ConsumerGroupDir + "/ids";
}
}
}
public class ZKGroupTopicDirs : ZKGroupDirs
{
public string Topic { get; private set; }
public ZKGroupTopicDirs(string @group, string topic)
: base(@group)
{
this.Topic = topic;
}
public string ConsumerOffsetDir
{
get
{
return this.ConsumerGroupDir + "/offsets/" + this.Topic;
}
}
public string ConsumerOwnerDir
{
get
{
return this.ConsumerGroupDir + "/owners/" + this.Topic;
}
}
}
public class ZkConfig
{
public const int DefaultSessionTimeout = 6000;
public const int DefaultConnectionTimeout = 6000;
public const int DefaultSyncTime = 2000;
public ZkConfig()
: this(null, DefaultSessionTimeout, DefaultConnectionTimeout, DefaultSyncTime)
{
}
public ZkConfig(string zkconnect, int zksessionTimeoutMs, int zkconnectionTimeoutMs, int zksyncTimeMs)
{
this.ZkConnect = zkconnect;
this.ZkConnectionTimeoutMs = zkconnectionTimeoutMs;
this.ZkSessionTimeoutMs = zksessionTimeoutMs;
this.ZkSyncTimeMs = zksyncTimeMs;
}
public string ZkConnect { get; set; }
public int ZkSessionTimeoutMs { get; set; }
public int ZkConnectionTimeoutMs { get; set; }
public int ZkSyncTimeMs { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if FEATURE_APPX
using Internal.Resources;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text; // For UriEncode
using Windows.ApplicationModel.Resources.Core;
using Windows.ApplicationModel;
using Windows.Foundation.Collections;
using Windows.Storage;
namespace System.Resources
{
#if FEATURE_APPX
// Please see the comments regarding thread safety preceding the implementations
// of Initialize() and GetString() below.
internal sealed class WindowsRuntimeResourceManager : WindowsRuntimeResourceManagerBase
{
// Setting invariant culture to Windows Runtime doesn't work because Windows Runtime expects language name in the form of BCP-47 tags while
// invariant name is an empty string. We will use the private invariant culture name x-VL instead.
private const string c_InvariantCulturePrivateName = "x-VL";
private ResourceMap _resourceMap;
private ResourceContext _clonedResourceContext;
private string _clonedResourceContextFallBackList;
private static char[] s_charCultureSeparator;
private struct PackageInfo
{
public string Path;
public string Name;
public string FullName;
}
private static PackageInfo s_currentPackageInfo;
private static List<PackageInfo> s_dependentPackageInfoList;
private static ResourceContext s_globalResourceContext; // Read from it but do not modify it or call Reset() on it as that would affect the app-wide state
private static volatile string s_globalResourceContextFallBackList;
private static volatile CultureInfo s_globalResourceContextBestFitCultureInfo;
private static volatile global::Windows.ApplicationModel.Resources.Core.ResourceManager s_globalResourceManager;
private static Object s_objectForLock = new Object(); // Used by InitializeStatics
private static bool InitializeStatics()
{
global::Windows.ApplicationModel.Resources.Core.ResourceManager globalResourceManager = null;
if (s_globalResourceManager == null)
{
lock (s_objectForLock)
{
if (s_globalResourceManager == null)
{
globalResourceManager = global::Windows.ApplicationModel.Resources.Core.ResourceManager.Current;
InitializeStaticGlobalResourceContext(globalResourceManager);
s_charCultureSeparator = new char[] { ';' };
Package currentPackage = Package.Current;
if (currentPackage != null)
{
StorageFolder currentPackageLocation = currentPackage.InstalledLocation;
s_currentPackageInfo.Path = null;
s_currentPackageInfo.Name = null;
s_currentPackageInfo.FullName = null;
if (currentPackageLocation != null)
s_currentPackageInfo.Path = currentPackageLocation.Path;
PackageId id = currentPackage.Id;
if (id != null)
{
s_currentPackageInfo.Name = id.Name; // We do not enforce this to be non-null.
s_currentPackageInfo.FullName = id.FullName;
}
}
if (globalResourceManager != null &&
s_globalResourceContext != null &&
s_globalResourceContextFallBackList != null &&
s_globalResourceContextFallBackList.Length > 0 && // Should never be empty
s_charCultureSeparator != null &&
s_currentPackageInfo.Path != null)
s_globalResourceManager = globalResourceManager;
}
}
}
return s_globalResourceManager != null;
}
private static void InitializeStaticGlobalResourceContext(global::Windows.ApplicationModel.Resources.Core.ResourceManager resourceManager)
{
if (s_globalResourceContext == null)
{
lock (s_objectForLock)
{
if (s_globalResourceContext == null)
{
resourceManager = resourceManager ?? global::Windows.ApplicationModel.Resources.Core.ResourceManager.Current;
if (resourceManager != null)
{
#pragma warning disable 618
ResourceContext globalResourceContext = resourceManager.DefaultContext;
#pragma warning restore 618
if (globalResourceContext != null)
{
List<String> languages = new List<string>(globalResourceContext.Languages);
s_globalResourceContextBestFitCultureInfo = GetBestFitCultureFromLanguageList(languages);
s_globalResourceContextFallBackList = ReadOnlyListToString(languages);
s_globalResourceContext = globalResourceContext;
s_globalResourceContext.QualifierValues.MapChanged += new MapChangedEventHandler<string, string>(GlobalResourceContextChanged);
}
}
}
}
}
}
// Returns the CultureInfo representing the first language in the list that we can construct a CultureInfo for or null if
// no such culture exists.
private static unsafe CultureInfo GetBestFitCultureFromLanguageList(List<string> languages)
{
char* localeNameBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH]; // LOCALE_NAME_MAX_LENGTH includes null terminator
for (int i = 0; i < languages.Count; i++)
{
if (WindowsRuntimeResourceManagerBase.IsValidCulture(languages[i]))
{
return new CultureInfo(languages[i]);
}
int result = Interop.Kernel32.ResolveLocaleName(languages[i], localeNameBuffer, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH);
if (result != 0)
{
string localeName = new string(localeNameBuffer, 0, result - 1); // result length includes null terminator
if (WindowsRuntimeResourceManagerBase.IsValidCulture(localeName))
{
return new CultureInfo(localeName);
}
}
}
return null;
}
// Can be called independently of/simultaneously with InitializeStatics.
// Does not use the results of InitializeStatics.
// Does not require the use of a lock because, given that the results of all the callees of
// this function are idempotent for the process lifetime, this function will always store
// the same information in s_dependentPackagePath no matter how many times it is called.
private static void InitializeStaticsForDependentPackages()
{
if (s_dependentPackageInfoList == null)
{
// Create an empty list. If there are no dependencies, this will be our way of knowing that we ran
// through this function once.
List<PackageInfo> dependentPackageInfoList = new List<PackageInfo>();
// We call Package.Current here and in InitializeStatics. This may cause a small perf hit.
// In theory we could have cached it as a static variable.
// However, we don't want to have to keep a reference to it alive for the lifetime of the AppDomain.
// Also having InitializeStaticsForDependentPackages not depend on InitializeStatics leads to a simpler design.
Package currentPackage = Package.Current;
if (currentPackage != null)
{
IReadOnlyList<Package> dependencies = currentPackage.Dependencies;
if (dependencies != null)
{
int dependenciesCount = dependencies.Count;
if (dependenciesCount > 0)
{
// We have dependencies. Throw away the old empty list, and create a list with
// capacity exactly equal to the number of dependencies.
dependentPackageInfoList = new List<PackageInfo>(dependenciesCount);
foreach (Package package in dependencies)
{
if (package != null)
{
StorageFolder dependentPackageLocation = package.InstalledLocation;
PackageInfo dependentPackageInfo;
dependentPackageInfo.Path = null;
dependentPackageInfo.Name = null;
dependentPackageInfo.FullName = null;
if (dependentPackageLocation != null)
dependentPackageInfo.Path = dependentPackageLocation.Path;
PackageId id = package.Id;
if (id != null)
{
dependentPackageInfo.Name = id.Name;
dependentPackageInfo.FullName = id.FullName;
}
dependentPackageInfoList.Add(dependentPackageInfo);
}
}
}
}
}
// Assign even if the list is empty. That way we know we ran through this function once.
s_dependentPackageInfoList = dependentPackageInfoList;
}
Debug.Assert(s_dependentPackageInfoList != null);
}
private static void GlobalResourceContextChanged(object sender, IMapChangedEventArgs<string> e)
{
Debug.Assert(s_globalResourceContextFallBackList != null);
Debug.Assert(s_globalResourceContext != null);
IReadOnlyList<string> langs;
try
{
langs = s_globalResourceContext.Languages;
}
catch (ArgumentException)
{
// Sometimes Windows Runtime fails and we get Argument Exception which can fail fast the whole app
// to avoid that we ignore the exception.
return;
}
List<String> languages = new List<string>(langs);
if (languages.Count > 0 && languages[0] == c_InvariantCulturePrivateName)
{
languages[0] = CultureInfo.InvariantCulture.Name;
}
s_globalResourceContextBestFitCultureInfo = GetBestFitCultureFromLanguageList(languages);
s_globalResourceContextFallBackList = ReadOnlyListToString(languages);
}
private static bool LibpathMatchesPackagepath(String libpath, String packagepath)
{
Debug.Assert(libpath != null);
Debug.Assert(packagepath != null);
return packagepath.Length < libpath.Length &&
String.Compare(packagepath, 0,
libpath, 0,
packagepath.Length,
StringComparison.OrdinalIgnoreCase) == 0 &&
// Ensure wzPackagePath is not just a prefix, but a path prefix
// This says: packagepath is c:\foo || c:\foo\
(libpath[packagepath.Length] == '\\' || packagepath.EndsWith("\\"));
}
#if netstandard
/* Returns true if libpath is path to an ni image and if the path contains packagename as a subfolder */
private static bool LibpathContainsPackagename(String libpath, String packagename)
{
Debug.Assert(libpath != null);
Debug.Assert(packagename != null);
return libpath.IndexOf("\\" + packagename + "\\", StringComparison.OrdinalIgnoreCase) >= 0 &&
(libpath.EndsWith("ni.dll", StringComparison.OrdinalIgnoreCase) || libpath.EndsWith("ni.exe", StringComparison.OrdinalIgnoreCase));
}
#endif
private static string FindPackageSimpleNameForFilename(string libpath)
{
Debug.Assert(libpath != null);
Debug.Assert(s_currentPackageInfo.Path != null); // Set in InitializeStatics()
// s_currentPackageInfo.Name may be null (see note below)
if (LibpathMatchesPackagepath(libpath, s_currentPackageInfo.Path))
return s_currentPackageInfo.Name; // This may be null, in which case we failed to get the name (in InitializeStatics), but matched the path, so stop looking.
else // Look at dependent packages
{
InitializeStaticsForDependentPackages();
// s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages.
foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList)
{
if (LibpathMatchesPackagepath(libpath, dependentPackageInfo.Path))
return dependentPackageInfo.Name; // This may be null, in which case we failed to get the name (in InitializeStaticsForDependentPackages), but matched the path, so stop looking.
}
}
#if netstandard
/* On phone libpath is usually ni path and not IL path as we do not touch the IL on phone.
On Phone NI images are no longer under package root. Due to this above logic fails to
find the package to which the library belongs. We assume that NI paths usually have
package name as subfolder in its path. Based on this assumption we can find the package
to which an NI belongs. Below code does that.
*/
if (LibpathContainsPackagename(libpath, s_currentPackageInfo.FullName))
return s_currentPackageInfo.Name;
else // Look at dependent packages
{
// s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages.
foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList)
{
if (LibpathContainsPackagename(libpath, dependentPackageInfo.FullName))
return dependentPackageInfo.Name;
}
}
#endif
return null;
}
// Obtain instances of the Resource Map and Resource Context provided by
// the Windows Modern Resource Manager (MRM).
// Not thread-safe. Only call this once on one thread for each object instance.
// For example, System.Runtime.ResourceManager only calls this from its constructors,
// guaranteeing that this only gets called once, on one thread, for each new instance
// of System.Runtime.ResourceManager.
// Throws exceptions
// Only returns true if the function succeeded completely.
// Outputs exceptionInfo since it may be needed for debugging purposes
// if an exception is thrown by one of Initialize's callees.
public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo)
{
Debug.Assert(libpath != null);
Debug.Assert(reswFilename != null);
exceptionInfo = null;
if (InitializeStatics())
{
// AllResourceMaps can throw ERROR_MRM_MAP_NOT_FOUND,
// although in that case we are not sure for which package it failed to find
// resources (if we are looking for resources for a framework package,
// it might throw ERROR_MRM_MAP_NOT_FOUND if the app package
// resources could not be loaded, even if the framework package
// resources are properly configured). So we will not fill in the
// exceptionInfo structure at this point since we don't have any
// reliable information to include in it.
IReadOnlyDictionary<String, ResourceMap>
resourceMapDictionary = s_globalResourceManager.AllResourceMaps;
if (resourceMapDictionary != null)
{
string packageSimpleName = FindPackageSimpleNameForFilename(libpath);
#if netstandard
// If we have found a simple package name for the assembly, lets make sure it is not *.resource.dll that
// an application may have packaged in its AppX. This is to enforce AppX apps to use PRI resources.
if (packageSimpleName != null)
{
if (packageSimpleName.EndsWith(".resources.dll", StringComparison.CurrentCultureIgnoreCase))
{
// Pretend we didn't get a package name. When an attempt is made to get resource string, GetString implementation
// will see that we are going to use modern resource manager but we don't have PRI and will thrown an exception indicating
// so. This will force the developer to have a valid PRI based resource.
packageSimpleName = null;
}
}
#endif // netstandard
if (packageSimpleName != null)
{
ResourceMap packageResourceMap = null;
// Win8 enforces that package simple names are unique (for example, the App Store will not
// allow two apps with the same package simple name). That is why the Modern Resource Manager
// keys access to resources based on the package simple name.
if (resourceMapDictionary.TryGetValue(packageSimpleName, out packageResourceMap))
{
if (packageResourceMap != null)
{
// GetSubtree returns null when it cannot find resource strings
// named "reswFilename/*" for the package we are looking up.
reswFilename = UriUtility.UriEncode(reswFilename);
_resourceMap = packageResourceMap.GetSubtree(reswFilename);
if (_resourceMap == null)
{
exceptionInfo = new PRIExceptionInfo();
exceptionInfo.PackageSimpleName = packageSimpleName;
exceptionInfo.ResWFile = reswFilename;
}
else
{
_clonedResourceContext = s_globalResourceContext.Clone();
if (_clonedResourceContext != null)
{
// Will need to be changed the first time it is used. But we can't set it to "" since we will take a lock on it.
_clonedResourceContextFallBackList = ReadOnlyListToString(_clonedResourceContext.Languages);
if (_clonedResourceContextFallBackList != null)
return true;
}
}
}
}
}
}
}
return false;
}
private static IReadOnlyList<string> StringToReadOnlyList(string s)
{
Debug.Assert(s != null);
Debug.Assert(s_charCultureSeparator != null);
List<string> newList = new List<string>(s.Split(s_charCultureSeparator));
return newList.AsReadOnly();
}
private static string ReadOnlyListToString(IReadOnlyList<string> list)
{
Debug.Assert(list != null);
return String.Join(";", list);
}
public override CultureInfo GlobalResourceContextBestFitCultureInfo
{
get
{
InitializeStaticGlobalResourceContext(null);
return s_globalResourceContextBestFitCultureInfo;
}
}
// This method will set the culture ci as default language in the default resource context
// which is global for the whole app
public override bool SetGlobalResourceContextDefaultCulture(CultureInfo ci)
{
Debug.Assert(ci != null);
InitializeStaticGlobalResourceContext(null);
if (s_globalResourceContext == null)
{
return false;
}
if (s_globalResourceContextBestFitCultureInfo != null && s_globalResourceContextBestFitCultureInfo.Name.Equals(ci.Name, StringComparison.OrdinalIgnoreCase))
{
if (!ReferenceEquals(s_globalResourceContextBestFitCultureInfo, ci))
{
// We have same culture name but different reference, we'll need to update s_globalResourceContextBestFitCultureInfo only as ci can
// be a customized subclassed culture which setting different values for NFI, DTFI...etc.
s_globalResourceContextBestFitCultureInfo = ci;
}
// the default culture is already set. nothing more need to be done
return true;
}
List<String> languages = new List<String>(s_globalResourceContext.Languages);
languages.Insert(0, ci.Name == CultureInfo.InvariantCulture.Name ? c_InvariantCulturePrivateName : ci.Name);
// remove any duplication in the list
int i = languages.Count - 1;
while (i > 0)
{
if (languages[i].Equals(ci.Name, StringComparison.OrdinalIgnoreCase))
{
languages.RemoveAt(i);
}
i--;
}
s_globalResourceContext.Languages = languages;
// update s_globalResourceContextBestFitCultureInfo and don't wait to be overridden by GlobalResourceContextChanged
// to avoid any timing problem
s_globalResourceContextBestFitCultureInfo = ci;
return true;
}
// Obtains a resource string given the name of the string resource, and optional starting
// and neutral resource cultures (e.g. "de-DE").
// Thread-safe provided that the call to Initialize() happened only once on one thread
// and has already completed successfully, and that the WinRT APIs called below
// continue to be thread-safe.
// Throws exceptions
public override String GetString(String stringName,
String startingCulture, String neutralResourcesCulture)
{
Debug.Assert(stringName != null);
Debug.Assert(_resourceMap != null); // Should have been initialized by now
ResourceCandidate resourceCandidate = null;
stringName = UriUtility.UriEncode(stringName);
if (startingCulture == null && neutralResourcesCulture == null)
{
#pragma warning disable 618
resourceCandidate = _resourceMap.GetValue(stringName);
#pragma warning restore 618
}
else
{
Debug.Assert(_clonedResourceContext != null); // Should have been initialized by now
Debug.Assert(_clonedResourceContextFallBackList != null); // Should have been initialized by now
Debug.Assert(s_globalResourceContextFallBackList != null); // Should have been initialized by now
Debug.Assert(s_globalResourceContextFallBackList.Length > 0); // Should never be empty
// We need to modify the culture fallback list used by the Modern Resource Manager
// The starting culture has to be looked up first, and neutral resources culture has
// to be looked up last.
string newResourceFallBackList = null;
newResourceFallBackList =
(startingCulture == null ? "" : startingCulture + ";") +
s_globalResourceContextFallBackList + // Our tests do not test this line of code, so be extra careful if you modify or move it.
(neutralResourcesCulture == null ? "" : ";" + neutralResourcesCulture);
lock (_clonedResourceContext)
{
// s_globalResourceContextFallBackList may have changed on another thread by now.
// We cannot prevent that from happening because it may have happened on a native
// thread, and we do not share the same lock mechanisms with native code.
// The worst that can happen is that a string is unexpectedly missing
// or in the wrong language.
if (!String.Equals(newResourceFallBackList, _clonedResourceContextFallBackList, StringComparison.Ordinal))
{
_clonedResourceContext.Languages = StringToReadOnlyList(newResourceFallBackList);
_clonedResourceContextFallBackList = newResourceFallBackList;
}
resourceCandidate = _resourceMap.GetValue(stringName, _clonedResourceContext);
}
}
if (resourceCandidate != null)
return resourceCandidate.ValueAsString;
return null;
}
}
// Adapted from the UrlEncode functions at file:alm\tfs_core\framework\common\UriUtility\HttpUtility.cs
// using methods which were in turn borrowed from
// file:ndp\fx\src\xsp\system\web\util\httpencoder.cs
// file:ndp\fx\src\xsp\system\web\httpserverutility.cs
// and file:ndp\fx\src\xsp\system\web\util\httpencoderutility.cs
internal static class UriUtility
{
// This method percent encodes the UTF8 encoding of a string.
// All characters are percent encoded except the unreserved characters from RFC 3986.
// We cannot use the System.Uri class since by default it respects
// the set of unreserved characters from RFC 2396, which is different
// by the 5 characters !*'()
// Adapted from the UrlEncode methods originally
// in file:ndp\fx\src\xsp\system\web\httpserverutility.cs
// and file:ndp\fx\src\xsp\system\web\util\httpencoder.cs
public static string UriEncode(string str)
{
if (str == null)
return null;
byte[] bytes = Encoding.UTF8.GetBytes(str);
int count = bytes.Length;
if (count == 0)
return null;
int cBytesToEncode = 0;
// count them first
for (int i = 0; i < count; i++)
{
if (!IsUriUnreservedChar((char)bytes[i]))
cBytesToEncode++;
}
byte[] expandedBytes = null;
// nothing to expand?
if (cBytesToEncode == 0)
expandedBytes = bytes;
else
{
// expand not 'safe' characters into %xx
expandedBytes = new byte[count + cBytesToEncode * 2];
int pos = 0;
for (int i = 0; i < count; i++)
{
byte b = bytes[i];
if (IsUriUnreservedChar((char)b))
{
expandedBytes[pos++] = b;
}
else
{
expandedBytes[pos++] = (byte)'%';
expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf);
expandedBytes[pos++] = (byte)IntToHex(b & 0xf);
}
}
}
// Since all the bytes in expandedBytes are ascii characters UTF8 encoding can be used
return Encoding.UTF8.GetString(expandedBytes);
}
// Adapted from IntToHex originally in file:ndp\fx\src\xsp\system\web\util\httpencoderutility.cs
private static char IntToHex(int n)
{
if (n <= 9)
return (char)(n + (int)'0');
else
return (char)(n - 10 + (int)'a');
}
// Modified from IsUrlSafeChar originally in file:ndp\fx\src\xsp\system\web\util\httpencoderutility.cs
// Set of unreserved characters from RFC 3986
private static bool IsUriUnreservedChar(char ch)
{
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
return true;
switch (ch)
{
case '-':
case '_':
case '.':
case '~':
return true;
}
return false;
}
}
#endif //FEATURE_APPX
}
| |
/*
* Copyright (c) 2006, Clutch, Inc.
* Original Author: Jeff Cesnik
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace OpenMetaverse
{
/// <summary>
///
/// </summary>
public abstract class UDPBase
{
// these abstract methods must be implemented in a derived class to actually do
// something with the packets that are sent and received.
protected abstract void PacketReceived(UDPPacketBuffer buffer);
protected abstract void PacketSent(UDPPacketBuffer buffer, int bytesSent);
// the port to listen on
protected int udpPort;
// the remote endpoint to communicate with
protected IPEndPoint remoteEndPoint = null;
// the UDP socket
private Socket udpSocket;
// the all important shutdownFlag.
private volatile bool shutdownFlag = true;
/// <summary>
/// Initialize the UDP packet handler in server mode
/// </summary>
/// <param name="port">Port to listening for incoming UDP packets on</param>
public UDPBase(int port)
{
udpPort = port;
}
/// <summary>
/// Initialize the UDP packet handler in client mode
/// </summary>
/// <param name="endPoint">Remote UDP server to connect to</param>
public UDPBase(IPEndPoint endPoint)
{
remoteEndPoint = endPoint;
udpPort = 0;
}
/// <summary>
///
/// </summary>
public void Start()
{
if (shutdownFlag)
{
const int SIO_UDP_CONNRESET = -1744830452;
IPEndPoint ipep = new IPEndPoint(Settings.BIND_ADDR, udpPort);
udpSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
try
{
// this udp socket flag is not supported under mono,
// so we'll catch the exception and continue
udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
}
catch (SocketException)
{
Logger.DebugLog("UDP SIO_UDP_CONNRESET flag not supported on this platform");
}
udpSocket.Bind(ipep);
// we're not shutting down, we're starting up
shutdownFlag = false;
// kick off an async receive. The Start() method will return, the
// actual receives will occur asynchronously and will be caught in
// AsyncEndRecieve().
AsyncBeginReceive();
}
}
/// <summary>
///
/// </summary>
public void Stop()
{
if (!shutdownFlag)
{
// wait indefinitely for a writer lock. Once this is called, the .NET runtime
// will deny any more reader locks, in effect blocking all other send/receive
// threads. Once we have the lock, we set shutdownFlag to inform the other
// threads that the socket is closed.
shutdownFlag = true;
udpSocket.Close();
}
}
/// <summary>
///
/// </summary>
public bool IsRunning
{
get { return !shutdownFlag; }
}
private void AsyncBeginReceive()
{
// allocate a packet buffer
//WrappedObject<UDPPacketBuffer> wrappedBuffer = Pool.CheckOut();
UDPPacketBuffer buf = new UDPPacketBuffer();
if (!shutdownFlag)
{
try
{
// kick off an async read
udpSocket.BeginReceiveFrom(
//wrappedBuffer.Instance.Data,
buf.Data,
0,
UDPPacketBuffer.BUFFER_SIZE,
SocketFlags.None,
ref buf.RemoteEndPoint,
AsyncEndReceive,
//wrappedBuffer);
buf);
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.ConnectionReset)
{
Logger.Log("SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + udpPort, Helpers.LogLevel.Error);
bool salvaged = false;
while (!salvaged)
{
try
{
udpSocket.BeginReceiveFrom(
//wrappedBuffer.Instance.Data,
buf.Data,
0,
UDPPacketBuffer.BUFFER_SIZE,
SocketFlags.None,
ref buf.RemoteEndPoint,
AsyncEndReceive,
//wrappedBuffer);
buf);
salvaged = true;
}
catch (SocketException) { }
catch (ObjectDisposedException) { return; }
}
Logger.Log("Salvaged the UDP listener on port " + udpPort, Helpers.LogLevel.Info);
}
}
catch (ObjectDisposedException) { }
}
}
private void AsyncEndReceive(IAsyncResult iar)
{
// Asynchronous receive operations will complete here through the call
// to AsyncBeginReceive
if (!shutdownFlag)
{
// start another receive - this keeps the server going!
AsyncBeginReceive();
// get the buffer that was created in AsyncBeginReceive
// this is the received data
//WrappedObject<UDPPacketBuffer> wrappedBuffer = (WrappedObject<UDPPacketBuffer>)iar.AsyncState;
//UDPPacketBuffer buffer = wrappedBuffer.Instance;
UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
try
{
// get the length of data actually read from the socket, store it with the
// buffer
buffer.DataLength = udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
// call the abstract method PacketReceived(), passing the buffer that
// has just been filled from the socket read.
PacketReceived(buffer);
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
//finally { wrappedBuffer.Dispose(); }
}
}
public void AsyncBeginSend(UDPPacketBuffer buf)
{
if (!shutdownFlag)
{
try
{
udpSocket.BeginSendTo(
buf.Data,
0,
buf.DataLength,
SocketFlags.None,
buf.RemoteEndPoint,
AsyncEndSend,
buf);
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
}
}
void AsyncEndSend(IAsyncResult result)
{
try
{
UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
if (!udpSocket.Connected) return;
int bytesSent = udpSocket.EndSendTo(result);
PacketSent(buf, bytesSent);
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
}
}
}
| |
// Copyright 2011 Chris Edwards
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Text;
using Fluency.Utils;
namespace Fluency.DataGeneration
{
/// <summary>
/// A random value generator.
/// </summary>
public static class ARandom
{
public static IValueConstraints _valueConstraints = new SqlServerDefaultValuesAndConstraints();
private static Random Random { get { return ThreadLocalRandom.Instance; } }
#region Strings
/// <summary>
/// Returns a random <see cref="string"/> of all capital letters. The length of the string equals the specified <paramref name="size"/>.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public static string String( int size )
{
var builder = new StringBuilder();
for ( var i = 0; i < size; i++ )
//26 letters in the alfabet, ascii + 65 for the capital letters
builder.Append( Convert.ToChar( Convert.ToInt32( Math.Floor( 26 * Random.NextDouble() + 65 ) ) ) );
return builder.ToString();
}
/// <summary>
/// Creates a random <see cref="string"/> constrained to characters in the specified <paramref name="charactersToChooseFrom"/>
/// whose length equals the specified <paramref name="size"/>.
/// </summary>
/// <param name="size">The size.</param>
/// <param name="charactersToChooseFrom">The characters to choose from.</param>
/// <returns></returns>
public static string StringFromCharacterSet( int size, string charactersToChooseFrom )
{
if ( string.IsNullOrEmpty( charactersToChooseFrom ) )
throw new ArgumentNullException( "charactersToChooseFrom", "charactersToChooseFrom[] was null or empty. Cannot generate a string with no chars to choose from." );
var characterArray = charactersToChooseFrom.ToCharArray();
var builder = new StringBuilder( size );
for ( var i = 0; i < size; i++ )
builder.Append( ItemFrom( characterArray ) );
return builder.ToString();
}
/// <summary>
/// Returns a <see cref="string"/> containing randomly generated text, with a length less than or equal to
/// the specified <paramref name="maxChars"/>.<br/>
/// The text looks real, but is actually gibberish. Similar to lorem ipsum. Uses the <see cref="WaffleEngine"/> to generate the text.
/// </summary>
/// <param name="maxChars">The max chars.</param>
/// <returns></returns>
public static string Text( int maxChars )
{
if ( maxChars < 1 )
throw new ArgumentOutOfRangeException( "maxChars", "maxChars must be greater than zero, but was [{0}]".format_using( maxChars ) );
var sb = new StringBuilder();
var waffle = new WaffleEngine( Random );
// Guess at a number of paragraphs to generate.
const int numberOfCharactersPerParagraph = 80;
var numberOfParagraphsToGenerate = maxChars / numberOfCharactersPerParagraph + 1;
waffle.TextWaffle( numberOfParagraphsToGenerate, false, sb );
return sb.ToString( 0, maxChars );
}
/// <summary>
/// Returns a random <see cref="string"/> containing a title of length less than or equal to the specified <paramref name="maxChars"/>.
/// </summary>
/// <param name="maxChars">The max chars.</param>
/// <returns></returns>
public static string Title( int maxChars )
{
if ( maxChars < 1 )
throw new ArgumentOutOfRangeException( "maxChars", "maxChars must be greater than zero, but was [{0}]".format_using( maxChars ) );
var waffle = new WaffleEngine( Random );
var title = waffle.GenerateTitle();
if ( title.Length > maxChars )
title = title.Substring( 0, maxChars );
return title;
}
/// <summary>
/// Returns a <see cref="string"/> containing the <paramref name="pattern"/> after replacing
/// any <c>'9'</c> or <c>'#'</c> characters with random digits.<br/>
/// Example:<br/>
/// <code>ARandom.StringPattern( "(999) 999-9999" ) => "(361) 735-8254"</code>
/// </summary>
/// <param name="pattern">The pattern.</param>
/// <returns></returns>
public static string StringPattern( string pattern )
{
if ( pattern == null )
throw new ArgumentNullException( "pattern" );
var output = "";
foreach ( var c in pattern )
{
var randomizedPattern = GetRandomizedPatternChar( c );
output += randomizedPattern;
}
return output;
}
private static string GetRandomizedPatternChar( char c )
{
switch ( c )
{
case '9':
case '#':
return IntBetween( 0, 9 ).ToString();
default:
return c.ToString();
}
}
#endregion
#region Integers
/// <summary>
/// Returns a random <see cref="integer"/> between 1 and 9999.
/// </summary>
/// <remarks>
/// I think this code was tampered with. I believe it used to include the full range of int
/// including negative values. Not sure.
/// </remarks>
/// <returns></returns>
public static int Int()
{
return IntBetween( 1, 9999 );
}
// TODO: Decimal???
// TODO: Byte???
/// <summary>
/// Returns a random positive <see cref="integer"/> between 1 and 9999.
/// </summary>
/// <returns></returns>
public static int PositiveInt()
{
return IntBetween( 1, 9999 );
}
/// <summary>
/// Returns a random <see cref="integer"/> between the specified <paramref name="min"/> and <paramref name="max"/> (inclusive).
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <returns></returns>
public static int IntBetween( int min, int max )
{
if ( !( min <= max ) )
throw new ArgumentException( "Min value must be less than or equal to Max value. Failed to generate a random int between {0} and {1}".format_using( min, max ) );
// Guard against number greater than int.maxvalue
var offset = -1;
if ( min == int.MinValue )
{
// Guard against number smaller than int.minvalue
offset = 1;
// If doing this would cause us to violate int.maxvalue, cheat (will never generate minvalue).
if ( max == int.MaxValue )
{
offset = -1;
min = min + 1;
}
}
// Because upper bounds is exclusive, increment it by 1 unless it exceeds maxvalue
if (max < int.MaxValue)
max += 1;
// Use offset because Next() does not allow int.MaxValue as upper bounds.
var result = Random.Next( min + offset, max + offset );
return result - offset;
}
#endregion
#region Doubles
/// <summary>
/// Returns a random <see cref="double"/> value.
/// </summary>
/// <returns></returns>
public static double Double()
{
return Random.NextDouble() + Int();
}
/// <summary>
/// Returns a random <see cref="double"/> value between the specified <paramref name="min"/> and <paramref name="max"/> (inclusive).
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <returns></returns>
public static double DoubleBetween( double min, double max )
{
if ( min > max )
throw new ArgumentException( "Min value must be less than Max value." );
var range = max - min;
return min + ( range * Random.NextDouble() );
}
#endregion
#region Floats (Singles)
/// <summary>
/// Returns a random <see cref="float"/> value.
/// </summary>
/// <returns></returns>
public static float Float()
{
return (float)( Random.NextDouble() + Int() );
}
/// <summary>
/// Returns a random <see cref="float"/> value between the specified <paramref name="min"/> and <paramref name="max"/> (inclusive).
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <returns></returns>
public static float FloatBetween( float min, float max )
{
if ( min > max )
throw new ArgumentException( "Min value must be less than Max value." );
var range = max - min;
return min + ( range * (float)Random.NextDouble() );
}
#endregion
#region Currency (Decimal)
/// <summary>
/// Returns a random currency amount (<see cref="Decimal"/>). <br/>
/// The value will be between zero and 999,999,999.00 (inclusive) with a precision of two decimal places.
/// </summary>
/// <returns></returns>
public static decimal CurrencyAmount()
{
return IntBetween( 0, 999999999 ) + ( IntBetween( 0, 100 ) / 100 );
}
/// <summary>
/// Returns a random currency amount (<see cref="Decimal"/>) that is less than or equal to
/// the specified <paramref name="maxAmount"/>. <br/>
/// The value will be between zero and the specified <paramref name="maxAmount"/> (inclusive)
/// with a precision of two decimal places.
/// </summary>
/// <param name="maxAmount">The max amount.</param>
/// <returns></returns>
public static decimal CurrencyAmountLessThan( int maxAmount )
{
return IntBetween( 0, maxAmount - 1 ) + ( IntBetween( 0, 100 ) / 100 );
}
/// <summary>
/// Returns a random currency amount (<see cref="Decimal"/>) that is greater than or equal to the
/// specified <paramref name="minAmount"/> and less than or equal to the specified
/// <paramref name="maxAmount"/>. <br/>
/// The value will be between zero and the specified <paramref name="maxAmount"/> (inclusive)
/// with a precision of two decimal places.
/// </summary>
/// <param name="minAmount">The min amount. </param>
/// <param name="maxAmount">The max amount.</param>
/// <returns></returns>
public static decimal CurrencyAmountBetween( int minAmount, int maxAmount )
{
return IntBetween( minAmount, maxAmount - 1 ) + ( IntBetween( 0, 100 ) / 100 );
}
#endregion
#region Lists and Enums
/// <summary>
/// Returns an item of type <typeparamref name="T"/> chosen at random from the specified list of <paramref name="items"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items">The items.</param>
/// <returns></returns>
public static T ItemFrom< T >( IList< T > items )
{
if ( items == null )
throw new ArgumentNullException( "items", "items parameter was NULL. Cannot select a random item from a null list." );
if ( items.Count == 0 )
throw new ArgumentException( "items was an empty list. Cannot select a random item from an empty list.", "items" );
return items[IntBetween( 0, items.Count - 1 )];
}
/// <summary>
/// Returns an item of type <typeparamref name="T"/> chosen at random from the specified array of <paramref name="items"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items">The items.</param>
/// <returns></returns>
public static T ItemFrom< T >( params T[] items )
{
if ( items == null )
throw new ArgumentNullException( "items", "items parameter was NULL. Cannot select a random item from a null list." );
if ( items.Length == 0 )
throw new ArgumentException( "items was an empty list. Cannot select a random item from an empty list.", "items" );
return ItemFrom< T >( new List< T >( items ) );
}
/// <summary>
/// Returns a randomly selected enum value from the specified enum type <typeparamref name="TEnumType"/>.
/// </summary>
/// <typeparam name="TEnumType"></typeparam>
/// <returns></returns>
public static TEnumType EnumValue< TEnumType >()
{
if ( !typeof ( TEnumType ).IsSubclassOf( typeof ( Enum ) ) )
throw new ArgumentException( "Must be enum type." );
var values = Enum.GetValues( typeof ( TEnumType ) );
var randomArrayIndex = IntBetween( 0, values.Length - 1 );
return (TEnumType)values.GetValue( randomArrayIndex );
}
#endregion
#region DateTimes
/// <summary>
/// Returns a random <see cref="DateTime"/>. <br/>
/// Note, this may return dates far into the future as well as far into the past.
/// </summary>
/// <returns></returns>
public static DateTime DateTime()
{
return DateTimeBetween( _valueConstraints.MinDateTime, _valueConstraints.MaxDateTime );
}
/// <summary>
/// Returns a random <see cref="DateTime"/> between the specified <paramref name="min"/> and <paramref name="max"/> (inclusive).
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <returns></returns>
public static DateTime DateTimeBetween( DateTime min, DateTime max )
{
if ( max <= min )
throw new ArgumentException( string.Format( "Max [{0}] must be greater than min [{1}].", max, min ) );
double startTick = min.Ticks;
double endTick = max.Ticks;
var numberOfTicksInRange = endTick - startTick;
var randomTickInRange = startTick + numberOfTicksInRange * Random.NextDouble();
// Handle overrun...that might occur.
if ( randomTickInRange > System.DateTime.MaxValue.Ticks )
randomTickInRange = System.DateTime.MaxValue.Ticks;
return new DateTime( Convert.ToInt64( randomTickInRange ) );
}
/// <summary>
/// Returns a random <see cref="DateTime"/> prior to the specified <paramref name="upperBounds"/>.
/// </summary>
/// <param name="upperBounds">The compare date time.</param>
/// <returns></returns>
public static DateTime DateTimeBefore( DateTime upperBounds )
{
return DateTimeBetween( _valueConstraints.MinDateTime, upperBounds );
}
/// <summary>
/// Returns a random <see cref="DateTime"/> greater than the specified <paramref name="lowerBounds"/>.
/// </summary>
/// <param name="lowerBounds">The compare date time.</param>
/// <returns></returns>
public static DateTime DateTimeAfter( DateTime lowerBounds )
{
return DateTimeBetween( lowerBounds, _valueConstraints.MaxDateTime );
}
/// <summary>
/// Returns a random <see cref="DateTime"/> less than now.
/// </summary>
/// <returns></returns>
public static DateTime DateTimeInPast()
{
return DateTimeBefore( System.DateTime.Now );
}
/// <summary>
/// Returns a random <see cref="DateTime"/> greater than the specified <paramref name="lowerBounds"/>
/// and less than now.
/// </summary>
/// <param name="lowerBounds">The start date.</param>
/// <returns></returns>
public static DateTime DateTimeInPastSince( DateTime lowerBounds )
{
if ( lowerBounds >= System.DateTime.Now )
throw new ArgumentException( "The datetime must be in the past.", "lowerBounds" );
return DateTimeBetween( lowerBounds, System.DateTime.Now );
}
/// <summary>
/// Returns a random <see cref="DateTime"/> greater than one year ago, and less than now.
/// </summary>
/// <returns></returns>
public static DateTime DateTimeInPastYear()
{
return DateTimeInPastSince( 1.YearsAgo() );
}
/// <summary>
/// Returns a random <see cref="DateTime"/> greater than now.
/// </summary>
/// <returns></returns>
public static DateTime DateTimeInFuture()
{
return DateTimeAfter( System.DateTime.Now );
}
#endregion
#region Dates (No Time)
/// <summary>
/// Generates a random date with no time component.
/// </summary>
/// <returns></returns>
public static DateTime Date()
{
return DateTime().Date;
}
/// <summary>
/// Generates a random date (no time) between the specified <paramref name="startDate"/> and <paramref name="endDate"/> (inclusive).
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <returns></returns>
public static DateTime DateBetween( DateTime startDate, DateTime endDate )
{
if ( DateTimeRangeDoesNotCrossDateBoundary( startDate, endDate ) )
{
throw new FluencyException(
"No valid date exists between the two supplied date time values. For a valid date to exist, there must be a midnight value between them (since technically a date without time is a datetime for midnight on the specified day)." );
}
var result = DateTimeBetween( startDate, endDate ).Date;
// Since start date includes time and result does not, stripping the time could make the result less than the start date. If so, just try again.
if ( result < startDate )
result = DateBetween( startDate, endDate );
return result;
}
/// <summary>
/// Returns a random date (<see cref="DateTime"/> with no time data) greater than the specified <paramref name="lowerBounds"/>
/// </summary>
/// <param name="lowerBounds">The compare date time.</param>
/// <returns></returns>
public static DateTime DateAfter( DateTime lowerBounds )
{
// Don't include lower bound date.
var startDate = lowerBounds + TimeSpan.FromTicks( 1 );
return DateBetween( startDate, _valueConstraints.MaxDateTime );
}
/// <summary>
/// Returns a random date (<see cref="DateTime"/> with no time data) less than today,
/// but greater than the specified <paramref name="lowerBounds"/>.
/// </summary>
/// <param name="lowerBounds">The start date.</param>
/// <returns></returns>
public static DateTime DateInPastSince( DateTime lowerBounds )
{
return DateTimeInPastSince( lowerBounds ).Date;
}
/// <summary>
/// Returns a random date (<see cref="DateTime"/> with no time data) less than today.
/// </summary>
/// <returns></returns>
public static DateTime DateInPast()
{
return DateTimeBefore( System.DateTime.Now ).Date;
}
/// <summary>
/// Returns a random date (<see cref="DateTime"/> with no time data) greater than one year ago today,
/// and less than today.
/// </summary>
/// <returns></returns>
public static DateTime DateInPastYear()
{
return DateTimeInPastYear().Date;
}
#endregion
/// <summary>
/// Returns a random interest rate (<see cref="Decimal"/>) between 0 and 10.
/// </summary>
/// <returns></returns>
public static decimal InterestRate()
{
return (decimal)DoubleBetween( 0, 10 );
}
// TODO: Add CurrencyAmountBetween( decimal minAmount, decimal maxAmount )
/// <summary>
/// Returns a random <see cref="Boolean"/> value.
/// </summary>
/// <returns></returns>
public static bool Boolean()
{
return ItemFrom( true, false );
}
/// <summary>
/// Returns a <see cref="string"/> containing a random email address.<br/>
/// It is (10 random letters)@(10 random letters).(com, org, net, etc.)<br/>
/// Example: <br/>
/// <code>"[email protected]"</code>
/// </summary>
/// <returns></returns>
public static string Email()
{
return string.Format( "{0}@{1}",
String( 10 ),
InternetHostName() );
}
/// <summary>
/// Returns a <see cref="string"/> containing a random http url.<br/>
/// It is of the form: http://(random hostname)/(1-5 part lowercase url path segments with no trailing slash)
/// Example:"http://erjl.fiehoisjn.cc/sjike/ffe/serwao"
/// </summary>
/// <returns></returns>
public static string HttpUrl()
{
return string.Format( "http://{0}/{1}",
InternetHostName(),
UrlPathSegments() );
}
static string UrlPathSegments()
{
var numSegments = IntBetween( 1, 5 );
var pathSegments = new string[numSegments];
for ( int i = 0; i < numSegments; i++ )
pathSegments[i] = String( IntBetween( 4, 10 ) ).ToLower();
return string.Join( "/", pathSegments );
}
/// <summary>
/// Returns a <see cref="string"/> containing a randome internet host name.<br/>
/// It is of the form (3-4 random letters).(3-10 random letters).(com, org, net, etc...)<br/>
/// Example:<br/>
/// <code>"axd.wjdfard.net"</code>
/// </summary>
/// <returns></returns>
public static string InternetHostName()
{
return string.Format( "{0}.{1}.{2}",
ItemFrom( String( 5 ), "www", String( 4 ) ),
String( IntBetween( 3, 10 ) ),
DomainSuffix()
).ToLower();
}
/// <summary>
/// Returns as <see cref="string"/> containing a random internet domain name suffix like com, net, org, etc.
/// </summary>
/// <returns></returns>
public static string DomainSuffix()
{
return ItemFrom( "com", "gov", "net", "org", "biz", "cc", "tv" );
}
#region Names
/// <summary>
/// Returns a random first name.<br/>
/// Examples: <code>"Bob", "Judy", "Josephina"</code>
/// </summary>
/// <returns></returns>
public static string FirstName()
{
return ItemFrom( RandomData.FirstNames );
}
/// <summary>
/// Returns a random last name.<br/>
/// Examples: <code>"Smith", "Olson", "Naranja"</code>
/// </summary>
/// <returns></returns>
public static string LastName()
{
return ItemFrom( RandomData.LastNames );
}
/// <summary>
/// Returns a <see cref="string"/> containing a random full name. It is in the form of first name, followed by a space, then the last name.<br/>
/// Examples: <code>"Bob Smith", "Judith Werner"</code>
/// </summary>
/// <returns></returns>
public static string FullName()
{
return FirstName() + " " + LastName();
}
#endregion
#region Locations and Addresses
public static string AddressLine1()
{
return string.Format( "{0} {1}",
IntBetween( 100, 9999 ),
StreetName() );
}
public static string StreetName()
{
return ItemFrom( RandomData.Streets );
}
/// <summary>
/// Returns the full name of a random US State.<br/>
/// Examples: <code>"Texas", "Ohio", "Alaska"</code>
/// </summary>
/// <returns></returns>
public static string StateName()
{
return ItemFrom( RandomData.States );
}
/// <summary>
/// Returns a random 2-letter state code.<br/>
/// Examples: <code>"TX", "CA", "WA"</code>
/// </summary>
/// <returns></returns>
public static string StateCode()
{
return ItemFrom( RandomData.StateCodes );
}
/// <summary>
/// Returns a random city name.<br/>
/// Examples: <code>"Sacramento", "New York", "Austin"</code>
/// </summary>
/// <returns></returns>
public static string City()
{
return ItemFrom( RandomData.Cities );
}
/// <summary>
/// Returns a random 5-digit zip code.<br/>
/// Example: <code>"78234"</code>
/// </summary>
/// <returns></returns>
public static string ZipCode()
{
return StringPattern( "99999" );
}
#endregion
#region Ages and Birth Dates
/// <summary>
/// Generates a random age between 1 and 100.
/// </summary>
/// <returns></returns>
public static int Age()
{
return IntBetween( 1, 100 );
}
/// <summary>
/// Generates a random adult age between 21 and 65 (inclusive).
/// </summary>
/// <returns></returns>
public static int AdultAge()
{
return IntBetween( 21, 65 );
}
/// <summary>
/// Returns a random BirthDate (<see cref="DateTime"/>) for a person aged anywhere between 5 and 75 years old.<br/>
/// Note: The returned value is a Date and does not include time information.
/// </summary>
/// <returns></returns>
public static DateTime BirthDate()
{
return DateTimeBetween( 75.YearsAgo(), 5.YearsAgo() ).Date;
}
/// <summary>
/// Generates a random birthdate for a person of the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age. (between 1 and 1000</param>
/// <returns></returns>
public static DateTime BirthDateForAge( int age )
{
if ( age < 1 || age > 1000 )
throw new ArgumentOutOfRangeException( "age", "Age is out of range. Should be between 1 and 1000 (yeah, 1000 is large, but age of building?)" );
var latestPossibleBirthday = age.YearsAgo().Date;
var earliestPossibleBirthday = ( age + 1 ).YearsAgo().Date.AddDays( 1 ); // Without this extra day, would be too old.
return DateBetween( earliestPossibleBirthday, latestPossibleBirthday );
}
#endregion
private static bool DateTimeRangeDoesNotCrossDateBoundary( DateTime startDate, DateTime endDate )
{
var bothOnSameDay = startDate.Date == endDate.Date;
var neitherAreMidnight = startDate != startDate.Date && endDate != endDate.Date;
return bothOnSameDay && neitherAreMidnight;
}
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using SquabPie.Mono.Collections.Generic;
using SquabPie.Mono.Cecil.Metadata;
using SquabPie.Mono.Cecil.PE;
using RVA = System.UInt32;
#if !READ_ONLY
namespace SquabPie.Mono.Cecil.Cil {
sealed class CodeWriter : ByteBuffer {
readonly RVA code_base;
internal readonly MetadataBuilder metadata;
readonly Dictionary<uint, MetadataToken> standalone_signatures;
RVA current;
MethodBody body;
public CodeWriter (MetadataBuilder metadata)
: base (0)
{
this.code_base = metadata.text_map.GetNextRVA (TextSegment.CLIHeader);
this.current = code_base;
this.metadata = metadata;
this.standalone_signatures = new Dictionary<uint, MetadataToken> ();
}
public RVA WriteMethodBody (MethodDefinition method)
{
var rva = BeginMethod ();
if (IsUnresolved (method)) {
if (method.rva == 0)
return 0;
WriteUnresolvedMethodBody (method);
} else {
if (IsEmptyMethodBody (method.Body))
return 0;
WriteResolvedMethodBody (method);
}
Align (4);
EndMethod ();
return rva;
}
static bool IsEmptyMethodBody (MethodBody body)
{
return body.instructions.IsNullOrEmpty ()
&& body.variables.IsNullOrEmpty ();
}
static bool IsUnresolved (MethodDefinition method)
{
return method.HasBody && method.HasImage && method.body == null;
}
void WriteUnresolvedMethodBody (MethodDefinition method)
{
var code_reader = metadata.module.Read (method, (_, reader) => reader.code);
MethodSymbols symbols;
var buffer = code_reader.PatchRawMethodBody (method, this, out symbols);
WriteBytes (buffer);
if (symbols.instructions.IsNullOrEmpty ())
return;
symbols.method_token = method.token;
symbols.local_var_token = GetLocalVarToken (buffer, symbols);
var symbol_writer = metadata.symbol_writer;
if (symbol_writer != null)
symbol_writer.Write (symbols);
}
static MetadataToken GetLocalVarToken (ByteBuffer buffer, MethodSymbols symbols)
{
if (symbols.variables.IsNullOrEmpty ())
return MetadataToken.Zero;
buffer.position = 8;
return new MetadataToken (buffer.ReadUInt32 ());
}
void WriteResolvedMethodBody (MethodDefinition method)
{
body = method.Body;
ComputeHeader ();
if (RequiresFatHeader ())
WriteFatHeader ();
else
WriteByte ((byte) (0x2 | (body.CodeSize << 2))); // tiny
WriteInstructions ();
if (body.HasExceptionHandlers)
WriteExceptionHandlers ();
var symbol_writer = metadata.symbol_writer;
if (symbol_writer != null)
symbol_writer.Write (body);
}
void WriteFatHeader ()
{
var body = this.body;
byte flags = 0x3; // fat
if (body.InitLocals)
flags |= 0x10; // init locals
if (body.HasExceptionHandlers)
flags |= 0x8; // more sections
WriteByte (flags);
WriteByte (0x30);
WriteInt16 ((short) body.max_stack_size);
WriteInt32 (body.code_size);
body.local_var_token = body.HasVariables
? GetStandAloneSignature (body.Variables)
: MetadataToken.Zero;
WriteMetadataToken (body.local_var_token);
}
void WriteInstructions ()
{
var instructions = body.Instructions;
var items = instructions.items;
var size = instructions.size;
for (int i = 0; i < size; i++) {
var instruction = items [i];
WriteOpCode (instruction.opcode);
WriteOperand (instruction);
}
}
void WriteOpCode (OpCode opcode)
{
if (opcode.Size == 1) {
WriteByte (opcode.Op2);
} else {
WriteByte (opcode.Op1);
WriteByte (opcode.Op2);
}
}
void WriteOperand (Instruction instruction)
{
var opcode = instruction.opcode;
var operand_type = opcode.OperandType;
if (operand_type == OperandType.InlineNone)
return;
var operand = instruction.operand;
if (operand == null)
throw new ArgumentException ();
switch (operand_type) {
case OperandType.InlineSwitch: {
var targets = (Instruction []) operand;
WriteInt32 (targets.Length);
var diff = instruction.Offset + opcode.Size + (4 * (targets.Length + 1));
for (int i = 0; i < targets.Length; i++)
WriteInt32 (GetTargetOffset (targets [i]) - diff);
break;
}
case OperandType.ShortInlineBrTarget: {
var target = (Instruction) operand;
WriteSByte ((sbyte) (GetTargetOffset (target) - (instruction.Offset + opcode.Size + 1)));
break;
}
case OperandType.InlineBrTarget: {
var target = (Instruction) operand;
WriteInt32 (GetTargetOffset (target) - (instruction.Offset + opcode.Size + 4));
break;
}
case OperandType.ShortInlineVar:
WriteByte ((byte) GetVariableIndex ((VariableDefinition) operand));
break;
case OperandType.ShortInlineArg:
WriteByte ((byte) GetParameterIndex ((ParameterDefinition) operand));
break;
case OperandType.InlineVar:
WriteInt16 ((short) GetVariableIndex ((VariableDefinition) operand));
break;
case OperandType.InlineArg:
WriteInt16 ((short) GetParameterIndex ((ParameterDefinition) operand));
break;
case OperandType.InlineSig:
WriteMetadataToken (GetStandAloneSignature ((CallSite) operand));
break;
case OperandType.ShortInlineI:
if (opcode == OpCodes.Ldc_I4_S)
WriteSByte ((sbyte) operand);
else
WriteByte ((byte) operand);
break;
case OperandType.InlineI:
WriteInt32 ((int) operand);
break;
case OperandType.InlineI8:
WriteInt64 ((long) operand);
break;
case OperandType.ShortInlineR:
WriteSingle ((float) operand);
break;
case OperandType.InlineR:
WriteDouble ((double) operand);
break;
case OperandType.InlineString:
WriteMetadataToken (
new MetadataToken (
TokenType.String,
GetUserStringIndex ((string) operand)));
break;
case OperandType.InlineType:
case OperandType.InlineField:
case OperandType.InlineMethod:
case OperandType.InlineTok:
WriteMetadataToken (metadata.LookupToken ((IMetadataTokenProvider) operand));
break;
default:
throw new ArgumentException ();
}
}
int GetTargetOffset (Instruction instruction)
{
if (instruction == null) {
var last = body.instructions [body.instructions.size - 1];
return last.offset + last.GetSize ();
}
return instruction.offset;
}
uint GetUserStringIndex (string @string)
{
if (@string == null)
return 0;
return metadata.user_string_heap.GetStringIndex (@string);
}
static int GetVariableIndex (VariableDefinition variable)
{
return variable.Index;
}
int GetParameterIndex (ParameterDefinition parameter)
{
if (body.method.HasThis) {
if (parameter == body.this_parameter)
return 0;
return parameter.Index + 1;
}
return parameter.Index;
}
bool RequiresFatHeader ()
{
var body = this.body;
return body.CodeSize >= 64
|| body.InitLocals
|| body.HasVariables
|| body.HasExceptionHandlers
|| body.MaxStackSize > 8;
}
void ComputeHeader ()
{
int offset = 0;
var instructions = body.instructions;
var items = instructions.items;
var count = instructions.size;
var stack_size = 0;
var max_stack = 0;
Dictionary<Instruction, int> stack_sizes = null;
if (body.HasExceptionHandlers)
ComputeExceptionHandlerStackSize (ref stack_sizes);
for (int i = 0; i < count; i++) {
var instruction = items [i];
instruction.offset = offset;
offset += instruction.GetSize ();
ComputeStackSize (instruction, ref stack_sizes, ref stack_size, ref max_stack);
}
body.code_size = offset;
body.max_stack_size = max_stack;
}
void ComputeExceptionHandlerStackSize (ref Dictionary<Instruction, int> stack_sizes)
{
var exception_handlers = body.ExceptionHandlers;
for (int i = 0; i < exception_handlers.Count; i++) {
var exception_handler = exception_handlers [i];
switch (exception_handler.HandlerType) {
case ExceptionHandlerType.Catch:
AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
break;
case ExceptionHandlerType.Filter:
AddExceptionStackSize (exception_handler.FilterStart, ref stack_sizes);
AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
break;
}
}
}
static void AddExceptionStackSize (Instruction handler_start, ref Dictionary<Instruction, int> stack_sizes)
{
if (handler_start == null)
return;
if (stack_sizes == null)
stack_sizes = new Dictionary<Instruction, int> ();
stack_sizes [handler_start] = 1;
}
static void ComputeStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, ref int stack_size, ref int max_stack)
{
int computed_size;
if (stack_sizes != null && stack_sizes.TryGetValue (instruction, out computed_size))
stack_size = computed_size;
max_stack = System.Math.Max (max_stack, stack_size);
ComputeStackDelta (instruction, ref stack_size);
max_stack = System.Math.Max (max_stack, stack_size);
CopyBranchStackSize (instruction, ref stack_sizes, stack_size);
ComputeStackSize (instruction, ref stack_size);
}
static void CopyBranchStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, int stack_size)
{
if (stack_size == 0)
return;
switch (instruction.opcode.OperandType) {
case OperandType.ShortInlineBrTarget:
case OperandType.InlineBrTarget:
CopyBranchStackSize (ref stack_sizes, (Instruction) instruction.operand, stack_size);
break;
case OperandType.InlineSwitch:
var targets = (Instruction[]) instruction.operand;
for (int i = 0; i < targets.Length; i++)
CopyBranchStackSize (ref stack_sizes, targets [i], stack_size);
break;
}
}
static void CopyBranchStackSize (ref Dictionary<Instruction, int> stack_sizes, Instruction target, int stack_size)
{
if (stack_sizes == null)
stack_sizes = new Dictionary<Instruction, int> ();
int branch_stack_size = stack_size;
int computed_size;
if (stack_sizes.TryGetValue (target, out computed_size))
branch_stack_size = System.Math.Max (branch_stack_size, computed_size);
stack_sizes [target] = branch_stack_size;
}
static void ComputeStackSize (Instruction instruction, ref int stack_size)
{
switch (instruction.opcode.FlowControl) {
case FlowControl.Branch:
case FlowControl.Break:
case FlowControl.Throw:
case FlowControl.Return:
stack_size = 0;
break;
}
}
static void ComputeStackDelta (Instruction instruction, ref int stack_size)
{
switch (instruction.opcode.FlowControl) {
case FlowControl.Call: {
var method = (IMethodSignature) instruction.operand;
// pop 'this' argument
if (method.HasImplicitThis() && instruction.opcode.Code != Code.Newobj)
stack_size--;
// pop normal arguments
if (method.HasParameters)
stack_size -= method.Parameters.Count;
// pop function pointer
if (instruction.opcode.Code == Code.Calli)
stack_size--;
// push return value
if (method.ReturnType.etype != ElementType.Void || instruction.opcode.Code == Code.Newobj)
stack_size++;
break;
}
default:
ComputePopDelta (instruction.opcode.StackBehaviourPop, ref stack_size);
ComputePushDelta (instruction.opcode.StackBehaviourPush, ref stack_size);
break;
}
}
static void ComputePopDelta (StackBehaviour pop_behavior, ref int stack_size)
{
switch (pop_behavior) {
case StackBehaviour.Popi:
case StackBehaviour.Popref:
case StackBehaviour.Pop1:
stack_size--;
break;
case StackBehaviour.Pop1_pop1:
case StackBehaviour.Popi_pop1:
case StackBehaviour.Popi_popi:
case StackBehaviour.Popi_popi8:
case StackBehaviour.Popi_popr4:
case StackBehaviour.Popi_popr8:
case StackBehaviour.Popref_pop1:
case StackBehaviour.Popref_popi:
stack_size -= 2;
break;
case StackBehaviour.Popi_popi_popi:
case StackBehaviour.Popref_popi_popi:
case StackBehaviour.Popref_popi_popi8:
case StackBehaviour.Popref_popi_popr4:
case StackBehaviour.Popref_popi_popr8:
case StackBehaviour.Popref_popi_popref:
stack_size -= 3;
break;
case StackBehaviour.PopAll:
stack_size = 0;
break;
}
}
static void ComputePushDelta (StackBehaviour push_behaviour, ref int stack_size)
{
switch (push_behaviour) {
case StackBehaviour.Push1:
case StackBehaviour.Pushi:
case StackBehaviour.Pushi8:
case StackBehaviour.Pushr4:
case StackBehaviour.Pushr8:
case StackBehaviour.Pushref:
stack_size++;
break;
case StackBehaviour.Push1_push1:
stack_size += 2;
break;
}
}
void WriteExceptionHandlers ()
{
Align (4);
var handlers = body.ExceptionHandlers;
if (handlers.Count < 0x15 && !RequiresFatSection (handlers))
WriteSmallSection (handlers);
else
WriteFatSection (handlers);
}
static bool RequiresFatSection (Collection<ExceptionHandler> handlers)
{
for (int i = 0; i < handlers.Count; i++) {
var handler = handlers [i];
if (IsFatRange (handler.TryStart, handler.TryEnd))
return true;
if (IsFatRange (handler.HandlerStart, handler.HandlerEnd))
return true;
if (handler.HandlerType == ExceptionHandlerType.Filter
&& IsFatRange (handler.FilterStart, handler.HandlerStart))
return true;
}
return false;
}
static bool IsFatRange (Instruction start, Instruction end)
{
if (start == null)
throw new ArgumentException ();
if (end == null)
return true;
return end.Offset - start.Offset > 255 || start.Offset > 65535;
}
void WriteSmallSection (Collection<ExceptionHandler> handlers)
{
const byte eh_table = 0x1;
WriteByte (eh_table);
WriteByte ((byte) (handlers.Count * 12 + 4));
WriteBytes (2);
WriteExceptionHandlers (
handlers,
i => WriteUInt16 ((ushort) i),
i => WriteByte ((byte) i));
}
void WriteFatSection (Collection<ExceptionHandler> handlers)
{
const byte eh_table = 0x1;
const byte fat_format = 0x40;
WriteByte (eh_table | fat_format);
int size = handlers.Count * 24 + 4;
WriteByte ((byte) (size & 0xff));
WriteByte ((byte) ((size >> 8) & 0xff));
WriteByte ((byte) ((size >> 16) & 0xff));
WriteExceptionHandlers (handlers, WriteInt32, WriteInt32);
}
void WriteExceptionHandlers (Collection<ExceptionHandler> handlers, Action<int> write_entry, Action<int> write_length)
{
for (int i = 0; i < handlers.Count; i++) {
var handler = handlers [i];
write_entry ((int) handler.HandlerType);
write_entry (handler.TryStart.Offset);
write_length (GetTargetOffset (handler.TryEnd) - handler.TryStart.Offset);
write_entry (handler.HandlerStart.Offset);
write_length (GetTargetOffset (handler.HandlerEnd) - handler.HandlerStart.Offset);
WriteExceptionHandlerSpecific (handler);
}
}
void WriteExceptionHandlerSpecific (ExceptionHandler handler)
{
switch (handler.HandlerType) {
case ExceptionHandlerType.Catch:
WriteMetadataToken (metadata.LookupToken (handler.CatchType));
break;
case ExceptionHandlerType.Filter:
WriteInt32 (handler.FilterStart.Offset);
break;
default:
WriteInt32 (0);
break;
}
}
public MetadataToken GetStandAloneSignature (Collection<VariableDefinition> variables)
{
var signature = metadata.GetLocalVariableBlobIndex (variables);
return GetStandAloneSignatureToken (signature);
}
public MetadataToken GetStandAloneSignature (CallSite call_site)
{
var signature = metadata.GetCallSiteBlobIndex (call_site);
var token = GetStandAloneSignatureToken (signature);
call_site.MetadataToken = token;
return token;
}
MetadataToken GetStandAloneSignatureToken (uint signature)
{
MetadataToken token;
if (standalone_signatures.TryGetValue (signature, out token))
return token;
token = new MetadataToken (TokenType.Signature, metadata.AddStandAloneSignature (signature));
standalone_signatures.Add (signature, token);
return token;
}
RVA BeginMethod ()
{
return current;
}
void WriteMetadataToken (MetadataToken token)
{
WriteUInt32 (token.ToUInt32 ());
}
void Align (int align)
{
align--;
WriteBytes (((position + align) & ~align) - position);
}
void EndMethod ()
{
current = (RVA) (code_base + position);
}
}
}
#endif
| |
//------------------------------------------------------------------------------
// <copyright file="_NtlmClient.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Collections;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.Globalization;
internal class NtlmClient : ISessionAuthenticationModule {
internal const string AuthType = "NTLM";
internal static string Signature = AuthType.ToLower(CultureInfo.InvariantCulture);
internal static int SignatureSize = Signature.Length;
public Authorization Authenticate(string challenge, WebRequest webRequest, ICredentials credentials) {
GlobalLog.Print("NtlmClient::Authenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()");
return DoAuthenticate(challenge, webRequest, credentials, false);
}
private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) {
GlobalLog.Print("NtlmClient::DoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString());
GlobalLog.Assert(credentials != null, "NtlmClient::DoAuthenticate()|credentials == null");
if (credentials == null) {
return null;
}
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest != null, "NtlmClient::DoAuthenticate()|httpWebRequest == null");
GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "NtlmClient::DoAuthenticate()|httpWebRequest.ChallengedUri == null");
NTAuthentication authSession = null;
string incoming = null;
if (!preAuthenticate) {
int index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature);
if (index < 0) {
return null;
}
int blobBegin = index + SignatureSize;
//
// there may be multiple challenges. If the next character after the
// package name is not a comma then it is challenge data
//
if (challenge.Length > blobBegin && challenge[blobBegin] != ',') {
++blobBegin;
}
else {
index = -1;
}
if (index >= 0 && challenge.Length > blobBegin)
{
// Strip other modules information in case of multiple challenges
// i.e do not take ", NTLM" as part of the following Negotiate blob
// Negotiate TlRMTVNTUAACAAAADgAOADgAAAA1wo ... MAbwBmAHQALgBjAG8AbQAAAAAA,NTLM
index = challenge.IndexOf(',', blobBegin);
if (index != -1)
incoming = challenge.Substring(blobBegin, index - blobBegin);
else
incoming = challenge.Substring(blobBegin);
}
authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this);
GlobalLog.Print("NtlmClient::DoAuthenticate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession));
}
if (authSession==null) {
NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature);
GlobalLog.Print("NtlmClient::DoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC));
string username = string.Empty;
if (NC == null || (!(NC is SystemNetworkCredential) && (username = NC.InternalGetUserName()).Length == 0))
{
return null;
}
ICredentialPolicy policy = AuthenticationManager.CredentialPolicy;
if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this))
return null;
SpnToken spn = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest);
GlobalLog.Print("NtlmClient::Authenticate() ChallengedSpn:" + ValidationHelper.ToString(spn));
ChannelBinding binding = null;
if (httpWebRequest.CurrentAuthenticationState.TransportContext != null)
{
binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint);
}
authSession =
new NTAuthentication(
AuthType,
NC,
spn,
httpWebRequest,
binding);
GlobalLog.Print("NtlmClient::DoAuthenticate() setting SecurityContext for:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " to authSession:" + ValidationHelper.HashString(authSession));
httpWebRequest.CurrentAuthenticationState.SetSecurityContext(authSession, this);
}
string clientResponse = authSession.GetOutgoingBlob(incoming);
if (clientResponse==null) {
return null;
}
bool canShareConnection = httpWebRequest.UnsafeOrProxyAuthenticatedConnectionSharing;
if (canShareConnection) {
httpWebRequest.LockConnection = true;
}
// this is the first leg of an NTLM handshake,
// set the NtlmKeepAlive override *STRICTLY* only in this case.
httpWebRequest.NtlmKeepAlive = incoming==null;
return AuthenticationManager.GetGroupAuthorization(this, AuthType + " " + clientResponse, authSession.IsCompleted, authSession, canShareConnection, false);
}
public bool CanPreAuthenticate {
get {
return true;
}
}
public Authorization PreAuthenticate(WebRequest webRequest, ICredentials credentials) {
GlobalLog.Print("NtlmClient::PreAuthenticate() webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " calling DoAuthenticate()");
return DoAuthenticate(null, webRequest, credentials, true);
}
public string AuthenticationType {
get {
return AuthType;
}
}
//
// called when getting the final blob on the 200 OK from the server
//
public bool Update(string challenge, WebRequest webRequest) {
GlobalLog.Print("NtlmClient::Update(): " + challenge);
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest != null, "NtlmClient::Update()|httpWebRequest == null");
GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "NtlmClient::Update()|httpWebRequest.ChallengedUri == null");
//
// try to retrieve the state of the ongoing handshake
//
NTAuthentication authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this);
GlobalLog.Print("NtlmClient::Update() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession));
if (authSession==null) {
GlobalLog.Print("NtlmClient::Update() null session returning true");
return true;
}
GlobalLog.Print("NtlmClient::Update() authSession.IsCompleted:" + authSession.IsCompleted.ToString());
if (!authSession.IsCompleted && httpWebRequest.CurrentAuthenticationState.StatusCodeMatch==httpWebRequest.ResponseStatusCode) {
GlobalLog.Print("NtlmClient::Update() still handshaking (based on status code) returning false");
return false;
}
ClearSession(httpWebRequest);
// now possibly close the ConnectionGroup after authentication is done.
if (!httpWebRequest.UnsafeOrProxyAuthenticatedConnectionSharing) {
GlobalLog.Print("NtlmClient::Update() releasing ConnectionGroup:" + httpWebRequest.GetConnectionGroupLine());
httpWebRequest.ServicePoint.ReleaseConnectionGroup(httpWebRequest.GetConnectionGroupLine());
}
// Extract the CBT we used and cache it for future requests that want to do preauth
httpWebRequest.ServicePoint.SetCachedChannelBinding(httpWebRequest.ChallengedUri, authSession.ChannelBinding);
GlobalLog.Print("NtlmClient::Update() session removed and ConnectionGorup released returning true");
return true;
}
public void ClearSession(WebRequest webRequest) {
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
GlobalLog.Assert(httpWebRequest != null, "NtlmClient::ClearSession()|httpWebRequest == null");
httpWebRequest.CurrentAuthenticationState.ClearSession();
}
public bool CanUseDefaultCredentials {
get {
return true;
}
}
}; // class NtlmClient
} // namespace System.Net
| |
// <copyright file="NativeRealtimeMultiplayerClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.Native
{
using System;
using System.Linq;
using System.Collections.Generic;
using GooglePlayGames.BasicApi.Multiplayer;
using GooglePlayGames.OurUtils;
using GooglePlayGames.Native.PInvoke;
using Types = GooglePlayGames.Native.Cwrapper.Types;
using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus;
public class NativeRealtimeMultiplayerClient : IRealTimeMultiplayerClient
{
private readonly object mSessionLock = new object();
private readonly NativeClient mNativeClient;
private readonly RealtimeManager mRealtimeManager;
private volatile RoomSession mCurrentSession;
internal NativeRealtimeMultiplayerClient(NativeClient nativeClient, RealtimeManager manager)
{
mNativeClient = Misc.CheckNotNull(nativeClient);
mRealtimeManager = Misc.CheckNotNull(manager);
mCurrentSession = GetTerminatedSession();
// register callback for when the application pauses. OnPause
// will disconnect the client, we need to leave the room manually
// the disconnection does not trigger and events.
PlayGamesHelperObject.AddPauseCallback(HandleAppPausing);
}
private RoomSession GetTerminatedSession()
{
var terminatedRoom = new RoomSession(mRealtimeManager, new NoopListener());
terminatedRoom.EnterState(new ShutdownState(terminatedRoom), false);
return terminatedRoom;
}
public void CreateQuickGame(uint minOpponents, uint maxOpponents, uint variant,
RealTimeMultiplayerListener listener)
{
CreateQuickGame (minOpponents, maxOpponents, variant, 0, listener);
}
public void CreateQuickGame(uint minOpponents, uint maxOpponents, uint variant,
ulong exclusiveBitMask, RealTimeMultiplayerListener listener)
{
lock (mSessionLock)
{
var newSession = new RoomSession(mRealtimeManager, listener);
if (mCurrentSession.IsActive())
{
Logger.e("Received attempt to create a new room without cleaning up the old one.");
newSession.LeaveRoom();
return;
}
mCurrentSession = newSession;
//Quickgames start when there is the min number of players
Logger.d("QuickGame: Setting MinPlayersToStart = " + minOpponents);
mCurrentSession.MinPlayersToStart = minOpponents;
// We're holding the session lock, so no other threads could have torn down the session
// in the meantime.
using (var configBuilder = RealtimeRoomConfigBuilder.Create())
{
var config = configBuilder.SetMinimumAutomatchingPlayers(minOpponents)
.SetMaximumAutomatchingPlayers(maxOpponents)
.SetVariant(variant)
.SetExclusiveBitMask(exclusiveBitMask)
.Build();
using (config)
{
using (var helper = HelperForSession(newSession))
{
newSession.StartRoomCreation(mNativeClient.GetUserId(),
() => mRealtimeManager.CreateRoom(config, helper,
newSession.HandleRoomResponse)
);
}
}
}
}
}
private static RealTimeEventListenerHelper HelperForSession(RoomSession session)
{
return RealTimeEventListenerHelper.Create()
.SetOnDataReceivedCallback((room, participant, data, isReliable) =>
session.OnDataReceived(room, participant, data, isReliable))
.SetOnParticipantStatusChangedCallback((room, participant) =>
session.OnParticipantStatusChanged(room, participant))
.SetOnRoomConnectedSetChangedCallback((room) =>
session.OnConnectedSetChanged(room))
.SetOnRoomStatusChangedCallback((room) =>
session.OnRoomStatusChanged(room));
}
private void HandleAppPausing(bool paused)
{
if (paused)
{
Logger.d("Application is pausing, which disconnects the RTMP " +
" client. Leaving room.");
LeaveRoom();
}
}
public void CreateWithInvitationScreen(uint minOpponents, uint maxOppponents, uint variant,
RealTimeMultiplayerListener listener)
{
lock (mSessionLock)
{
var newRoom = new RoomSession(mRealtimeManager, listener);
if (mCurrentSession.IsActive())
{
Logger.e("Received attempt to create a new room without cleaning up the old one.");
newRoom.LeaveRoom();
return;
}
// The user attempted to create a room via the invitation screen, this is now the new
// current room.
mCurrentSession = newRoom;
mCurrentSession.ShowingUI = true;
mRealtimeManager.ShowPlayerSelectUI(minOpponents, maxOppponents, true,
response =>
{
mCurrentSession.ShowingUI = false;
if (response.Status() != Status.UIStatus.VALID)
{
Logger.d("User did not complete invitation screen.");
newRoom.LeaveRoom();
return;
}
// the min number to start is the number of automatched
// plus the number of named invitations
// plus the local player.
mCurrentSession.MinPlayersToStart =
response.MinimumAutomatchingPlayers() +
(uint)response.Count()
+ 1;
using (var configBuilder = RealtimeRoomConfigBuilder.Create())
{
configBuilder.SetVariant(variant);
configBuilder.PopulateFromUIResponse(response);
using (var config = configBuilder.Build())
{
using (var helper = HelperForSession(newRoom))
{
newRoom.StartRoomCreation(mNativeClient.GetUserId(),
() => mRealtimeManager.CreateRoom(config, helper,
newRoom.HandleRoomResponse));
}
}
}
});
}
}
public void ShowWaitingRoomUI()
{
lock (mSessionLock)
{
mCurrentSession.ShowWaitingRoomUI();
}
}
public void GetAllInvitations(Action<Invitation[]> callback)
{
mRealtimeManager.FetchInvitations((response) =>
{
if (!response.RequestSucceeded())
{
Logger.e("Couldn't load invitations.");
callback(new Invitation[0]);
return;
}
List<Invitation> invites = new List<Invitation>();
foreach (var invitation in response.Invitations())
{
using (invitation)
{
invites.Add(invitation.AsInvitation());
}
}
callback(invites.ToArray());
});
}
public void AcceptFromInbox(RealTimeMultiplayerListener listener)
{
lock (mSessionLock)
{
var newRoom = new RoomSession(mRealtimeManager, listener);
if (mCurrentSession.IsActive())
{
Logger.e("Received attempt to accept invitation without cleaning up " +
"active session.");
newRoom.LeaveRoom();
return;
}
// The user accepted an invitation from the inbox, this is now the current room.
mCurrentSession = newRoom;
mCurrentSession.ShowingUI = true;
mRealtimeManager.ShowRoomInboxUI(
response =>
{
mCurrentSession.ShowingUI = false;
if (response.ResponseStatus() != Status.UIStatus.VALID)
{
Logger.d("User did not complete invitation screen.");
newRoom.LeaveRoom();
return;
}
// We are not cleaning up the invitation here to workaround a bug in the
// C++ SDK where it holds a reference to un-owned memory rather than making a
// copy. This is cleaned up after the callback comes back instead.
var invitation = response.Invitation();
using (var helper = HelperForSession(newRoom))
{
Logger.d("About to accept invitation " + invitation.Id());
newRoom.StartRoomCreation(mNativeClient.GetUserId(),
() => mRealtimeManager.AcceptInvitation(invitation, helper,
acceptResponse =>
{
// Clean up the invitation here (see above comment).
using (invitation)
{
newRoom.HandleRoomResponse(acceptResponse);
newRoom.SetInvitation(invitation.AsInvitation());
}
}));
}
});
}
}
public void AcceptInvitation(string invitationId, RealTimeMultiplayerListener listener)
{
lock (mSessionLock)
{
var newRoom = new RoomSession(mRealtimeManager, listener);
if (mCurrentSession.IsActive())
{
Logger.e("Received attempt to accept invitation without cleaning up " +
"active session.");
newRoom.LeaveRoom();
return;
}
mCurrentSession = newRoom;
mRealtimeManager.FetchInvitations(response =>
{
if (!response.RequestSucceeded())
{
Logger.e("Couldn't load invitations.");
newRoom.LeaveRoom();
return;
}
foreach (var invitation in response.Invitations())
{
using (invitation)
{
if (invitation.Id().Equals(invitationId))
{
mCurrentSession.MinPlayersToStart =
invitation.AutomatchingSlots() +
invitation.ParticipantCount();
Logger.d("Setting MinPlayersToStart with invitation to : " +
mCurrentSession.MinPlayersToStart);
using (var helper = HelperForSession(newRoom))
{
newRoom.StartRoomCreation(mNativeClient.GetUserId(),
() => mRealtimeManager.AcceptInvitation(
invitation, helper, newRoom.HandleRoomResponse));
return;
}
}
}
}
Logger.e("Room creation failed since we could not find invitation with ID "
+ invitationId);
newRoom.LeaveRoom();
});
}
}
public Invitation GetInvitation()
{
return mCurrentSession.GetInvitation();
}
public void LeaveRoom()
{
mCurrentSession.LeaveRoom();
}
public void SendMessageToAll(bool reliable, byte[] data)
{
mCurrentSession.SendMessageToAll(reliable, data);
}
public void SendMessageToAll(bool reliable, byte[] data, int offset, int length)
{
mCurrentSession.SendMessageToAll(reliable, data, offset, length);
}
public void SendMessage(bool reliable, string participantId, byte[] data)
{
mCurrentSession.SendMessage(reliable, participantId, data);
}
public void SendMessage(bool reliable, string participantId, byte[] data, int offset,
int length)
{
mCurrentSession.SendMessage(reliable, participantId, data, offset, length);
}
public List<Participant> GetConnectedParticipants()
{
return mCurrentSession.GetConnectedParticipants();
}
public Participant GetSelf()
{
return mCurrentSession.GetSelf();
}
public Participant GetParticipant(string participantId)
{
return mCurrentSession.GetParticipant(participantId);
}
public bool IsRoomConnected()
{
return mCurrentSession.IsRoomConnected();
}
public void DeclineInvitation(string invitationId)
{
mRealtimeManager.FetchInvitations(response =>
{
if (!response.RequestSucceeded())
{
Logger.e("Couldn't load invitations.");
return;
}
foreach (var invitation in response.Invitations())
{
using (invitation)
{
if (invitation.Id().Equals(invitationId))
{
mRealtimeManager.DeclineInvitation(invitation);
}
}
}
});
}
/// <summary>
/// A stub implementation of the RealTimeMultiplayerListener API. Used so that we can guarantee
/// that we will never have a null reference to a listener object.
/// </summary>
private class NoopListener : RealTimeMultiplayerListener
{
public void OnRoomSetupProgress(float percent)
{
}
public void OnRoomConnected(bool success)
{
}
public void OnLeftRoom()
{
}
public void OnParticipantLeft(Participant participant)
{
}
public void OnPeersConnected(string[] participantIds)
{
}
public void OnPeersDisconnected(string[] participantIds)
{
}
public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data)
{
}
}
/// <summary>A class that encapsulates the state machine required to map the native callbacks to the
/// corresponding callbacks in Unity. This session exposes an API that mirrors all the commands
/// that can be issued to the RealtimeMultiplayerClient and directs these to the current state
/// of the state machine which performs the actual logic.
///
/// <para>All methods that can transitively update the state of the statemachine must be guarded with
/// the lifecycle lock to ensure a consistent user-facing view of the state of the session.</para>
///
/// <para>Note that this class maintains the invariant that mState is never null.</para>
/// <para>See the doc for the individual states for details on state transitions and note that
/// all states assume that all lifecycle methods will be invoked while the containing
/// RoomSession is holding the lifecycle lock.</para>
/// </summary>
private class RoomSession
{
private readonly object mLifecycleLock = new object();
private readonly OnGameThreadForwardingListener mListener;
private readonly RealtimeManager mManager;
private volatile string mCurrentPlayerId;
private volatile State mState;
private volatile bool mStillPreRoomCreation;
Invitation mInvitation;
private volatile bool mShowingUI;
private uint mMinPlayersToStart;
internal RoomSession(RealtimeManager manager, RealTimeMultiplayerListener listener)
{
mManager = Misc.CheckNotNull(manager);
mListener = new OnGameThreadForwardingListener(listener);
EnterState(new BeforeRoomCreateStartedState(this), false);
mStillPreRoomCreation = true;
}
internal bool ShowingUI
{
get
{
return mShowingUI;
}
set
{
mShowingUI = value;
}
}
internal uint MinPlayersToStart
{
get
{
return mMinPlayersToStart;
}
set
{
mMinPlayersToStart = value;
}
}
internal RealtimeManager Manager()
{
return mManager;
}
internal bool IsActive()
{
return mState.IsActive();
}
internal string SelfPlayerId()
{
return mCurrentPlayerId;
}
public void SetInvitation(Invitation invitation)
{
mInvitation = invitation;
}
public Invitation GetInvitation()
{
return mInvitation;
}
internal OnGameThreadForwardingListener OnGameThreadListener()
{
return mListener;
}
/// <summary>
/// Enters the state firing on the OnStateEntered event.
/// </summary>
/// <param name="handler">Handler for the state.</param>
internal void EnterState(State handler)
{
EnterState(handler, true);
}
/// <summary>
/// Sets the state of the session to the given state.
/// </summary>
/// <remarks>
/// Lifecycle methods - these might cause state transitions, and thus require us to hold a
/// lock while they're executing to prevent any externally visible inconsistent state (e.g.
/// receiving any callbacks after we've left a room).
/// </remarks>
/// <param name="handler">Handler - the State Handler.</param>
/// <param name="fireStateEnteredEvent">If set to <c>true</c> fire the StateEntered event.</param>
internal void EnterState(State handler, bool fireStateEnteredEvent)
{
lock (mLifecycleLock)
{
mState = Misc.CheckNotNull(handler);
if (fireStateEnteredEvent)
{
Logger.d("Entering state: " + handler.GetType().Name);
mState.OnStateEntered();
}
}
}
internal void LeaveRoom()
{
if (!ShowingUI)
{
lock (mLifecycleLock)
{
mState.LeaveRoom();
}
}
else
{
Logger.d("Not leaving room since showing UI");
}
}
internal void ShowWaitingRoomUI()
{
mState.ShowWaitingRoomUI(MinPlayersToStart);
}
/// <summary>
/// Starts the room creation provided the session is still in a state that allows room
/// creation (i.e. it hasn't been torn down).
/// </summary>
/// <param name="currentPlayerId">The current player identifier.</param>
/// <param name="createRoom">The action that will begin creating the room.</param>
internal void StartRoomCreation(string currentPlayerId, Action createRoom)
{
lock (mLifecycleLock)
{
if (!mStillPreRoomCreation)
{
Logger.e("Room creation started more than once, this shouldn't happen!");
return;
}
if (!mState.IsActive())
{
Logger.w("Received an attempt to create a room after the session was already " +
"torn down!");
return;
}
mCurrentPlayerId = Misc.CheckNotNull(currentPlayerId);
mStillPreRoomCreation = false;
EnterState(new RoomCreationPendingState(this));
createRoom.Invoke();
}
}
internal void OnRoomStatusChanged(NativeRealTimeRoom room)
{
lock (mLifecycleLock)
{
mState.OnRoomStatusChanged(room);
}
}
internal void OnConnectedSetChanged(NativeRealTimeRoom room)
{
lock (mLifecycleLock)
{
mState.OnConnectedSetChanged(room);
}
}
internal void OnParticipantStatusChanged(NativeRealTimeRoom room,
MultiplayerParticipant participant)
{
lock (mLifecycleLock)
{
mState.OnParticipantStatusChanged(room, participant);
}
}
/// <summary>
/// Handles the room response.
/// </summary>
/// <param name="response">Response.</param>
/// <param name="invitation">Invitation if accepting an invitation, this is stored in the session, otherwise null</param>
internal void HandleRoomResponse(RealtimeManager.RealTimeRoomResponse response)
{
lock (mLifecycleLock)
{
mState.HandleRoomResponse(response);
}
}
/**
* Non-Lifecycle methods - these cannot cause state transitions, and thus we do not need to
* hold any locks. We rely on only accessing volatile fields to ensure consistency instead.
*/
internal void OnDataReceived(NativeRealTimeRoom room, MultiplayerParticipant sender,
byte[] data, bool isReliable)
{
mState.OnDataReceived(room, sender, data, isReliable);
}
internal void SendMessageToAll(bool reliable, byte[] data)
{
SendMessageToAll(reliable, data, 0, data.Length);
}
internal void SendMessageToAll(bool reliable, byte[] data, int offset, int length)
{
mState.SendToAll(data, offset, length, reliable);
}
internal void SendMessage(bool reliable, string participantId, byte[] data)
{
SendMessage(reliable, participantId, data, 0, data.Length);
}
internal void SendMessage(bool reliable, string participantId, byte[] data, int offset,
int length)
{
mState.SendToSpecificRecipient(participantId, data, offset, length, reliable);
}
internal List<Participant> GetConnectedParticipants()
{
return mState.GetConnectedParticipants();
}
internal virtual Participant GetSelf()
{
return mState.GetSelf();
}
internal virtual Participant GetParticipant(string participantId)
{
return mState.GetParticipant(participantId);
}
internal virtual bool IsRoomConnected()
{
return mState.IsRoomConnected();
}
}
private static T WithDefault<T>(T presented, T defaultValue) where T : class
{
return presented != null ? presented : defaultValue;
}
/// <summary>
/// Simple forwarding wrapper that makes sure all callbacks occur on the game thread.
/// </summary>
class OnGameThreadForwardingListener
{
private readonly RealTimeMultiplayerListener mListener;
internal OnGameThreadForwardingListener(RealTimeMultiplayerListener listener)
{
mListener = Misc.CheckNotNull(listener);
}
public void RoomSetupProgress(float percent)
{
PlayGamesHelperObject.RunOnGameThread(() => mListener.OnRoomSetupProgress(percent));
}
public void RoomConnected(bool success)
{
PlayGamesHelperObject.RunOnGameThread(() => mListener.OnRoomConnected(success));
}
public void LeftRoom()
{
PlayGamesHelperObject.RunOnGameThread(() => mListener.OnLeftRoom());
}
public void PeersConnected(string[] participantIds)
{
PlayGamesHelperObject.RunOnGameThread(() => mListener.OnPeersConnected(participantIds));
}
public void PeersDisconnected(string[] participantIds)
{
PlayGamesHelperObject.RunOnGameThread(
() => mListener.OnPeersDisconnected(participantIds));
}
public void RealTimeMessageReceived(bool isReliable, string senderId, byte[] data)
{
PlayGamesHelperObject.RunOnGameThread(
() => mListener.OnRealTimeMessageReceived(isReliable, senderId, data));
}
public void ParticipantLeft(Participant participant)
{
PlayGamesHelperObject.RunOnGameThread(
() => mListener.OnParticipantLeft(participant));
}
}
/// <summary>
/// A base state implementation. All methods do nothing or return stub values. States that
/// require specific behavior must override the corresponding methods.
/// </summary>
internal abstract class State
{
internal virtual void HandleRoomResponse(RealtimeManager.RealTimeRoomResponse response)
{
Logger.d(this.GetType().Name + ".HandleRoomResponse: Defaulting to no-op.");
}
internal virtual bool IsActive()
{
Logger.d(this.GetType().Name + ".IsNonPreemptable: Is preemptable by default.");
return true;
}
internal virtual void LeaveRoom()
{
Logger.d(this.GetType().Name + ".LeaveRoom: Defaulting to no-op.");
}
internal virtual void ShowWaitingRoomUI(uint minimumParticipantsBeforeStarting)
{
Logger.d(this.GetType().Name + ".ShowWaitingRoomUI: Defaulting to no-op.");
}
internal virtual void OnStateEntered()
{
Logger.d(this.GetType().Name + ".OnStateEntered: Defaulting to no-op.");
}
internal virtual void OnRoomStatusChanged(NativeRealTimeRoom room)
{
Logger.d(this.GetType().Name + ".OnRoomStatusChanged: Defaulting to no-op.");
}
internal virtual void OnConnectedSetChanged(NativeRealTimeRoom room)
{
Logger.d(this.GetType().Name + ".OnConnectedSetChanged: Defaulting to no-op.");
}
internal virtual void OnParticipantStatusChanged(NativeRealTimeRoom room,
MultiplayerParticipant participant)
{
Logger.d(this.GetType().Name + ".OnParticipantStatusChanged: Defaulting to no-op.");
}
internal virtual void OnDataReceived(NativeRealTimeRoom room, MultiplayerParticipant sender,
byte[] data, bool isReliable)
{
Logger.d(this.GetType().Name + ".OnDataReceived: Defaulting to no-op.");
}
internal virtual void SendToSpecificRecipient(
string recipientId, byte[] data, int offset, int length, bool isReliable)
{
Logger.d(this.GetType().Name + ".SendToSpecificRecipient: Defaulting to no-op.");
}
internal virtual void SendToAll(byte[] data, int offset, int length, bool isReliable)
{
Logger.d(this.GetType().Name + ".SendToApp: Defaulting to no-op.");
}
internal virtual List<Participant> GetConnectedParticipants()
{
Logger.d(this.GetType().Name + ".GetConnectedParticipants: Returning empty connected" +
" participants");
return new List<Participant>();
}
internal virtual Participant GetSelf()
{
Logger.d(this.GetType().Name + ".GetSelf: Returning null self.");
return null;
}
internal virtual Participant GetParticipant(string participantId)
{
Logger.d(this.GetType().Name + ".GetSelf: Returning null participant.");
return null;
}
internal virtual bool IsRoomConnected()
{
Logger.d(this.GetType().Name + ".IsRoomConnected: Returning room not connected.");
return false;
}
}
/// <summary>
/// A base class for all states where message passing is enabled (i.e. the Active and
/// Connecting states).
/// </summary>
private abstract class MessagingEnabledState : State
{
protected readonly RoomSession mSession;
protected NativeRealTimeRoom mRoom;
protected Dictionary<string, MultiplayerParticipant> mNativeParticipants;
protected Dictionary<string, Participant> mParticipants;
internal MessagingEnabledState(RoomSession session, NativeRealTimeRoom room)
{
mSession = Misc.CheckNotNull(session);
UpdateCurrentRoom(room);
}
internal void UpdateCurrentRoom(NativeRealTimeRoom room)
{
if (mRoom != null)
{
mRoom.Dispose();
}
mRoom = Misc.CheckNotNull(room);
mNativeParticipants = mRoom.Participants().ToDictionary(p => p.Id());
mParticipants = mNativeParticipants.Values
.Select(p => p.AsParticipant())
.ToDictionary(p => p.ParticipantId);
}
internal sealed override void OnRoomStatusChanged(NativeRealTimeRoom room)
{
HandleRoomStatusChanged(room);
UpdateCurrentRoom(room);
}
internal virtual void HandleRoomStatusChanged(NativeRealTimeRoom room)
{
// noop
}
internal sealed override void OnConnectedSetChanged(NativeRealTimeRoom room)
{
HandleConnectedSetChanged(room);
UpdateCurrentRoom(room);
}
internal virtual void HandleConnectedSetChanged(NativeRealTimeRoom room)
{
// noop
}
internal sealed override void OnParticipantStatusChanged(NativeRealTimeRoom room,
MultiplayerParticipant participant)
{
HandleParticipantStatusChanged(room, participant);
UpdateCurrentRoom(room);
}
internal virtual void HandleParticipantStatusChanged(NativeRealTimeRoom room,
MultiplayerParticipant participant)
{
// noop
}
internal sealed override List<Participant> GetConnectedParticipants()
{
var connectedParticipants = mParticipants.Values
.Where(p => p.IsConnectedToRoom)
.ToList();
connectedParticipants.Sort();
return connectedParticipants;
}
internal override void SendToSpecificRecipient(
string recipientId, byte[] data, int offset, int length, bool isReliable)
{
if (!mNativeParticipants.ContainsKey(recipientId))
{
Logger.e("Attempted to send message to unknown participant " + recipientId);
return;
}
if (isReliable)
{
mSession.Manager().SendReliableMessage(mRoom, mNativeParticipants[recipientId],
Misc.GetSubsetBytes(data, offset, length), null);
}
else
{
mSession.Manager().SendUnreliableMessageToSpecificParticipants(mRoom,
new List<MultiplayerParticipant> { mNativeParticipants[recipientId] },
Misc.GetSubsetBytes(data, offset, length));
}
}
internal override void SendToAll(byte[] data, int offset,
int length, bool isReliable)
{
var trimmed = Misc.GetSubsetBytes(data, offset, length);
if (isReliable)
{
foreach (var participantId in mNativeParticipants.Keys)
{
SendToSpecificRecipient(participantId, trimmed, 0, trimmed.Length, true);
}
}
else
{
mSession.Manager().SendUnreliableMessageToAll(mRoom, trimmed);
}
}
internal override void OnDataReceived(NativeRealTimeRoom room,
MultiplayerParticipant sender, byte[] data, bool isReliable)
{
mSession.OnGameThreadListener().RealTimeMessageReceived(isReliable, sender.Id(), data);
}
}
/// <summary>The state of the session before we have initiated room creation. This is necessary
/// in cases where we have to do additional callbacks to look up information before the room
/// can be created (e.g. finding the invitation corresponding to an ID).
///
/// <para>This is the initial state for all sessions. In the event of an error before room
/// creation states, this state will immediately transition to Shutdown (as there is nothing
/// to clean up). Unlike other states, transitions out of this state are determined externally
/// by the enclosing room (which knows when we can begin room creation).</para>
/// </summary>
class BeforeRoomCreateStartedState : State
{
private readonly RoomSession mContainingSession;
internal BeforeRoomCreateStartedState(RoomSession session)
{
mContainingSession = Misc.CheckNotNull(session);
}
internal override void LeaveRoom()
{
Logger.d("Session was torn down before room was created.");
mContainingSession.OnGameThreadListener().RoomConnected(false);
mContainingSession.EnterState(new ShutdownState(mContainingSession));
}
}
/// <summary>The state we were have issued a room creation request. Normally this state
/// immediately transitions into the connecting state where we begin creating the mesh network.
///
/// <para>This state can transition to 3 other states: Connecting, Aborting room, or shutdown.
/// If room creation proceeds normally and there are no intervening calls to leave room, we
/// transition into 'Connecting'. If the user tears down the session before room creation
/// completes, we transition into 'Aborting Room', and if the room creation fails we transition
/// immediately to 'Shutdown'.</para>
/// </summary>
class RoomCreationPendingState : State
{
private readonly RoomSession mContainingSession;
internal RoomCreationPendingState(RoomSession session)
{
mContainingSession = Misc.CheckNotNull(session);
}
internal override void HandleRoomResponse(RealtimeManager.RealTimeRoomResponse response)
{
if (!response.RequestSucceeded())
{
mContainingSession.EnterState(new ShutdownState(mContainingSession));
mContainingSession.OnGameThreadListener().RoomConnected(false);
return;
}
mContainingSession.EnterState(new ConnectingState(response.Room(), mContainingSession));
}
internal override bool IsActive()
{
// The client must explicitly leave before cleaning up a room that is being created.
return true;
}
internal override void LeaveRoom()
{
Logger.d("Received request to leave room during room creation, aborting creation.");
mContainingSession.EnterState(new AbortingRoomCreationState(mContainingSession));
}
}
/// <summary>A state indicating we're in the process of creating a fully connected mesh network
/// between all multiplayer clients.
///
/// <para>We can transition into 2 states from 'Connecting': 'Active' and 'Leaving room'.
/// If we are able to create a mesh network from all participants, we move into 'Active'.
/// If any participant fails to create the mesh or the user asks to leave the room, we
/// transition into 'Leave Room'.</para>
/// </summary>
class ConnectingState : MessagingEnabledState
{
private const float InitialPercentComplete = 20.0F;
private static readonly HashSet<Types.ParticipantStatus> FailedStatuses =
new HashSet<Types.ParticipantStatus>
{
Types.ParticipantStatus.DECLINED,
Types.ParticipantStatus.LEFT,
};
private HashSet<string> mConnectedParticipants = new HashSet<string>();
private float mPercentComplete = InitialPercentComplete;
private float mPercentPerParticipant;
internal ConnectingState(NativeRealTimeRoom room, RoomSession session)
: base(session, room)
{
mPercentPerParticipant =
(100.0f - InitialPercentComplete) / (float)session.MinPlayersToStart;
}
internal override void OnStateEntered()
{
mSession.OnGameThreadListener().RoomSetupProgress(mPercentComplete);
}
internal override void HandleConnectedSetChanged(NativeRealTimeRoom room)
{
HashSet<string> newConnectedSet = new HashSet<string>();
// handle when an invitation is received, so number of total
// participants is not known.
if (room.Status() == Types.RealTimeRoomStatus.AUTO_MATCHING ||
room.Status() == Types.RealTimeRoomStatus.CONNECTING)
{
if (mSession.MinPlayersToStart <= room.ParticipantCount())
{
mSession.MinPlayersToStart = mSession.MinPlayersToStart +
room.ParticipantCount();
mPercentPerParticipant =
(100.0f - InitialPercentComplete) / (float)mSession.MinPlayersToStart;
}
}
foreach (var participant in room.Participants())
{
using (participant)
{
if (participant.IsConnectedToRoom())
{
newConnectedSet.Add(participant.Id());
}
}
}
// If the connected set hasn't actually changed, bail out.
if (mConnectedParticipants.Equals(newConnectedSet))
{
Logger.w("Received connected set callback with unchanged connected set!");
return;
}
var noLongerConnected = mConnectedParticipants.Except(newConnectedSet);
// Check if the room has been deleted.
// creation.
if (room.Status() == Types.RealTimeRoomStatus.DELETED)
{
Logger.e("Participants disconnected during room setup, failing. " +
"Participants were: " + string.Join(",", noLongerConnected.ToArray()));
mSession.OnGameThreadListener().RoomConnected(false);
mSession.EnterState(new ShutdownState(mSession));
return;
}
var newlyConnected = newConnectedSet.Except(mConnectedParticipants);
Logger.d("New participants connected: " +
string.Join(",", newlyConnected.ToArray()));
// If we're fully connected, transition to the Active state and signal the client.
if (room.Status() == Types.RealTimeRoomStatus.ACTIVE)
{
Logger.d("Fully connected! Transitioning to active state.");
mSession.EnterState(new ActiveState(room, mSession));
mSession.OnGameThreadListener().RoomConnected(true);
return;
}
// Otherwise, we're not fully there. Increment the progress by the appropriate
// amount and inform the client.
mPercentComplete += mPercentPerParticipant * (float)newlyConnected.Count();
mConnectedParticipants = newConnectedSet;
mSession.OnGameThreadListener().RoomSetupProgress(mPercentComplete);
}
internal override void HandleParticipantStatusChanged(NativeRealTimeRoom room,
MultiplayerParticipant participant)
{
if (!FailedStatuses.Contains(participant.Status()))
{
return;
}
// call PeersDisconnected when the player leaves or declines
// this let's the caller know that someone declined.
mSession.OnGameThreadListener().ParticipantLeft(participant.AsParticipant());
if (room.Status() != Types.RealTimeRoomStatus.CONNECTING &&
room.Status() != Types.RealTimeRoomStatus.AUTO_MATCHING)
{
LeaveRoom();
}
}
internal override void LeaveRoom()
{
mSession.EnterState(new LeavingRoom(mSession, mRoom,
() => mSession.OnGameThreadListener().RoomConnected(false)));
}
internal override void ShowWaitingRoomUI(uint minimumParticipantsBeforeStarting)
{
mSession.ShowingUI = true;
mSession.Manager().ShowWaitingRoomUI(mRoom, minimumParticipantsBeforeStarting, response =>
{
mSession.ShowingUI = false;
Logger.d("ShowWaitingRoomUI Response: " + response.ResponseStatus());
if(response.ResponseStatus() == Status.UIStatus.VALID) {
Logger.d("Connecting state ShowWaitingRoomUI: room pcount:" + response.Room().ParticipantCount() +
" status: " + response.Room().Status());
if (response.Room().Status() == Types.RealTimeRoomStatus.ACTIVE) {
mSession.EnterState(new ActiveState(response.Room(), mSession));
}
}
else if(response.ResponseStatus() == Status.UIStatus.ERROR_LEFT_ROOM){
LeaveRoom();
}
else {
mSession.OnGameThreadListener().RoomSetupProgress(this.mPercentComplete);
}
});
}
}
/// <summary>The active state, i.e. we have created a full mesh network and have informed the user.
/// <para>The only transition out of 'Active' is into 'Leaving Room'. This occurs either when
/// we are informed that the user has been unexpectedly disconnected, or when the user
/// explicitly asks to leave.</para>
/// </summary>
class ActiveState : MessagingEnabledState
{
internal ActiveState(NativeRealTimeRoom room, RoomSession session)
: base(session, room)
{
}
internal override void OnStateEntered()
{
if (GetSelf() == null)
{
Logger.e("Room reached active state with unknown participant for the player");
LeaveRoom();
}
}
internal override bool IsRoomConnected()
{
return true;
}
internal override Participant GetParticipant(string participantId)
{
if (!mParticipants.ContainsKey(participantId))
{
Logger.e("Attempted to retrieve unknown participant " + participantId);
return null;
}
return mParticipants[participantId];
}
internal override Participant GetSelf()
{
foreach (var participant in mParticipants.Values)
{
if (participant.Player != null
&& participant.Player.id.Equals(mSession.SelfPlayerId()))
{
return participant;
}
}
return null;
}
internal override void HandleConnectedSetChanged(NativeRealTimeRoom room)
{
List<string> newlyConnected = new List<string>();
List<string> newlyLeft = new List<string>();
var updatedParticipants = room.Participants().ToDictionary(p => p.Id());
foreach (var participantId in mNativeParticipants.Keys)
{
var freshParticipant = updatedParticipants[participantId];
var staleParticipant = mNativeParticipants[participantId];
if (!freshParticipant.IsConnectedToRoom())
{
newlyLeft.Add(participantId);
}
if (!staleParticipant.IsConnectedToRoom() && freshParticipant.IsConnectedToRoom())
{
newlyConnected.Add(participantId);
}
}
// Update the cached participants to reflect the new statuses by cleaning up the old
// ones and then updating the new values.
foreach (var participant in mNativeParticipants.Values)
{
participant.Dispose();
}
mNativeParticipants = updatedParticipants;
mParticipants = mNativeParticipants.Values
.Select(p => p.AsParticipant())
.ToDictionary(p => p.ParticipantId);
Logger.d("Updated participant statuses: " +
string.Join(",", mParticipants.Values.Select(p => p.ToString()).ToArray()));
// Check whether the current player was disconnected from the room.
if (newlyLeft.Contains(GetSelf().ParticipantId))
{
Logger.w("Player was disconnected from the multiplayer session.");
}
// Strip out the participant ID of the local player - this player is not a "peer".
var selfId = GetSelf().ParticipantId;
newlyConnected = newlyConnected.Where(peerId => !peerId.Equals(selfId)).ToList();
newlyLeft = newlyLeft.Where(peerId => !peerId.Equals(selfId)).ToList();
// Otherwise inform the client about changes in room participants, screening out
// results about the local player.
if (newlyConnected.Count > 0)
{
newlyConnected.Sort();
mSession.OnGameThreadListener()
.PeersConnected(newlyConnected.Where(peer => !peer.Equals(selfId)).ToArray());
}
if (newlyLeft.Count > 0)
{
newlyLeft.Sort();
mSession.OnGameThreadListener()
.PeersDisconnected(newlyLeft.Where(peer => !peer.Equals(selfId)).ToArray());
}
}
internal override void LeaveRoom()
{
mSession.EnterState(new LeavingRoom(mSession, mRoom,
() => mSession.OnGameThreadListener().LeftRoom()));
}
}
/// <summary>
/// A terminal state. Once this state is reached the session is considered dead and can be
/// safely disposed of.
/// </summary>
class ShutdownState : State
{
private readonly RoomSession mSession;
internal ShutdownState(RoomSession session)
{
mSession = Misc.CheckNotNull(session);
}
internal override bool IsActive()
{
return false;
}
internal override void LeaveRoom()
{
mSession.OnGameThreadListener().LeftRoom();
}
}
/// <summary>
/// A state indicating the we're in the process of leaving a room. Sessions that enter this
/// state immediately transition into 'Shutdown' after issuing a request to leave the room.
/// </summary>
class LeavingRoom : State
{
private readonly RoomSession mSession;
private readonly NativeRealTimeRoom mRoomToLeave;
private readonly Action mLeavingCompleteCallback;
internal LeavingRoom(RoomSession session, NativeRealTimeRoom room,
Action leavingCompleteCallback)
{
mSession = Misc.CheckNotNull(session);
mRoomToLeave = Misc.CheckNotNull(room);
mLeavingCompleteCallback = Misc.CheckNotNull(leavingCompleteCallback);
}
internal override bool IsActive()
{
return false;
}
internal override void OnStateEntered()
{
mSession.Manager().LeaveRoom(mRoomToLeave, (status) =>
{ mLeavingCompleteCallback();
mSession.EnterState(new ShutdownState(mSession));
} );
}
}
/// <summary>The state indicating that we were in the process of creating a room, but that the
/// user quit before this room was sucessfully created. This state is implemented such that any
/// room response that we receive will result in the room being left, and the session
/// transitioning to a terminal state.
///
/// <para>This state transitions into 'Shutdown' (if the room creation failed) or 'Leaving room'
/// (if room creation succeeded).</para>
/// </summary>
class AbortingRoomCreationState : State
{
private readonly RoomSession mSession;
internal AbortingRoomCreationState(RoomSession session)
{
mSession = Misc.CheckNotNull(session);
}
internal override bool IsActive()
{
return false;
}
internal override void HandleRoomResponse(RealtimeManager.RealTimeRoomResponse response)
{
// If the room creation didn't succeed, we have nothing left to do, just bail out
// and alert the user callback.
if (!response.RequestSucceeded())
{
mSession.EnterState(new ShutdownState(mSession));
mSession.OnGameThreadListener().RoomConnected(false);
return;
}
// We just created a room which we're not going to use. Clean up and notify the user
// when we're done.
mSession.EnterState(new LeavingRoom(mSession, response.Room(),
() => mSession.OnGameThreadListener().RoomConnected(false)));
}
}
}
}
#endif
| |
// Copyright (c) .NET Foundation and contributors. 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.IO;
using System.Linq;
using Microsoft.Build.Evaluation;
using NuGet.Frameworks;
using NuGet.ProjectModel;
namespace Microsoft.DotNet.Cli.Utils
{
internal class MSBuildProject : IProject
{
private static readonly NuGetFramework s_toolPackageFramework = FrameworkConstants.CommonFrameworks.NetCoreApp10;
private Project _project;
private string _projectRoot;
private string _msBuildExePath;
public string DepsJsonPath
{
get
{
return _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("ProjectDepsFilePath"))
.EvaluatedValue;
}
}
public string RuntimeConfigJsonPath
{
get
{
return _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("ProjectRuntimeConfigFilePath"))
.EvaluatedValue;
}
}
public string FullOutputPath
{
get
{
return _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("TargetDir"))
.EvaluatedValue;
}
}
public string ProjectRoot
{
get
{
return _projectRoot;
}
}
public NuGetFramework DotnetCliToolTargetFramework
{
get
{
var frameworkString = _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("DotnetCliToolTargetFramework"))
?.EvaluatedValue;
if (string.IsNullOrEmpty(frameworkString))
{
return s_toolPackageFramework;
}
return NuGetFramework.Parse(frameworkString);
}
}
public Dictionary<string, string> EnvironmentVariables
{
get
{
return new Dictionary<string, string>
{
{ Constants.MSBUILD_EXE_PATH, _msBuildExePath }
};
}
}
public string ToolDepsJsonGeneratorProject
{
get
{
var generatorProject = _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("ToolDepsJsonGeneratorProject"))
?.EvaluatedValue;
return generatorProject;
}
}
public MSBuildProject(
string msBuildProjectPath,
NuGetFramework framework,
string configuration,
string outputPath,
string msBuildExePath)
{
_projectRoot = msBuildExePath;
var globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "MSBuildExtensionsPath", Path.GetDirectoryName(msBuildExePath) }
};
if(framework != null)
{
globalProperties.Add("TargetFramework", framework.GetShortFolderName());
}
if(outputPath != null)
{
globalProperties.Add("OutputPath", outputPath);
}
if(configuration != null)
{
globalProperties.Add("Configuration", configuration);
}
_project = ProjectCollection.GlobalProjectCollection.LoadProject(
msBuildProjectPath,
globalProperties,
null);
_msBuildExePath = msBuildExePath;
}
public IEnumerable<SingleProjectInfo> GetTools()
{
var toolsReferences = _project.AllEvaluatedItems.Where(i => i.ItemType.Equals("DotNetCliToolReference"));
var tools = toolsReferences.Select(t => new SingleProjectInfo(
t.EvaluatedInclude,
t.GetMetadataValue("Version"),
Enumerable.Empty<ResourceAssemblyInfo>()));
return tools;
}
public LockFile GetLockFile()
{
var lockFilePath = GetLockFilePathFromProjectLockFileProperty() ??
GetLockFilePathFromIntermediateBaseOutputPath();
return new LockFileFormat()
.ReadWithLock(lockFilePath)
.Result;
}
public bool TryGetLockFile(out LockFile lockFile)
{
lockFile = null;
var lockFilePath = GetLockFilePathFromProjectLockFileProperty() ??
GetLockFilePathFromIntermediateBaseOutputPath();
if (lockFilePath == null)
{
return false;
}
if (!File.Exists(lockFilePath))
{
return false;
}
lockFile = new LockFileFormat()
.ReadWithLock(lockFilePath)
.Result;
return true;
}
private string GetLockFilePathFromProjectLockFileProperty()
{
return _project
.AllEvaluatedProperties
.Where(p => p.Name.Equals("ProjectAssetsFile"))
.Select(p => p.EvaluatedValue)
.FirstOrDefault(p => Path.IsPathRooted(p) && File.Exists(p));
}
private string GetLockFilePathFromIntermediateBaseOutputPath()
{
var intermediateOutputPath = _project
.AllEvaluatedProperties
.FirstOrDefault(p => p.Name.Equals("BaseIntermediateOutputPath"))
.EvaluatedValue;
return Path.Combine(intermediateOutputPath, "project.assets.json");
}
}
}
| |
using System;
using System.Collections.Generic;
namespace PlayFab.PlayStreamModels
{
/// <summary>
/// The base type for all PlayStream events.
/// See https://api.playfab.com/playstream/docs/PlayStreamEventModels for more information
/// </summary>
public abstract class PlayStreamEventBase
{
public string Source;
public string EventId;
public string EntityId;
public string EntityType;
public string EventNamespace;
public string EventName;
public DateTime Timestamp;
public Dictionary<string, string> CustomTags;
public List<object> History;
public object Reserved;
}
#region none
public class EntityCreatedEventData : PlayStreamEventBase
{
public string EntityChain;
}
public class EntityLoggedInEventData : PlayStreamEventBase
{
public string EntityChain;
}
public class EntityObjectsSetEventData : PlayStreamEventBase
{
public string EntityChain;
public List<ObjectSet> Objects;
}
public class StudioCreatedEventData : PlayStreamEventBase
{
public string CreatorAuthenticationId;
public string CreatorPlayFabId;
public string StudioName;
}
public class StudioUserAddedEventData : PlayStreamEventBase
{
public string AuthenticationId;
public AuthenticationProvider? AuthenticationProvider;
public string AuthenticationProviderId;
public string Email;
public string InvitationId;
public string PlayFabId;
public List<string> StudioPermissions;
public Dictionary<string,string> TitlePermissions;
}
public class StudioUserInvitedEventData : PlayStreamEventBase
{
public AuthenticationProvider? AuthenticationProvider;
public string AuthenticationProviderId;
public string Email;
public DateTime? InvitationExpires;
public string InvitationId;
public bool InvitedExistingUser;
public string InvitorPlayFabId;
public List<string> StudioPermissions;
public Dictionary<string,string> TitlePermissions;
}
public class StudioUserRemovedEventData : PlayStreamEventBase
{
public string AuthenticationId;
public AuthenticationProvider? AuthenticationProvider;
public string AuthenticationProviderId;
public string PlayFabId;
public List<string> StudioPermissions;
public Dictionary<string,string> TitlePermissions;
}
#endregion none
#region character
public class CharacterConsumedItemEventData : PlayStreamEventBase
{
public string CatalogVersion;
public string ItemId;
public string ItemInstanceId;
public string PlayerId;
public uint PreviousUsesRemaining;
public string TitleId;
public uint UsesRemaining;
}
public class CharacterCreatedEventData : PlayStreamEventBase
{
public string CharacterName;
public DateTime Created;
public string PlayerId;
public string TitleId;
}
public class CharacterInventoryItemAddedEventData : PlayStreamEventBase
{
public string Annotation;
public List<string> BundleContents;
public string CatalogVersion;
public string Class;
public string CouponCode;
public string DisplayName;
public DateTime? Expiration;
public string InstanceId;
public string ItemId;
public string PlayerId;
public uint? RemainingUses;
public string TitleId;
}
public class CharacterStatisticChangedEventData : PlayStreamEventBase
{
public string PlayerId;
public string StatisticName;
public int? StatisticPreviousValue;
public int StatisticValue;
public string TitleId;
public uint Version;
}
public class CharacterVCPurchaseEventData : PlayStreamEventBase
{
public string CatalogVersion;
public string CurrencyCode;
public string ItemId;
public string PlayerId;
public string PurchaseId;
public int Quantity;
public string StoreId;
public string TitleId;
public uint UnitPrice;
}
public class CharacterVirtualCurrencyBalanceChangedEventData : PlayStreamEventBase
{
public string OrderId;
public string PlayerId;
public string TitleId;
public int VirtualCurrencyBalance;
public string VirtualCurrencyName;
public int VirtualCurrencyPreviousBalance;
}
#endregion character
#region partner
public class DisplayNameFilteredEventData : PlayStreamEventBase
{
public string DisplayName;
public string PlayerId;
}
public class PlayerDisplayNameFilteredEventData : PlayStreamEventBase
{
public string DisplayName;
public string TitleId;
}
public class PlayerPhotonSessionAuthenticatedEventData : PlayStreamEventBase
{
public string PhotonApplicationId;
public PhotonServicesEnum? PhotonApplicationType;
public string TitleId;
}
#endregion partner
#region player
public class PlayerAdCampaignAttributionEventData : PlayStreamEventBase
{
public string CampaignId;
public string TitleId;
}
public class PlayerAdClosedEventData : PlayStreamEventBase
{
public string AdPlacementId;
public string AdPlacementName;
public string AdUnit;
public string RewardId;
public string RewardName;
public string TitleId;
}
public class PlayerAddedTitleEventData : PlayStreamEventBase
{
public string DisplayName;
public LoginIdentityProvider? Platform;
public string PlatformUserId;
public string TitleId;
}
public class PlayerAdEndedEventData : PlayStreamEventBase
{
public string AdPlacementId;
public string AdPlacementName;
public string AdUnit;
public string RewardId;
public string RewardName;
public string TitleId;
}
public class PlayerAdOpenedEventData : PlayStreamEventBase
{
public string AdPlacementId;
public string AdPlacementName;
public string AdUnit;
public string RewardId;
public string RewardName;
public string TitleId;
}
public class PlayerAdRewardedEventData : PlayStreamEventBase
{
public List<string> ActionGroupDebugMessages;
public string AdPlacementId;
public string AdPlacementName;
public string AdUnit;
public string RewardId;
public string RewardName;
public string TitleId;
public int? ViewsRemainingThisPeriod;
}
public class PlayerAdRewardValuedEventData : PlayStreamEventBase
{
public string AdPlacementId;
public string AdPlacementName;
public string AdUnit;
public double RevenueShare;
public string RewardId;
public string RewardName;
public string TitleId;
}
public class PlayerAdStartedEventData : PlayStreamEventBase
{
public string AdPlacementId;
public string AdPlacementName;
public string AdUnit;
public string RewardId;
public string RewardName;
public string TitleId;
}
public class PlayerBannedEventData : PlayStreamEventBase
{
public DateTime? BanExpiration;
public string BanId;
public string BanReason;
public bool PermanentBan;
public string TitleId;
}
public class PlayerChangedAvatarEventData : PlayStreamEventBase
{
public string ImageUrl;
public string PreviousImageUrl;
public string TitleId;
}
public class PlayerCompletedPasswordResetEventData : PlayStreamEventBase
{
public string CompletedFromIPAddress;
public DateTime CompletionTimestamp;
public PasswordResetInitiationSource? InitiatedBy;
public string InitiatedFromIPAddress;
public DateTime InitiationTimestamp;
public DateTime LinkExpiration;
public string PasswordResetId;
public string RecoveryEmailAddress;
public string TitleId;
}
public class PlayerConsumedItemEventData : PlayStreamEventBase
{
public string CatalogVersion;
public string ItemId;
public string ItemInstanceId;
public uint PreviousUsesRemaining;
public string TitleId;
public uint UsesRemaining;
}
public class PlayerCreatedEventData : PlayStreamEventBase
{
public DateTime Created;
public string PublisherId;
public string TitleId;
}
public class PlayerDisplayNameChangedEventData : PlayStreamEventBase
{
public string DisplayName;
public string PreviousDisplayName;
public string TitleId;
}
public class PlayerExecutedCloudScriptEventData : PlayStreamEventBase
{
public ExecuteCloudScriptResult CloudScriptExecutionResult;
public string FunctionName;
public string TitleId;
}
public class PlayerInventoryItemAddedEventData : PlayStreamEventBase
{
public string Annotation;
public List<string> BundleContents;
public string CatalogVersion;
public string Class;
public string CouponCode;
public string DisplayName;
public DateTime? Expiration;
public string InstanceId;
public string ItemId;
public uint? RemainingUses;
public string TitleId;
}
public class PlayerJoinedLobbyEventData : PlayStreamEventBase
{
public string GameMode;
public string LobbyId;
public string Region;
public string ServerBuildVersion;
public string ServerHost;
public string ServerHostInstanceId;
public string ServerIPV6Address;
public uint ServerPort;
public string TitleId;
}
public class PlayerLeftLobbyEventData : PlayStreamEventBase
{
public string GameMode;
public string LobbyId;
public string Region;
public string ServerBuildVersion;
public string ServerHost;
public string ServerHostInstanceId;
public string ServerIPV6Address;
public uint ServerPort;
public string TitleId;
}
public class PlayerLinkedAccountEventData : PlayStreamEventBase
{
public string Email;
public LoginIdentityProvider? Origination;
public string OriginationUserId;
public string TitleId;
public string Username;
}
public class PlayerLoggedInEventData : PlayStreamEventBase
{
public EventLocation Location;
public LoginIdentityProvider? Platform;
public string PlatformUserId;
public string TitleId;
}
public class PlayerMatchedWithLobbyEventData : PlayStreamEventBase
{
public string GameMode;
public string LobbyId;
public string Region;
public string ServerBuildVersion;
public string ServerHost;
public string ServerHostInstanceId;
public string ServerIPV6Address;
public uint ServerPort;
public string TitleId;
}
public class PlayerPasswordResetLinkSentEventData : PlayStreamEventBase
{
public PasswordResetInitiationSource? InitiatedBy;
public string InitiatedFromIPAddress;
public DateTime LinkExpiration;
public string PasswordResetId;
public string RecoveryEmailAddress;
public string TitleId;
}
public class PlayerPayForPurchaseEventData : PlayStreamEventBase
{
public string OrderId;
public string ProviderData;
public string ProviderName;
public string ProviderToken;
public string PurchaseConfirmationPageURL;
public string PurchaseCurrency;
public uint PurchasePrice;
public TransactionStatus? Status;
public string TitleId;
public Dictionary<string,int> VirtualCurrencyBalances;
public Dictionary<string,int> VirtualCurrencyGrants;
}
public class PlayerRankedOnLeaderboardVersionEventData : PlayStreamEventBase
{
public LeaderboardSource LeaderboardSource;
public uint Rank;
public string TitleId;
public int Value;
public uint Version;
public LeaderboardVersionChangeBehavior? VersionChangeBehavior;
}
public class PlayerRealMoneyPurchaseEventData : PlayStreamEventBase
{
public string OrderId;
public uint OrderTotal;
public string PaymentProvider;
public PaymentType? PaymentType;
public List<string> PurchasedProduct;
public string TitleId;
public Currency? TransactionCurrency;
public string TransactionId;
public uint? TransactionTotal;
}
public class PlayerReceiptValidationEventData : PlayStreamEventBase
{
public string Error;
public string PaymentProvider;
public PaymentType? PaymentType;
public string ReceiptContent;
public string TitleId;
public bool Valid;
}
public class PlayerRedeemedCouponEventData : PlayStreamEventBase
{
public string CouponCode;
public List<CouponGrantedInventoryItem> GrantedInventoryItems;
public string TitleId;
}
public class PlayerRegisteredPushNotificationsEventData : PlayStreamEventBase
{
public string DeviceToken;
public PushNotificationPlatform? Platform;
public string TitleId;
}
public class PlayerRemovedTitleEventData : PlayStreamEventBase
{
public string TitleId;
}
public class PlayerReportedAsAbusiveEventData : PlayStreamEventBase
{
public string Comment;
public string ReportedByPlayer;
public string TitleId;
}
public class PlayerSetProfilePropertyEventData : PlayStreamEventBase
{
public PlayerProfileProperty? Property;
public string TitleId;
public object Value;
}
public class PlayerStartPurchaseEventData : PlayStreamEventBase
{
public string CatalogVersion;
public List<CartItem> Contents;
public string OrderId;
public string StoreId;
public string TitleId;
}
public class PlayerStatisticChangedEventData : PlayStreamEventBase
{
public StatisticAggregationMethod? AggregationMethod;
public uint StatisticId;
public string StatisticName;
public int? StatisticPreviousValue;
public int StatisticValue;
public string TitleId;
public uint Version;
}
public class PlayerStatisticDeletedEventData : PlayStreamEventBase
{
public uint StatisticId;
public string StatisticName;
public int? StatisticPreviousValue;
public string TitleId;
public uint Version;
}
public class PlayerTagAddedEventData : PlayStreamEventBase
{
public string Namespace;
public string TagName;
public string TitleId;
}
public class PlayerTagRemovedEventData : PlayStreamEventBase
{
public string Namespace;
public string TagName;
public string TitleId;
}
public class PlayerTriggeredActionExecutedCloudScriptEventData : PlayStreamEventBase
{
public ExecuteCloudScriptResult CloudScriptExecutionResult;
public string FunctionName;
public string TitleId;
public object TriggeringEventData;
public string TriggeringEventName;
public PlayerProfile TriggeringPlayer;
}
public class PlayerUnlinkedAccountEventData : PlayStreamEventBase
{
public LoginIdentityProvider? Origination;
public string OriginationUserId;
public string TitleId;
}
public class PlayerVCPurchaseEventData : PlayStreamEventBase
{
public string CatalogVersion;
public string CurrencyCode;
public string ItemId;
public string PurchaseId;
public int Quantity;
public string StoreId;
public string TitleId;
public uint UnitPrice;
}
public class PlayerVerifiedContactEmailEventData : PlayStreamEventBase
{
public string EmailAddress;
public string EmailName;
public string TitleId;
}
public class PlayerVirtualCurrencyBalanceChangedEventData : PlayStreamEventBase
{
public string OrderId;
public string TitleId;
public int VirtualCurrencyBalance;
public string VirtualCurrencyName;
public int VirtualCurrencyPreviousBalance;
}
#endregion player
#region session
public class GameLobbyEndedEventData : PlayStreamEventBase
{
public string GameMode;
public string Region;
public string ServerBuildVersion;
public string ServerHost;
public string ServerHostInstanceId;
public string ServerIPV6Address;
public uint ServerPort;
public Dictionary<string,string> Tags;
public string TitleId;
}
public class GameLobbyStartedEventData : PlayStreamEventBase
{
public string CustomCommandLineData;
public string CustomMatchmakerEndpoint;
public string GameMode;
public string GameServerData;
public int? MaxPlayers;
public string Region;
public string ServerBuildVersion;
public string ServerHost;
public string ServerHostInstanceId;
public string ServerIPV6Address;
public uint ServerPort;
public Dictionary<string,string> Tags;
public string TitleId;
}
public class GameServerHostStartedEventData : PlayStreamEventBase
{
public string InstanceId;
public string InstanceProvider;
public string InstanceType;
public string Region;
public string ServerBuildVersion;
public string ServerHost;
public string ServerIPV6Address;
public DateTime StartTime;
public string TitleId;
}
public class GameServerHostStoppedEventData : PlayStreamEventBase
{
public string InstanceId;
public string InstanceProvider;
public string InstanceType;
public string Region;
public string ServerBuildVersion;
public string ServerHost;
public string ServerIPV6Address;
public DateTime StartTime;
public GameServerHostStopReason? StopReason;
public DateTime StopTime;
public string TitleId;
}
public class SessionEndedEventData : PlayStreamEventBase
{
public bool Crashed;
public DateTime EndTime;
public double? KilobytesWritten;
public double SessionLengthMs;
public string TitleId;
public string UserId;
}
public class SessionStartedEventData : PlayStreamEventBase
{
public string TemporaryWriteUrl;
public string TitleId;
}
#endregion session
#region title
public class TitleAbortedTaskEventData : PlayStreamEventBase
{
public string DeveloperId;
public string TaskInstanceId;
public string UserId;
}
public class TitleAddedCloudScriptEventData : PlayStreamEventBase
{
public string DeveloperId;
public bool Published;
public int Revision;
public List<string> ScriptNames;
public string UserId;
public int Version;
}
public class TitleAddedGameBuildEventData : PlayStreamEventBase
{
public string BuildId;
public string DeveloperId;
public int MaxGamesPerHost;
public int MinFreeGameSlots;
public List<Region> Regions;
public string UserId;
}
public class TitleAPISettingsChangedEventData : PlayStreamEventBase
{
public string DeveloperId;
public APISettings PreviousSettingsValues;
public APISettings SettingsValues;
public string UserId;
}
public class TitleCatalogUpdatedEventData : PlayStreamEventBase
{
public string CatalogVersion;
public bool Deleted;
public string DeveloperId;
public string UserId;
}
public class TitleClientRateLimitedEventData : PlayStreamEventBase
{
public string AlertEventId;
public AlertStates? AlertState;
public string API;
public string ErrorCode;
public string GraphUrl;
public AlertLevel? Level;
}
public class TitleCompletedTaskEventData : PlayStreamEventBase
{
public DateTime? AbortedAt;
public bool IsAborted;
public TaskInstanceStatus? Result;
public object Summary;
public string TaskInstanceId;
public string TaskType;
}
public class TitleCreatedTaskEventData : PlayStreamEventBase
{
public string DeveloperId;
public NameIdentifier ScheduledTask;
public string UserId;
}
public class TitleDeletedEventData : PlayStreamEventBase
{
}
public class TitleDeletedTaskEventData : PlayStreamEventBase
{
public string DeveloperId;
public NameIdentifier ScheduledTask;
public string UserId;
}
public class TitleExceededLimitEventData : PlayStreamEventBase
{
public Dictionary<string,object> Details;
public string LimitDisplayName;
public string LimitId;
public double LimitValue;
public MetricUnit? Unit;
public double Value;
}
public class TitleHighErrorRateEventData : PlayStreamEventBase
{
public string AlertEventId;
public AlertStates? AlertState;
public string API;
public string ErrorCode;
public string GraphUrl;
public AlertLevel? Level;
}
public class TitleInitiatedPlayerPasswordResetEventData : PlayStreamEventBase
{
public string DeveloperId;
public string PasswordResetId;
public string PlayerId;
public string PlayerRecoveryEmailAddress;
public string UserId;
}
public class TitleLimitChangedEventData : PlayStreamEventBase
{
public string LimitDisplayName;
public string LimitId;
public double? PreviousPriceUSD;
public double? PreviousValue;
public double? PriceUSD;
public string TransactionId;
public MetricUnit? Unit;
public double? Value;
}
public class TitleModifiedGameBuildEventData : PlayStreamEventBase
{
public string BuildId;
public string DeveloperId;
public int MaxGamesPerHost;
public int MinFreeGameSlots;
public List<Region> Regions;
public string UserId;
}
public class TitleNewsUpdatedEventData : PlayStreamEventBase
{
public DateTime DateCreated;
public string NewsId;
public string NewsTitle;
public NewsStatus? Status;
}
public class TitlePermissionsPolicyChangedEventData : PlayStreamEventBase
{
public string DeveloperId;
public string NewPolicy;
public string PolicyName;
public string UserId;
}
public class TitleProfileViewConstraintsChangedEventData : PlayStreamEventBase
{
public string DeveloperId;
public string PreviousProfileViewConstraints;
public string ProfileType;
public string ProfileViewConstraints;
public string UserId;
}
public class TitlePublishedCloudScriptEventData : PlayStreamEventBase
{
public string DeveloperId;
public int Revision;
public string UserId;
}
public class TitleRequestedLimitChangeEventData : PlayStreamEventBase
{
public string DeveloperId;
public string LevelName;
public string LimitDisplayName;
public string LimitId;
public string PreviousLevelName;
public double? PreviousPriceUSD;
public double? PreviousValue;
public double? PriceUSD;
public string TransactionId;
public MetricUnit? Unit;
public string UserId;
public double? Value;
}
public class TitleScheduledCloudScriptExecutedEventData : PlayStreamEventBase
{
public ExecuteCloudScriptResult CloudScriptExecutionResult;
public string FunctionName;
public NameId ScheduledTask;
}
public class TitleSecretKeyEventData : PlayStreamEventBase
{
public bool? Deleted;
public string DeveloperId;
public bool? Disabled;
public DateTime? ExpiryDate;
public string SecretKeyId;
public string SecretKeyName;
public string UserId;
}
public class TitleStartedTaskEventData : PlayStreamEventBase
{
public string DeveloperId;
public object Parameter;
public string ScheduledByUserId;
public NameIdentifier ScheduledTask;
public string TaskInstanceId;
public string TaskType;
public string UserId;
}
public class TitleStatisticVersionChangedEventData : PlayStreamEventBase
{
public StatisticResetIntervalOption? ScheduledResetInterval;
public DateTime? ScheduledResetTime;
public string StatisticName;
public uint StatisticVersion;
}
public class TitleStoreUpdatedEventData : PlayStreamEventBase
{
public string CatalogVersion;
public bool Deleted;
public string DeveloperId;
public string StoreId;
public string UserId;
}
public class TitleUpdatedTaskEventData : PlayStreamEventBase
{
public string DeveloperId;
public bool HasRenamed;
public NameIdentifier ScheduledTask;
public string UserId;
}
#endregion title
public enum OperationTypes
{
Created,
Updated,
Deleted,
None
}
[Serializable]
public class ObjectSet
{
/// <summary>
/// The name of this object.
/// </summary>
public string Name;
/// <summary>
/// The JSON Object that was last set on the profile.
/// </summary>
public object Object;
/// <summary>
/// The operation that was performed.
/// </summary>
public OperationTypes? Operation;
}
public enum PlayerProfileProperty
{
TotalValueToDateInUSD,
PlayerValuesToDate
}
public enum AuthenticationProvider
{
PlayFab,
SAML
}
public enum TransactionStatus
{
CreateCart,
Init,
Approved,
Succeeded,
FailedByProvider,
DisputePending,
RefundPending,
Refunded,
RefundFailed,
ChargedBack,
FailedByUber,
FailedByPlayFab,
Revoked,
TradePending,
Traded,
Upgraded,
StackPending,
Stacked,
Other,
Failed
}
[Serializable]
public class CartItem
{
/// <summary>
/// Description of the catalog item.
/// </summary>
public string Description;
/// <summary>
/// Display name for the catalog item.
/// </summary>
public string DisplayName;
/// <summary>
/// Class name to which catalog item belongs.
/// </summary>
public string ItemClass;
/// <summary>
/// Unique identifier for the catalog item.
/// </summary>
public string ItemId;
/// <summary>
/// Unique instance identifier for this catalog item.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Cost of the catalog item for each applicable real world currency.
/// </summary>
public Dictionary<string,uint> RealCurrencyPrices;
/// <summary>
/// Amount of each applicable virtual currency which will be received as a result of purchasing this catalog item.
/// </summary>
public Dictionary<string,uint> VCAmount;
/// <summary>
/// Cost of the catalog item for each applicable virtual currency.
/// </summary>
public Dictionary<string,uint> VirtualCurrencyPrices;
}
public enum GameServerHostStopReason
{
Other,
ExcessCapacity,
LimitExceeded,
BuildNotActiveInRegion,
Unresponsive
}
public enum PaymentType
{
Purchase,
ReceiptValidation
}
public enum LeaderboardVersionChangeBehavior
{
ResetValues
}
/// <summary>
/// Statistic used as the source of leaderboard values.
/// </summary>
[Serializable]
public class StatisticLeaderboardSource
{
/// <summary>
/// Unique ID of the statistic.
/// </summary>
public uint StatisticId;
/// <summary>
/// Name of the statistic.
/// </summary>
public string StatisticName;
}
/// <summary>
/// The source of values for the leaderboard. The properties are mutually exclusive - only one of them will be set and the
/// rest will be null.
/// </summary>
[Serializable]
public class LeaderboardSource
{
/// <summary>
/// Statistic associated with the leaderboard.
/// </summary>
public StatisticLeaderboardSource Statistic;
}
public enum LoginIdentityProvider
{
Unknown,
PlayFab,
Custom,
GameCenter,
GooglePlay,
Steam,
XBoxLive,
PSN,
Kongregate,
Facebook,
IOSDevice,
AndroidDevice,
Twitch,
WindowsHello
}
public enum PasswordResetInitiationSource
{
Self,
Admin
}
[Serializable]
public class CouponGrantedInventoryItem
{
/// <summary>
/// Catalog version of the inventory item.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Unique instance ID of the inventory item.
/// </summary>
public string InstanceId;
/// <summary>
/// Catalog item ID of the inventory item.
/// </summary>
public string ItemId;
}
public enum Currency
{
AED,
AFN,
ALL,
AMD,
ANG,
AOA,
ARS,
AUD,
AWG,
AZN,
BAM,
BBD,
BDT,
BGN,
BHD,
BIF,
BMD,
BND,
BOB,
BRL,
BSD,
BTN,
BWP,
BYR,
BZD,
CAD,
CDF,
CHF,
CLP,
CNY,
COP,
CRC,
CUC,
CUP,
CVE,
CZK,
DJF,
DKK,
DOP,
DZD,
EGP,
ERN,
ETB,
EUR,
FJD,
FKP,
GBP,
GEL,
GGP,
GHS,
GIP,
GMD,
GNF,
GTQ,
GYD,
HKD,
HNL,
HRK,
HTG,
HUF,
IDR,
ILS,
IMP,
INR,
IQD,
IRR,
ISK,
JEP,
JMD,
JOD,
JPY,
KES,
KGS,
KHR,
KMF,
KPW,
KRW,
KWD,
KYD,
KZT,
LAK,
LBP,
LKR,
LRD,
LSL,
LYD,
MAD,
MDL,
MGA,
MKD,
MMK,
MNT,
MOP,
MRO,
MUR,
MVR,
MWK,
MXN,
MYR,
MZN,
NAD,
NGN,
NIO,
NOK,
NPR,
NZD,
OMR,
PAB,
PEN,
PGK,
PHP,
PKR,
PLN,
PYG,
QAR,
RON,
RSD,
RUB,
RWF,
SAR,
SBD,
SCR,
SDG,
SEK,
SGD,
SHP,
SLL,
SOS,
SPL,
SRD,
STD,
SVC,
SYP,
SZL,
THB,
TJS,
TMT,
TND,
TOP,
TRY,
TTD,
TVD,
TWD,
TZS,
UAH,
UGX,
USD,
UYU,
UZS,
VEF,
VND,
VUV,
WST,
XAF,
XCD,
XDR,
XOF,
XPF,
YER,
ZAR,
ZMW,
ZWD
}
[Serializable]
public class LogStatement
{
/// <summary>
/// Optional object accompanying the message as contextual information
/// </summary>
public object Data;
/// <summary>
/// 'Debug', 'Info', or 'Error'
/// </summary>
public string Level;
public string Message;
}
[Serializable]
public class ScriptExecutionError
{
/// <summary>
/// Error code, such as CloudScriptNotFound, JavascriptException, CloudScriptFunctionArgumentSizeExceeded,
/// CloudScriptAPIRequestCountExceeded, CloudScriptAPIRequestError, or CloudScriptHTTPRequestError
/// </summary>
public string Error;
/// <summary>
/// Details about the error
/// </summary>
public string Message;
/// <summary>
/// Point during the execution of the script at which the error occurred, if any
/// </summary>
public string StackTrace;
}
[Serializable]
public class ExecuteCloudScriptResult
{
/// <summary>
/// Number of PlayFab API requests issued by the CloudScript function
/// </summary>
public int APIRequestsIssued;
/// <summary>
/// Information about the error, if any, that occurred during execution
/// </summary>
public ScriptExecutionError Error;
public double ExecutionTimeSeconds;
/// <summary>
/// The name of the function that executed
/// </summary>
public string FunctionName;
/// <summary>
/// The object returned from the CloudScript function, if any
/// </summary>
public object FunctionResult;
/// <summary>
/// Flag indicating if the FunctionResult was too large and was subsequently dropped from this event. This only occurs if
/// the total event size is larger than 350KB.
/// </summary>
public bool? FunctionResultTooLarge;
/// <summary>
/// Number of external HTTP requests issued by the CloudScript function
/// </summary>
public int HttpRequestsIssued;
/// <summary>
/// Entries logged during the function execution. These include both entries logged in the function code using log.info()
/// and log.error() and error entries for API and HTTP request failures.
/// </summary>
public List<LogStatement> Logs;
/// <summary>
/// Flag indicating if the logs were too large and were subsequently dropped from this event. This only occurs if the total
/// event size is larger than 350KB after the FunctionResult was removed.
/// </summary>
public bool? LogsTooLarge;
public uint MemoryConsumedBytes;
/// <summary>
/// Processor time consumed while executing the function. This does not include time spent waiting on API calls or HTTP
/// requests.
/// </summary>
public double ProcessorTimeSeconds;
/// <summary>
/// The revision of the CloudScript that executed
/// </summary>
public int Revision;
}
public enum ContinentCode
{
AF,
AN,
AS,
EU,
NA,
OC,
SA
}
public enum CountryCode
{
AF,
AX,
AL,
DZ,
AS,
AD,
AO,
AI,
AQ,
AG,
AR,
AM,
AW,
AU,
AT,
AZ,
BS,
BH,
BD,
BB,
BY,
BE,
BZ,
BJ,
BM,
BT,
BO,
BQ,
BA,
BW,
BV,
BR,
IO,
BN,
BG,
BF,
BI,
KH,
CM,
CA,
CV,
KY,
CF,
TD,
CL,
CN,
CX,
CC,
CO,
KM,
CG,
CD,
CK,
CR,
CI,
HR,
CU,
CW,
CY,
CZ,
DK,
DJ,
DM,
DO,
EC,
EG,
SV,
GQ,
ER,
EE,
ET,
FK,
FO,
FJ,
FI,
FR,
GF,
PF,
TF,
GA,
GM,
GE,
DE,
GH,
GI,
GR,
GL,
GD,
GP,
GU,
GT,
GG,
GN,
GW,
GY,
HT,
HM,
VA,
HN,
HK,
HU,
IS,
IN,
ID,
IR,
IQ,
IE,
IM,
IL,
IT,
JM,
JP,
JE,
JO,
KZ,
KE,
KI,
KP,
KR,
KW,
KG,
LA,
LV,
LB,
LS,
LR,
LY,
LI,
LT,
LU,
MO,
MK,
MG,
MW,
MY,
MV,
ML,
MT,
MH,
MQ,
MR,
MU,
YT,
MX,
FM,
MD,
MC,
MN,
ME,
MS,
MA,
MZ,
MM,
NA,
NR,
NP,
NL,
NC,
NZ,
NI,
NE,
NG,
NU,
NF,
MP,
NO,
OM,
PK,
PW,
PS,
PA,
PG,
PY,
PE,
PH,
PN,
PL,
PT,
PR,
QA,
RE,
RO,
RU,
RW,
BL,
SH,
KN,
LC,
MF,
PM,
VC,
WS,
SM,
ST,
SA,
SN,
RS,
SC,
SL,
SG,
SX,
SK,
SI,
SB,
SO,
ZA,
GS,
SS,
ES,
LK,
SD,
SR,
SJ,
SZ,
SE,
CH,
SY,
TW,
TJ,
TZ,
TH,
TL,
TG,
TK,
TO,
TT,
TN,
TR,
TM,
TC,
TV,
UG,
UA,
AE,
GB,
US,
UM,
UY,
UZ,
VU,
VE,
VN,
VG,
VI,
WF,
EH,
YE,
ZM,
ZW
}
[Serializable]
public class PlayerLocation
{
/// <summary>
/// City of the player's geographic location.
/// </summary>
public string City;
/// <summary>
/// The two-character continent code for this location
/// </summary>
public ContinentCode ContinentCode;
/// <summary>
/// The two-character ISO 3166-1 country code for the country associated with the location
/// </summary>
public CountryCode CountryCode;
/// <summary>
/// Latitude coordinate of the player's geographic location.
/// </summary>
public double? Latitude;
/// <summary>
/// Longitude coordinate of the player's geographic location.
/// </summary>
public double? Longitude;
}
[Serializable]
public class AdCampaignAttribution
{
/// <summary>
/// UTC time stamp of attribution
/// </summary>
public DateTime AttributedAt;
/// <summary>
/// Attribution campaign identifier
/// </summary>
public string CampaignId;
/// <summary>
/// Attribution network name
/// </summary>
public string Platform;
}
public enum PushNotificationPlatform
{
ApplePushNotificationService,
GoogleCloudMessaging
}
[Serializable]
public class PushNotificationRegistration
{
/// <summary>
/// Notification configured endpoint
/// </summary>
public string NotificationEndpointARN;
/// <summary>
/// Push notification platform
/// </summary>
public PushNotificationPlatform? Platform;
}
[Serializable]
public class PlayerLinkedAccount
{
/// <summary>
/// Linked account's email
/// </summary>
public string Email;
/// <summary>
/// Authentication platform
/// </summary>
public LoginIdentityProvider? Platform;
/// <summary>
/// Platform user identifier
/// </summary>
public string PlatformUserId;
/// <summary>
/// Linked account's username
/// </summary>
public string Username;
}
[Serializable]
public class PlayerStatistic
{
/// <summary>
/// Statistic ID
/// </summary>
public string Id;
/// <summary>
/// Statistic name
/// </summary>
public string Name;
/// <summary>
/// Current statistic value
/// </summary>
public int StatisticValue;
/// <summary>
/// Statistic version (0 if not a versioned statistic)
/// </summary>
public int StatisticVersion;
}
public enum EmailVerificationStatus
{
Unverified,
Pending,
Confirmed
}
[Serializable]
public class ContactEmailInfo
{
/// <summary>
/// The email address
/// </summary>
public string EmailAddress;
/// <summary>
/// The name of the email info data
/// </summary>
public string Name;
/// <summary>
/// The verification status of the email
/// </summary>
public EmailVerificationStatus? VerificationStatus;
}
[Serializable]
public class PlayerProfile
{
/// <summary>
/// Array of ad campaigns player has been attributed to
/// </summary>
public List<AdCampaignAttribution> AdCampaignAttributions;
/// <summary>
/// Image URL of the player's avatar.
/// </summary>
public string AvatarUrl;
/// <summary>
/// Banned until UTC Date. If permanent ban this is set for 20 years after the original ban date.
/// </summary>
public DateTime? BannedUntil;
/// <summary>
/// Array of contact email addresses associated with the player
/// </summary>
public List<ContactEmailInfo> ContactEmailAddresses;
/// <summary>
/// Player record created
/// </summary>
public DateTime? Created;
/// <summary>
/// Player Display Name
/// </summary>
public string DisplayName;
/// <summary>
/// Last login
/// </summary>
public DateTime? LastLogin;
/// <summary>
/// Array of third party accounts linked to this player
/// </summary>
public List<PlayerLinkedAccount> LinkedAccounts;
/// <summary>
/// Dictionary of player's locations by type.
/// </summary>
public Dictionary<string,PlayerLocation> Locations;
/// <summary>
/// Player account origination
/// </summary>
public LoginIdentityProvider? Origination;
/// <summary>
/// PlayFab Player ID
/// </summary>
public string PlayerId;
/// <summary>
/// Array of player statistics
/// </summary>
public List<PlayerStatistic> PlayerStatistics;
/// <summary>
/// Publisher this player belongs to
/// </summary>
public string PublisherId;
/// <summary>
/// Array of configured push notification end points
/// </summary>
public List<PushNotificationRegistration> PushNotificationRegistrations;
/// <summary>
/// Dictionary of player's statistics using only the latest version's value
/// </summary>
public Dictionary<string,int> Statistics;
/// <summary>
/// List of player's tags for segmentation.
/// </summary>
public List<string> Tags;
/// <summary>
/// Title ID this profile applies to
/// </summary>
public string TitleId;
/// <summary>
/// A sum of player's total purchases in USD across all currencies.
/// </summary>
public uint? TotalValueToDateInUSD;
/// <summary>
/// Dictionary of player's total purchases by currency.
/// </summary>
public Dictionary<string,uint> ValuesToDate;
/// <summary>
/// Dictionary of player's virtual currency balances
/// </summary>
public Dictionary<string,int> VirtualCurrencyBalances;
}
/// <summary>
/// Identifier by either name or ID. Note that a name may change due to renaming, or reused after being deleted. ID is
/// immutable and unique.
/// </summary>
[Serializable]
public class NameIdentifier
{
public string Id;
public string Name;
}
[Serializable]
public class APISettings
{
/// <summary>
/// Allow game clients to add to virtual currency balances via API.
/// </summary>
public bool AllowClientToAddVirtualCurrency;
/// <summary>
/// Allow game clients to update statistic values via API.
/// </summary>
public bool AllowClientToPostPlayerStatistics;
/// <summary>
/// Allow clients to start multiplayer game sessions via API.
/// </summary>
public bool AllowClientToStartGames;
/// <summary>
/// Allow game clients to subtract from virtual currency balances via API.
/// </summary>
public bool AllowClientToSubtractVirtualCurrency;
/// <summary>
/// Allow players to choose display names that may be in use by other players, i.e. do not enforce uniqueness of display
/// names. Note: if this option is enabled, it cannot be disabled later.
/// </summary>
public bool AllowNonUniquePlayerDisplayNames;
/// <summary>
/// Allow game servers to delete player accounts via API.
/// </summary>
public bool AllowServerToDeleteUsers;
/// <summary>
/// Disable API access by returning errors to all API requests.
/// </summary>
public bool DisableAPIAccess;
/// <summary>
/// Display name randomly-generated suffix length.
/// </summary>
public int? DisplayNameRandomSuffixLength;
/// <summary>
/// Reduce the precision of IP addresses collected from players' devices before they are stored or used to estimate
/// geographic locations.
/// </summary>
public bool EnableClientIPAddressObfuscation;
/// <summary>
/// Require JSON format for data values associated with players, characters, inventories, and shared groups.
/// </summary>
public bool RequireCustomDataJSONFormat;
/// <summary>
/// Multiplayer game sessions are hosted on servers external to PlayFab.
/// </summary>
public bool UseExternalGameServerProvider;
/// <summary>
/// Use payment provider's sandbox mode (if available) for real-money purchases. This can be useful when testing in-game
/// purchasing in order to avoid being charged.
/// </summary>
public bool UseSandboxPayments;
}
public enum TaskInstanceStatus
{
Succeeded,
Starting,
InProgress,
Failed,
Aborted,
Pending
}
public enum StatisticAggregationMethod
{
Last,
Min,
Max,
Sum
}
[Serializable]
public class EventLocation
{
/// <summary>
/// City of the geographic location.
/// </summary>
public string City;
/// <summary>
/// Two-character code representing the continent of geographic location.
/// </summary>
public ContinentCode? ContinentCode;
/// <summary>
/// Two-character ISO 3166-1 code representing the country of the geographic location.
/// </summary>
public CountryCode? CountryCode;
/// <summary>
/// Latitude coordinate of the geographic location.
/// </summary>
public double? Latitude;
/// <summary>
/// Longitude coordinate of the geographic location.
/// </summary>
public double? Longitude;
}
public enum Region
{
USCentral,
USEast,
EUWest,
Singapore,
Japan,
Brazil,
Australia
}
public enum AlertLevel
{
Warn,
Alert,
Critical
}
public enum AlertStates
{
Triggered,
Recovered,
ReTriggered
}
public enum NewsStatus
{
None,
Unpublished,
Published,
Archived
}
public enum MetricUnit
{
Value,
Count,
Percent,
Milliseconds,
Seconds,
Hours,
Days,
Bits,
Bytes,
Kilobytes,
Megabytes,
Gigabytes,
Terabytes,
Bytes_Per_Second,
MonthlyActiveUsers,
EnableDisable
}
public enum StatisticResetIntervalOption
{
Never,
Hour,
Day,
Week,
Month
}
[Serializable]
public class NameId
{
public string Id;
public string Name;
}
public enum PhotonServicesEnum
{
Realtime,
Turnbased,
Chat
}
public enum SourceType
{
Admin,
BackEnd,
GameClient,
GameServer,
Partner
}
[Serializable]
public class PlayStreamEventHistory
{
/// <summary>
/// The ID of the previous event that caused this event to be created by hitting a trigger.
/// </summary>
public string ParentEventId;
/// <summary>
/// The ID of the trigger that caused this event to be created.
/// </summary>
public string ParentTriggerId;
/// <summary>
/// If true, then this event was allowed to trigger subsequent events in a trigger.
/// </summary>
public bool TriggeredEvents;
}
}
| |
#define SQLITE_OS_WIN
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using DWORD = System.UInt64;
using HANDLE = System.IntPtr;
using i64 = System.Int64;
using sqlite3_int64 = System.Int64;
using u32 = System.UInt32;
using u8 = System.Byte;
using System.IO.IsolatedStorage;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2004 May 22
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to windows.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d
**
** $Header: Community.CsharpSqlite/src/os_win_c.cs,v 6604176a7dbe 2010/03/12 23:35:36 Noah $
*************************************************************************
*/
const int INVALID_FILE_ATTRIBUTES = -1;
private static LockingStrategy lockingStrategy = HelperMethods.IsRunningMediumTrust() ? new MediumTrustLockingStrategy() : new LockingStrategy();
public static IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
public partial class sqlite3_file
{
// public HANDLE h; /* Handle for accessing the file */
public int locktype; /* Type of lock currently held on this file */
public int sharedLockByte; /* Randomly chosen byte used as a shared lock */
public DWORD lastErrno; /* The Windows errno from the last I/O error */
public DWORD sectorSize; /* Sector size of the device file is on */
public IsolatedStorageFileStream fs = null;
public void Clear()
{
pMethods = null;
//fs = null;
locktype = 0;
sharedLockByte = 0;
lastErrno = 0;
sectorSize = 0;
}
};
static int sqlite3_os_type = 0;
/*
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
** or WinCE. Return false (zero) for Win95, Win98, or WinME.
**
** Here is an interesting observation: Win95, Win98, and WinME lack
** the LockFileEx() API. But we can still statically link against that
** API as long as we don't call it when running Win95/98/ME. A call to
** this routine is used to determine if the host is Win95/98/ME or
** WinNT/2K/XP so that we will know whether or not we can safely call
** the LockFileEx() API.
*/
static bool isNT()
{
return Environment.OSVersion.Platform >= PlatformID.Win32NT;
}
private static bool ExistsFile(string sFilename)
{
return store.FileExists(sFilename);
}
private static void DeleteFile(string sFilename)
{
store.DeleteFile(sFilename);
}
/*
** Close a file.
**
** It is reported that an attempt to close a handle might sometimes
** fail. This is a very unreasonable result, but windows is notorious
** for being unreasonable so I do not doubt that it might happen. If
** the close fails, we pause for 100 milliseconds and try again. As
** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
** giving up and returning an error.
*/
public static int MX_CLOSE_ATTEMPT = 3;
static int winClose( sqlite3_file id )
{
bool rc;
int cnt = 0;
//sqlite3_file pFile = (sqlite3_file)id;
Debug.Assert( id != null );
do
{
if (id.fs != null)
{
id.fs.Close();
id.fs = null;
}
rc = true;
// rc = CloseHandle(pFile.h);
// if (!rc && ++cnt < MX_CLOSE_ATTEMPT) Thread.Sleep(100); //, 1) );
} while ( !rc && ++cnt < MX_CLOSE_ATTEMPT ); //, 1) );
return rc ? SQLITE_OK : SQLITE_IOERR;
}
/*
** Some microsoft compilers lack this definition.
*/
#if !INVALID_SET_FILE_POINTER
const int INVALID_SET_FILE_POINTER = -1;
#endif
/*
** Read data from a file into a buffer. Return SQLITE_OK if all
** bytes were read successfully and SQLITE_IOERR if anything goes
** wrong.
*/
static int winRead(
sqlite3_file id, /* File to read from */
byte[] pBuf, /* Write content into this buffer */
int amt, /* Number of bytes to read */
sqlite3_int64 offset /* Begin reading at this offset */
)
{
long rc;
// sqlite3_file pFile = id;
long got;
//Debug.Assert( fs != null );
if ( !id.fs.CanRead ) return SQLITE_IOERR_READ;
try
{
rc = id.fs.Seek( offset, SeekOrigin.Begin ); // SetFilePointer(pFile.fs.Name, lowerBits, upperBits, FILE_BEGIN);
}
catch ( Exception e ) // if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR )
{
//pFile.lastErrno = 1;
return SQLITE_FULL;
}
try
{
got = id.fs.Read( pBuf, 0, amt ); // if (!ReadFile(pFile.fs.Name, pBuf, amt, got, 0))
}
catch ( Exception e )
{
//pFile.lastErrno = 1;
return SQLITE_IOERR_READ;
}
if ( got == amt )
{
return SQLITE_OK;
}
else
{
/* Unread parts of the buffer must be zero-filled */
Array.Clear( pBuf, (int)got, (int)( amt - got ) ); // memset(&((char*)pBuf)[got], 0, amt - got);
return SQLITE_IOERR_SHORT_READ;
}
}
/*
** Write data from a buffer into a file. Return SQLITE_OK on success
** or some other error code on failure.
*/
static int winWrite(
sqlite3_file id, /* File to write into */
byte[] pBuf, /* The bytes to be written */
int amt, /* Number of bytes to write */
sqlite3_int64 offset /* Offset into the file to begin writing at */
)
{
int rc;
long wrote = 0;
//Debug.Assert( id != null );
//id.fs.Seek( offset, SeekOrigin.Begin );
id.fs.Seek(offset, SeekOrigin.Begin);
Debug.Assert( amt > 0 );
//wrote = id.fs.Position;
wrote = id.fs.Position;
try
{
Debug.Assert( pBuf.Length >= amt );
//id.fs.Write( pBuf, 0, amt );
id.fs.Write(pBuf, 0, amt);
rc = 1;// Success
//wrote = id.fs.Position - wrote;
wrote = id.fs.Position - wrote;
}
catch ( IOException e )
{
return SQLITE_READONLY;
}
if ( rc == 0 || amt > (int)wrote )
{
id.lastErrno = 1;
return SQLITE_FULL;
}
return SQLITE_OK;
}
/*
** Truncate an open file to a specified size
*/
static int winTruncate( sqlite3_file id, sqlite3_int64 nByte )
{
Debug.Assert( id != null );
try
{
//id.fs.SetLength( nByte );
id.fs.SetLength(nByte);
}
catch ( IOException e )
{
id.lastErrno = 1;
return SQLITE_IOERR_TRUNCATE;
}
return SQLITE_OK;
}
/*
** Make sure all writes to a particular file are committed to disk.
*/
static int winSync( sqlite3_file id, int flags )
{
sqlite3_file pFile = (sqlite3_file)id;
Debug.Assert( id != null );
UNUSED_PARAMETER(flags);
//pFile.fs.Flush();
id.fs.Flush();
return SQLITE_OK;
}
/*
** Determine the current size of a file in bytes
*/
static int sqlite3_fileSize( sqlite3_file id, ref int pSize )
{
Debug.Assert( id != null );
//pSize = id.fs.CanRead ? (int)id.fs.Length : 0;
pSize = id.fs.CanRead ? (int)id.fs.Length : 0;
return SQLITE_OK;
}
/*
** Acquire a reader lock.
** Different API routines are called depending on whether or not this
** is Win95 or WinNT.
*/
static int getReadLock(sqlite3_file pFile)
{
int res = 0;
if (isNT())
{
res = lockingStrategy.SharedLockFile(pFile, SHARED_FIRST, SHARED_SIZE);
}
if (res == 0)
{
pFile.lastErrno = 1;
}
return res;
}
/*
** Undo a readlock
*/
static int unlockReadLock(sqlite3_file pFile)
{
int res = 1;
if (isNT())
{
try
{
lockingStrategy.UnlockFile(pFile, SHARED_FIRST, SHARED_SIZE); // res = UnlockFile(pFilE.h, SHARED_FIRST, 0, SHARED_SIZE, 0);
}
catch (Exception e)
{
res = 0;
}
}
else
{
Debugger.Break(); // res = UnlockFile(pFilE.h, SHARED_FIRST + pFilE.sharedLockByte, 0, 1, 0);
}
if (res == 0)
{
pFile.lastErrno = 1;
}
return res;
}
/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
** (1) SHARED_LOCK
** (2) RESERVED_LOCK
** (3) PENDING_LOCK
** (4) EXCLUSIVE_LOCK
**
** Sometimes when requesting one lock state, additional lock states
** are inserted in between. The locking might fail on one of the later
** transitions leaving the lock state different from what it started but
** still short of its goal. The following chart shows the allowed
** transitions and the inserted intermediate states:
**
** UNLOCKED -> SHARED
** SHARED -> RESERVED
** SHARED -> (PENDING) -> EXCLUSIVE
** RESERVED -> (PENDING) -> EXCLUSIVE
** PENDING -> EXCLUSIVE
**
** This routine will only increase a lock. The winUnlock() routine
** erases all locks at once and returns us immediately to locking level 0.
** It is not possible to lower the locking level one step at a time. You
** must go straight to locking level 0.
*/
static int winLock( sqlite3_file id, int locktype )
{
int rc = SQLITE_OK; /* Return code from subroutines */
int res = 1; /* Result of a windows lock call */
int newLocktype; /* Set pFile.locktype to this value before exiting */
bool gotPendingLock = false;/* True if we acquired a PENDING lock this time */
sqlite3_file pFile = (sqlite3_file)id;
DWORD error = NO_ERROR;
Debug.Assert( id != null );
/* If there is already a lock of this type or more restrictive on the
** OsFile, do nothing. Don't use the end_lock: exit path, as
** sqlite3OsEnterMutex() hasn't been called yet.
*/
if ( pFile.locktype >= locktype )
{
return SQLITE_OK;
}
/* Make sure the locking sequence is correct
*/
Debug.Assert( pFile.locktype != NO_LOCK || locktype == SHARED_LOCK );
Debug.Assert( locktype != PENDING_LOCK );
Debug.Assert( locktype != RESERVED_LOCK || pFile.locktype == SHARED_LOCK );
/* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
** the PENDING_LOCK byte is temporary.
*/
newLocktype = pFile.locktype;
if ( pFile.locktype == NO_LOCK
|| ( ( locktype == EXCLUSIVE_LOCK )
&& ( pFile.locktype == RESERVED_LOCK ) )
)
{
int cnt = 3;
res = 0;
while ( cnt-- > 0 && res == 0 )//(res = LockFile(pFile.fs.SafeFileHandle.DangerousGetHandle().ToInt32(), PENDING_BYTE, 0, 1, 0)) == 0)
{
try
{
lockingStrategy.LockFile( pFile, PENDING_BYTE, 1 );
res = 1;
}
catch ( Exception e )
{
/* Try 3 times to get the pending lock. The pending lock might be
** held by another reader process who will release it momentarily.
*/
Thread.Sleep( 1 );
}
}
gotPendingLock = ( res != 0 );
if ( 0 == res )
{
error = 1;
}
}
/* Acquire a shared lock
*/
if ( locktype == SHARED_LOCK && res != 0 )
{
Debug.Assert( pFile.locktype == NO_LOCK );
res = getReadLock( pFile );
if ( res != 0 )
{
newLocktype = SHARED_LOCK;
}
else
{
error = 1;
}
}
if ( ( locktype == RESERVED_LOCK ) && res != 0 )
{
Debug.Assert( pFile.locktype == SHARED_LOCK );
try
{
lockingStrategy.LockFile( pFile, RESERVED_BYTE, 1 );//res = LockFile(pFile.fs.SafeFileHandle.DangerousGetHandle().ToInt32(), RESERVED_BYTE, 0, 1, 0);
newLocktype = RESERVED_LOCK;
res = 1;
}
catch ( Exception e )
{
res = 0;
error = 1;
}
if ( res != 0 )
{
newLocktype = RESERVED_LOCK;
}
else
{
error = 1;
}
}
/* Acquire a PENDING lock
*/
if ( locktype == EXCLUSIVE_LOCK && res != 0 )
{
newLocktype = PENDING_LOCK;
gotPendingLock = false;
}
/* Acquire an EXCLUSIVE lock
*/
if ( locktype == EXCLUSIVE_LOCK && res != 0 )
{
Debug.Assert( pFile.locktype >= SHARED_LOCK );
res = unlockReadLock( pFile );
try
{
lockingStrategy.LockFile( pFile, SHARED_FIRST, SHARED_SIZE );
newLocktype = EXCLUSIVE_LOCK;
res = 1;
}
catch ( Exception e )
{
res = 0;
}
if ( res != 0 )
{
newLocktype = EXCLUSIVE_LOCK;
}
else
{
error = 1;
getReadLock( pFile );
}
}
/* If we are holding a PENDING lock that ought to be released, then
** release it now.
*/
if ( gotPendingLock && locktype == SHARED_LOCK )
{
lockingStrategy.UnlockFile( pFile, PENDING_BYTE, 1 );
}
/* Update the state of the lock has held in the file descriptor then
** return the appropriate result code.
*/
if ( res != 0 )
{
rc = SQLITE_OK;
}
else
{
pFile.lastErrno = error;
rc = SQLITE_BUSY;
}
pFile.locktype = (u8)newLocktype;
return rc;
}
/*
** This routine checks if there is a RESERVED lock held on the specified
** file by this or any other process. If such a lock is held, return
** non-zero, otherwise zero.
*/
static int winCheckReservedLock( sqlite3_file id, ref int pResOut )
{
//int rc;
//Debug.Assert( id != null );
//if ( id.locktype >= RESERVED_LOCK )
//{
// rc = 1;
//}
//else
//{
// try
// {
// lockingStrategy.LockFile(id, RESERVED_BYTE, 1);
// lockingStrategy.UnlockFile(id, RESERVED_BYTE, 1);
// rc = 1;
// }
// catch ( IOException e )
// { rc = 0; }
// rc = 1 - rc; // !rc
//}
//pResOut = rc;
pResOut = 0;
return SQLITE_OK;
}
/*
** Lower the locking level on file descriptor id to locktype. locktype
** must be either NO_LOCK or SHARED_LOCK.
**
** If the locking level of the file descriptor is already at or below
** the requested locking level, this routine is a no-op.
**
** It is not possible for this routine to fail if the second argument
** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
** might return SQLITE_IOERR;
*/
static int winUnlock( sqlite3_file id, int locktype )
{
int type;
sqlite3_file pFile = (sqlite3_file)id;
int rc = SQLITE_OK;
Debug.Assert( pFile != null );
Debug.Assert( locktype <= SHARED_LOCK );
type = pFile.locktype;
if ( type >= EXCLUSIVE_LOCK )
{
lockingStrategy.UnlockFile( pFile, SHARED_FIRST, SHARED_SIZE ); // UnlockFile(pFilE.h, SHARED_FIRST, 0, SHARED_SIZE, 0);
if ( locktype == SHARED_LOCK && getReadLock( pFile ) == 0 )
{
/* This should never happen. We should always be able to
** reacquire the read lock */
rc = SQLITE_IOERR_UNLOCK;
}
}
if ( type >= RESERVED_LOCK )
{
try
{
lockingStrategy.UnlockFile( pFile, RESERVED_BYTE, 1 );// UnlockFile(pFilE.h, RESERVED_BYTE, 0, 1, 0);
}
catch ( Exception e ) { }
}
if ( locktype == NO_LOCK && type >= SHARED_LOCK )
{
unlockReadLock( pFile );
}
if ( type >= PENDING_LOCK )
{
try
{
lockingStrategy.UnlockFile( pFile, PENDING_BYTE, 1 );// UnlockFile(pFilE.h, PENDING_BYTE, 0, 1, 0);
}
catch ( Exception e )
{ }
}
pFile.locktype = (u8)locktype;
return rc;
}
/*
** Control and query of the open file handle.
*/
static int winFileControl( sqlite3_file id, int op, ref int pArg )
{
switch ( op )
{
case SQLITE_FCNTL_LOCKSTATE:
{
pArg = ( (sqlite3_file)id ).locktype;
return SQLITE_OK;
}
case SQLITE_LAST_ERRNO:
{
pArg = (int)( (sqlite3_file)id ).lastErrno;
return SQLITE_OK;
}
}
return SQLITE_ERROR;
}
/*
** Return the sector size in bytes of the underlying block device for
** the specified file. This is almost always 512 bytes, but may be
** larger for some devices.
**
** SQLite code assumes this function cannot fail. It also assumes that
** if two files are created in the same file-system directory (i.e.
** a database and its journal file) that the sector size will be the
** same for both.
*/
static int winSectorSize( sqlite3_file id )
{
Debug.Assert( id != null );
return (int)( id.sectorSize );
}
/*
** Return a vector of device characteristics.
*/
static int winDeviceCharacteristics( sqlite3_file id )
{
UNUSED_PARAMETER( id );
return 0;
}
/*
** This vector defines all the methods that can operate on an
** sqlite3_file for win32.
*/
static sqlite3_io_methods winIoMethod = new sqlite3_io_methods(
1, /* iVersion */
(dxClose)winClose,
(dxRead)winRead,
(dxWrite)winWrite,
(dxTruncate)winTruncate,
(dxSync)winSync,
(dxFileSize)sqlite3_fileSize,
(dxLock)winLock,
(dxUnlock)winUnlock,
(dxCheckReservedLock)winCheckReservedLock,
(dxFileControl)winFileControl,
(dxSectorSize)winSectorSize,
(dxDeviceCharacteristics)winDeviceCharacteristics
);
/***************************************************************************
** Here ends the I/O methods that form the sqlite3_io_methods object.
**
** The next block of code implements the VFS methods.
****************************************************************************/
/*
** Convert a UTF-8 filename into whatever form the underlying
** operating system wants filenames in. Space to hold the result
** is obtained from malloc and must be freed by the calling
** function.
*/
static string convertUtf8Filename( string zFilename )
{
return zFilename;
}
/*
** Create a temporary file name in zBuf. zBuf must be big enough to
** hold at pVfs.mxPathname characters.
*/
static int getTempname(int nBuf, StringBuilder zBuf)
{
const string zChars = "abcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder zRandom = new StringBuilder(20);
i64 iRandom = 0;
for (int i = 0; i < 20; i++)
{
sqlite3_randomness(1, ref iRandom);
zRandom.Append((char)zChars[(int)(iRandom % (zChars.Length - 1))]);
}
//zBuf.Append(Path.GetTempPath() + SQLITE_TEMP_FILE_PREFIX + zRandom.ToString());
zBuf.Append("db/" + SQLITE_TEMP_FILE_PREFIX + zRandom.ToString());
return SQLITE_OK;
}
/*
** The return value of getLastErrorMsg
** is zero if the error message fits in the buffer, or non-zero
** otherwise (if the message was truncated).
*/
static int getLastErrorMsg( int nBuf, ref string zBuf )
{
zBuf = "Unknown error";
return 0;
}
/*
** Open a file.
*/
static int winOpen(
sqlite3_vfs pVfs, /* Not used */
string zName, /* Name of the file (UTF-8) */
sqlite3_file pFile, /* Write the SQLite file handle here */
int flags, /* Open mode flags */
ref int pOutFlags /* Status return flags */
)
{
if (pFile.fs != null)
return SQLITE_OK;
//HANDLE h;
//pFile.fs = null;
//fs = null;
FileAccess dwDesiredAccess;
FileShare dwShareMode;
FileMode dwCreationDisposition;
string zConverted; /* Filename in OS encoding */
string zUtf8Name = zName; /* Filename in UTF-8 encoding */
StringBuilder zTmpname = new StringBuilder( MAX_PATH + 1 ); /* Buffer used to create temp filename */
Debug.Assert( pFile != null );
UNUSED_PARAMETER( pVfs );
/* If the second argument to this function is NULL, generate a
** temporary file name to use
*/
if ( String.IsNullOrEmpty( zUtf8Name ) )
{
int rc = getTempname( MAX_PATH + 1, zTmpname );
if ( rc != SQLITE_OK )
{
return rc;
}
zUtf8Name = zTmpname.ToString();
}
// /* Convert the filename to the system encoding. */
zConverted = zUtf8Name;// convertUtf8Filename( zUtf8Name );
if ( String.IsNullOrEmpty( zConverted ) )
{
return SQLITE_NOMEM;
}
if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 )
{
dwDesiredAccess = FileAccess.Read | FileAccess.Write; // GENERIC_READ | GENERIC_WRITE;
}
else
{
dwDesiredAccess = FileAccess.Read; // GENERIC_READ;
}
/* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
** created. SQLite doesn't use it to indicate "exclusive access"
** as it is usually understood.
*/
Debug.Assert( 0 == ( flags & SQLITE_OPEN_EXCLUSIVE ) || ( flags & SQLITE_OPEN_CREATE ) != 0 );
if ( ( flags & SQLITE_OPEN_EXCLUSIVE ) != 0 )
{
/* Creates a new file, only if it does not already exist. */
/* If the file exists, it fails. */
dwCreationDisposition = FileMode.CreateNew;// CREATE_NEW;
}
else if ( ( flags & SQLITE_OPEN_CREATE ) != 0 )
{
/* Open existing file, or create if it doesn't exist */
dwCreationDisposition = FileMode.OpenOrCreate;// OPEN_ALWAYS;
}
else
{
/* Opens a file, only if it exists. */
dwCreationDisposition = FileMode.Open;//OPEN_EXISTING;
}
dwShareMode = FileShare.Read | FileShare.Write;// FILE_SHARE_READ | FILE_SHARE_WRITE;
if ( ( flags & SQLITE_OPEN_DELETEONCLOSE ) != 0 )
{
}
else
{
}
/* Reports from the internet are that performance is always
** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
if ( isNT() )
{
int retries = 3;
//while ( ( pFile.fs == null ) && ( retries > 0 ) )
while ((pFile.fs == null) && (retries > 0))
try
{
retries--;
//pFile.fs = new IsolatedStorageFileStream(zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, pFile.store);
pFile.fs = new IsolatedStorageFileStream(zConverted, dwCreationDisposition, dwDesiredAccess, dwShareMode, store);
}
catch ( Exception e )
{
Thread.Sleep( 100 );
}
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
}
//if ( pFile.fs == null
if (pFile.fs == null
||
//!pFile.fs.CanRead
!pFile.fs.CanRead
)
{
if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 )
{
return winOpen( pVfs, zName, pFile,
( ( flags | SQLITE_OPEN_READONLY ) & ~SQLITE_OPEN_READWRITE ), ref pOutFlags );
}
else
{
return SQLITE_CANTOPEN_BKPT();
}
}
if ( ( flags & SQLITE_OPEN_READWRITE ) != 0 )
{
pOutFlags = SQLITE_OPEN_READWRITE;
}
else
{
pOutFlags = SQLITE_OPEN_READONLY;
}
//}
pFile.Clear(); // memset(pFile, 0, sizeof(*pFile));
pFile.pMethods = winIoMethod;
pFile.lastErrno = NO_ERROR;
pFile.sectorSize = (ulong)getSectorSize( pVfs, zUtf8Name );
return SQLITE_OK;
}
/*
** Delete the named file.
**
** Note that windows does not allow a file to be deleted if some other
** process has it open. Sometimes a virus scanner or indexing program
** will open a journal file shortly after it is created in order to do
** whatever it does. While this other process is holding the
** file open, we will be unable to delete it. To work around this
** problem, we delay 100 milliseconds and try to delete again. Up
** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
** up and returning an error.
*/
static int MX_DELETION_ATTEMPTS = 5;
static int winDelete(
sqlite3_vfs pVfs, /* Not used on win32 */
string zFilename, /* Name of file to delete */
int syncDir /* Not used on win32 */
)
{
int cnt = 0;
int rc;
int error;
UNUSED_PARAMETER( pVfs );
UNUSED_PARAMETER( syncDir );
string zConverted = convertUtf8Filename( zFilename );
if ( zConverted == null || zConverted == "" )
{
return SQLITE_NOMEM;
}
if ( isNT() )
{
do
{
if (!ExistsFile(zFilename))
{
rc = SQLITE_IOERR;
break;
}
try
{
DeleteFile( zConverted );
rc = SQLITE_OK;
}
catch ( IOException e )
{
rc = SQLITE_IOERR;
Thread.Sleep( 100 );
}
} while ( rc != SQLITE_OK && ++cnt < MX_DELETION_ATTEMPTS );
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
** Since the ASCII version of these Windows API do not exist for WINCE,
** it's important to not reference them for WINCE builds.
*/
}
else
{
do
{
if (!ExistsFile(zFilename))
{
rc = SQLITE_IOERR;
break;
}
try
{
DeleteFile(zConverted);
rc = SQLITE_OK;
}
catch ( IOException e )
{
rc = SQLITE_IOERR;
Thread.Sleep( 100 );
}
} while ( rc != SQLITE_OK && cnt++ < MX_DELETION_ATTEMPTS );
}
//free(zConverted);
#if SQLITE_DEBUG
OSTRACE2( "DELETE \"%s\"\n", zFilename );
#endif
//return ( ( rc == INVALID_FILE_ATTRIBUTES )
//&& ( error == ERROR_FILE_NOT_FOUND ) ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
return rc;
}
/*
** Check the existence and status of a file.
*/
static int winAccess(
sqlite3_vfs pVfs, /* Not used on win32 */
string zFilename, /* Name of file to check */
int flags, /* Type of test to make on this file */
ref int pResOut /* OUT: Result */
)
{
pResOut = 1;
return SQLITE_OK;
//FileAttributes attr = 0; // DWORD attr;
//int rc = 0;
//UNUSED_PARAMETER( pVfs );
// if (flags == SQLITE_ACCESS_EXISTS)
// {
// pResOut =store.FileExists(zFilename) ? 1 : 0;
// return SQLITE_OK;
// }
// try
// {
// if (store.DirectoryExists(zFilename))
// {
// StringBuilder zTmpname = new StringBuilder(255); /* Buffer used to create temp filename */
// getTempname(256, zTmpname);
// string zTempFilename;
// zTempFilename = zTmpname.ToString();//( SQLITE_TEMP_FILE_PREFIX.Length + 1 );
// try
// {
// IsolatedStorageFileStream fs = store.CreateFile(zTempFilename);
// fs.Close();
// fs = null;
// store.DeleteFile(zTempFilename);
// attr = FileAttributes.Normal;
// }
// catch (IOException e) { attr = FileAttributes.ReadOnly; }
// }
// }
// catch (IOException e)
// {
// }
//// free(zConverted);
//switch ( flags )
//{
// case SQLITE_ACCESS_READ:
// case SQLITE_ACCESS_EXISTS:
// rc = attr != 0 ? 1 : 0;// != INVALID_FILE_ATTRIBUTES;
// break;
// case SQLITE_ACCESS_READWRITE:
// rc = attr == 0 ? 0 : (int)( attr & FileAttributes.ReadOnly ) != 0 ? 0 : 1; //FILE_ATTRIBUTE_READONLY ) == 0;
// break;
// default:
// Debug.Assert( "" == "Invalid flags argument" );
// rc = 0;
// break;
//}
//pResOut = rc;
//return SQLITE_OK;
}
/*
** Turn a relative pathname into a full pathname. Write the full
** pathname into zOut[]. zOut[] will be at least pVfs.mxPathname
** bytes in size.
*/
static int winFullPathname(
sqlite3_vfs pVfs, /* Pointer to vfs object */
string zRelative, /* Possibly relative input path */
int nFull, /* Size of output buffer in bytes */
StringBuilder zFull /* Output buffer */
)
{
zFull.Append(zRelative);
return SQLITE_OK;
int nByte;
string zOut = null;
UNUSED_PARAMETER( nFull );
//convertUtf8Filename(zRelative));
if ( isNT() )
{
try
{
zOut = Path.GetFullPath( zRelative ); // was unicodeToUtf8(zTemp);
}
catch ( IOException e )
{ zOut = zRelative; }
}
else
{
Debugger.Break(); // -- Not Running under NT
}
if ( zOut != null )
{
// sqlite3_snprintf(pVfs.mxPathname, zFull, "%s", zOut);
if ( zFull.Length > pVfs.mxPathname ) zFull.Length = pVfs.mxPathname;
zFull.Append( zOut );
// will happen on exit; was free(zOut);
return SQLITE_OK;
}
else
{
return SQLITE_NOMEM;
}
}
/*
** Get the sector size of the device used to store
** file.
*/
static int getSectorSize(
sqlite3_vfs pVfs,
string zRelative /* UTF-8 file name */
)
{
return SQLITE_DEFAULT_SECTOR_SIZE;
}
//TODO -- Fix This
static HANDLE winDlOpen( sqlite3_vfs vfs, string zFilename ) { return new HANDLE(); }
static int winDlError( sqlite3_vfs vfs, int nByte, ref string zErrMsg ) { return 0; }
static HANDLE winDlSym( sqlite3_vfs vfs, HANDLE data, string zSymbol ) { return new HANDLE(); }
static int winDlClose( sqlite3_vfs vfs, HANDLE data ) { return 0; }
static int winRandomness( sqlite3_vfs pVfs, int nBuf, ref byte[] zBuf )
{
int n = 0;
UNUSED_PARAMETER( pVfs );
byte[] sBuf = BitConverter.GetBytes(System.DateTime.Now.Ticks);
zBuf[0] = sBuf[0];
zBuf[1] = sBuf[1];
zBuf[2] = sBuf[2];
zBuf[3] = sBuf[3];
;// memcpy(&zBuf[n], x, sizeof(x))
n += 16;// sizeof(x);
if ( sizeof( DWORD ) <= nBuf - n )
{
//DWORD pid = GetCurrentProcessId();
u32 processId;
processId = 28376023;
put32bits( zBuf, n, processId);//(memcpy(&zBuf[n], pid, sizeof(pid));
n += 4;// sizeof(pid);
}
if ( sizeof( DWORD ) <= nBuf - n )
{
//DWORD cnt = GetTickCount();
System.DateTime dt = new System.DateTime();
put32bits( zBuf, n, (u32)dt.Ticks );// memcpy(&zBuf[n], cnt, sizeof(cnt));
n += 4;// cnt.Length;
}
if ( sizeof( long ) <= nBuf - n )
{
long i;
i = System.DateTime.UtcNow.Millisecond;// QueryPerformanceCounter(out i);
put32bits( zBuf, n, (u32)( i & 0xFFFFFFFF ) );//memcpy(&zBuf[n], i, sizeof(i));
put32bits( zBuf, n, (u32)( i >> 32 ) );
n += sizeof( long );
}
return n;
}
/*
** Sleep for a little while. Return the amount of time slept.
*/
static int winSleep( sqlite3_vfs pVfs, int microsec )
{
Thread.Sleep( ( microsec + 999 ) / 1000 );
UNUSED_PARAMETER( pVfs );
return ( ( microsec + 999 ) / 1000 ) * 1000;
}
/*
** The following variable, if set to a non-zero value, becomes the result
** returned from sqlite3OsCurrentTime(). This is used for testing.
/*
** Find the current time (in Universal Coordinated Time). Write the
** current time and date as a Julian Day number into prNow and
** return 0. Return 1 if the time and date cannot be found.
*/
static int winCurrentTime( sqlite3_vfs pVfs, ref double prNow )
{
sqlite3_int64 timeW; /* Whole days */
sqlite3_int64 timeF; /* Fractional Days */
/* Number of 100-nanosecond intervals in a single day */
const sqlite3_int64 ntuPerDay =
10000000 * (sqlite3_int64)86400;
/* Number of 100-nanosecond intervals in half of a day */
const sqlite3_int64 ntuPerHalfDay =
10000000 * (sqlite3_int64)43200;
timeW = System.DateTime.UtcNow.ToFileTime();
timeF = timeW % ntuPerDay; /* fractional days (100-nanoseconds) */
timeW = timeW / ntuPerDay; /* whole days */
timeW = timeW + 2305813; /* add whole days (from 2305813.5) */
timeF = timeF + ntuPerHalfDay; /* add half a day (from 2305813.5) */
timeW = timeW + ( timeF / ntuPerDay ); /* add whole day if half day made one */
timeF = timeF % ntuPerDay; /* compute new fractional days */
prNow = (double)timeW + ( (double)timeF / (double)ntuPerDay );
return 0;
}
/*
** The idea is that this function works like a combination of
** GetLastError() and FormatMessage() on windows (or errno and
** strerror_r() on unix). After an error is returned by an OS
** function, SQLite calls this function with zBuf pointing to
** a buffer of nBuf bytes. The OS layer should populate the
** buffer with a nul-terminated UTF-8 encoded error message
** describing the last IO error to have occurred within the calling
** thread.
**
** If the error message is too large for the supplied buffer,
** it should be truncated. The return value of xGetLastError
** is zero if the error message fits in the buffer, or non-zero
** otherwise (if the message was truncated). If non-zero is returned,
** then it is not necessary to include the nul-terminator character
** in the output buffer.
**
** Not supplying an error message will have no adverse effect
** on SQLite. It is fine to have an implementation that never
** returns an error message:
**
** int xGetLastError(sqlite3_vfs pVfs, int nBuf, char *zBuf){
** Debug.Assert(zBuf[0]=='\0');
** return 0;
** }
**
** However if an error message is supplied, it will be incorporated
** by sqlite into the error message available to the user using
** sqlite3_errmsg(), possibly making IO errors easier to debug.
*/
static int winGetLastError( sqlite3_vfs pVfs, int nBuf, ref string zBuf )
{
UNUSED_PARAMETER( pVfs );
return getLastErrorMsg( nBuf, ref zBuf );
}
static sqlite3_vfs winVfs = new sqlite3_vfs(
1, /* iVersion */
-1, //sqlite3_file.Length, /* szOsFile */
MAX_PATH, /* mxPathname */
null, /* pNext */
"win32", /* zName */
0, /* pAppData */
(dxOpen)winOpen, /* xOpen */
(dxDelete)winDelete, /* xDelete */
(dxAccess)winAccess, /* xAccess */
(dxFullPathname)winFullPathname,/* xFullPathname */
(dxDlOpen)winDlOpen, /* xDlOpen */
(dxDlError)winDlError, /* xDlError */
(dxDlSym)winDlSym, /* xDlSym */
(dxDlClose)winDlClose, /* xDlClose */
(dxRandomness)winRandomness, /* xRandomness */
(dxSleep)winSleep, /* xSleep */
(dxCurrentTime)winCurrentTime, /* xCurrentTime */
(dxGetLastError)winGetLastError /* xGetLastError */
);
/*
** Initialize and deinitialize the operating system interface.
*/
static int sqlite3_os_init()
{
sqlite3_vfs_register( winVfs, 1 );
return SQLITE_OK;
}
static int sqlite3_os_end()
{
return SQLITE_OK;
}
//
// Windows DLL definitions
//
const int NO_ERROR = 0;
/// <summary>
/// Basic locking strategy for Console/Winform applications
/// </summary>
private class LockingStrategy
{
public virtual void LockFile( sqlite3_file pFile, long offset, long length )
{
}
public virtual int SharedLockFile( sqlite3_file pFile, long offset, long length )
{
return 1;
}
public virtual void UnlockFile( sqlite3_file pFile, long offset, long length )
{
}
}
/// <summary>
/// Locking strategy for Medium Trust. It uses the same trick used in the native code for WIN_CE
/// which doesn't support LockFileEx as well.
/// </summary>
private class MediumTrustLockingStrategy : LockingStrategy
{
public override int SharedLockFile( sqlite3_file pFile, long offset, long length )
{
return 1;
}
}
}
internal static class HelperMethods
{
public static bool IsRunningMediumTrust()
{
return true;
}
}
}
| |
/*
Copyright 2012-2022 Marco De Salvo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RDFSharp.Model;
using System;
using System.Linq;
namespace RDFSharp.Test.Model
{
[TestClass]
public class RDFDisjointConstraintTest
{
#region Tests
[TestMethod]
public void ShouldCreateDisjointConstraint()
{
RDFDisjointConstraint disjointConstraint = new RDFDisjointConstraint(new RDFResource("ex:prop"));
Assert.IsNotNull(disjointConstraint);
Assert.IsTrue(disjointConstraint.DisjointPredicate.Equals(new RDFResource("ex:prop")));
}
[TestMethod]
public void ShouldThrowExceptionOnCreatingDisjointConstraint()
=> Assert.ThrowsException<RDFModelException>(() => new RDFDisjointConstraint(null));
[TestMethod]
public void ShouldExportDisjointConstraint()
{
RDFDisjointConstraint disjointConstraint = new RDFDisjointConstraint(new RDFResource("ex:prop"));
RDFGraph graph = disjointConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape")));
Assert.IsNotNull(graph);
Assert.IsTrue(graph.TriplesCount == 1);
Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape"))
&& t.Value.Predicate.Equals(RDFVocabulary.SHACL.DISJOINT)
&& t.Value.Object.Equals(new RDFResource("ex:prop"))));
}
//NS-CONFORMS:TRUE
[TestMethod]
public void ShouldConformNodeShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
nodeShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
nodeShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformNodeShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//PS-CONFORMS:TRUE
[TestMethod]
public void ShouldConformPropertyShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
[TestMethod]
public void ShouldConformPropertyShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsTrue(validationReport.Conforms);
}
//NS-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformNodeShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
nodeShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
nodeShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
[TestMethod]
public void ShouldNotConformNodeShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape"));
nodeShape.AddMessage(new RDFPlainLiteral("ErrorMessage"));
nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
nodeShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(nodeShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("ErrorMessage")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsNull(validationReport.Results[0].ResultPath);
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape")));
}
//PS-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformPropertyShapeWithClassTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must not have common values with property <{RDFVocabulary.FOAF.AGENT}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithClassTargetThreatingLiteralValueNodes()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGE, new RDFTypedLiteral("25", RDFModelEnums.RDFDatatypes.XSD_INTEGER)));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.DEPICTS, new RDFTypedLiteral("25", RDFModelEnums.RDFDatatypes.XSD_INTEGER)));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGE, new RDFTypedLiteral("27", RDFModelEnums.RDFDatatypes.XSD_INTEGER)));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGE);
propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person")));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.DEPICTS));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must not have common values with property <{RDFVocabulary.FOAF.DEPICTS}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFTypedLiteral("25", RDFModelEnums.RDFDatatypes.XSD_INTEGER)));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGE));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithNodeTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice")));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must not have common values with property <{RDFVocabulary.FOAF.AGENT}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithSubjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must not have common values with property <{RDFVocabulary.FOAF.AGENT}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
[TestMethod]
public void ShouldNotConformPropertyShapeWithObjectsOfTarget()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Steve")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS);
propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS));
propertyShape.AddConstraint(new RDFDisjointConstraint(RDFVocabulary.FOAF.AGENT));
shapesGraph.AddShape(propertyShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must not have common values with property <{RDFVocabulary.FOAF.AGENT}>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape")));
}
//MIXED-CONFORMS:FALSE
[TestMethod]
public void ShouldNotConformNodeShapeWithPropertyShape()
{
//DataGraph
RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph"));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:USA"), new RDFResource("ex:prefLabel"), new RDFPlainLiteral("USA")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:USA"), new RDFResource("ex:altLabel"), new RDFPlainLiteral("United States")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Germany"), new RDFResource("ex:prefLabel"), new RDFPlainLiteral("Germany")));
dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Germany"), new RDFResource("ex:altLabel"), new RDFPlainLiteral("Germany")));
//ShapesGraph
RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph"));
RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:DisjointExampleShape"));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:USA")));
nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Germany")));
RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:prefLabel"));
propShape.AddConstraint(new RDFDisjointConstraint(new RDFResource("ex:altLabel")));
nodeShape.AddConstraint(new RDFPropertyConstraint(propShape));
shapesGraph.AddShape(nodeShape);
shapesGraph.AddShape(propShape);
//Validate
RDFValidationReport validationReport = shapesGraph.Validate(dataGraph);
Assert.IsNotNull(validationReport);
Assert.IsFalse(validationReport.Conforms);
Assert.IsTrue(validationReport.ResultsCount == 1);
Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation);
Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1);
Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral($"Must not have common values with property <ex:altLabel>")));
Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Germany")));
Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFPlainLiteral("Germany")));
Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:prefLabel")));
Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.DISJOINT_CONSTRAINT_COMPONENT));
Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape")));
}
#endregion
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Communication Subscription Channel Type Feed
///<para>SObject Name: CommSubscriptionChannelTypeFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfCommSubscriptionChannelTypeFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "CommSubscriptionChannelTypeFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: CommSubscriptionChannelType
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfCommSubscriptionChannelType Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace System.Reflection
{
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyTitleAttribute : Attribute
{
public extern AssemblyTitleAttribute(string title);
public extern string Title
{
get;
private set;
}
}
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyDescriptionAttribute : Attribute
{
public extern AssemblyDescriptionAttribute(string description);
public extern string Description
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyConfigurationAttribute : Attribute
{
public extern AssemblyConfigurationAttribute(string configuration);
public extern string Configuration
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyCompanyAttribute : Attribute
{
public extern AssemblyCompanyAttribute(string company);
public extern string Company
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyProductAttribute : Attribute
{
public extern AssemblyProductAttribute(string product);
public extern string Product
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyCopyrightAttribute : Attribute
{
public extern AssemblyCopyrightAttribute(string copyright);
public extern string Copyright
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyTrademarkAttribute : Attribute
{
public extern AssemblyTrademarkAttribute(string trademark);
public extern string Trademark
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyCultureAttribute : Attribute
{
public extern AssemblyCultureAttribute(string culture);
public extern string Culture
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyVersionAttribute : Attribute
{
public extern AssemblyVersionAttribute(string version);
public extern string Version
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyFileVersionAttribute : Attribute
{
public extern AssemblyFileVersionAttribute(string version);
public extern string Version
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class AssemblyInformationalVersionAttribute : Attribute
{
public extern AssemblyInformationalVersionAttribute(string informationalVersion);
public extern string InformationalVersion
{
get;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class DefaultMemberAttribute : Attribute
{
public extern DefaultMemberAttribute(string memberName);
public extern string MemberName
{
get;
private set;
}
}
}
namespace System.Runtime.CompilerServices
{
[EditorBrowsable(EditorBrowsableState.Never)]
[Bridge.External]
[Bridge.NonScriptable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
#pragma warning disable CS3015 // Type has no accessible constructors which use only CLS-compliant types
public sealed class TupleElementNamesAttribute : Attribute
#pragma warning restore CS3015 // Type has no accessible constructors which use only CLS-compliant types
{
public extern TupleElementNamesAttribute(string[] transformNames);
public IList<string> TransformNames { get; }
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Bridge.External]
[Bridge.NonScriptable]
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class InternalsVisibleToAttribute : Attribute
{
private string _assemblyName;
private bool _allInternalsVisible = true;
public InternalsVisibleToAttribute(string assemblyName)
{
this._assemblyName = assemblyName;
}
public string AssemblyName
{
get
{
return _assemblyName;
}
}
public bool AllInternalsVisible
{
get { return _allInternalsVisible; }
set { _allInternalsVisible = value; }
}
}
/// <summary>
/// If AllInternalsVisible is not true for a friend assembly, the FriendAccessAllowed attribute
/// indicates which internals are shared with that friend assembly.
/// </summary>
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Enum |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Method |
AttributeTargets.Property |
AttributeTargets.Struct,
AllowMultiple = false,
Inherited = false)]
[FriendAccessAllowed]
[EditorBrowsable(EditorBrowsableState.Never)]
[Bridge.External]
[Bridge.NonScriptable]
internal sealed class FriendAccessAllowedAttribute : Attribute
{
}
/// <summary>
/// If a constructor for a value type takes an instance of this type as a parameter, any attribute applied to that constructor will instead be applied to the default (undeclarable) constructor.
/// </summary>
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor
{
private extern DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[AttributeUsage(AttributeTargets.Property)]
[Bridge.NonScriptable]
public class IndexerNameAttribute : Attribute
{
public extern IndexerNameAttribute(string indexerName);
public extern string Value
{
get;
private set;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field)]
[Bridge.NonScriptable]
public sealed class DecimalConstantAttribute : Attribute
{
public extern DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low);
[CLSCompliant(false)]
public extern DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low);
public extern decimal Value
{
get;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class ExtensionAttribute : Attribute
{
public extern ExtensionAttribute();
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class DynamicAttribute : Attribute
{
public extern DynamicAttribute();
public extern DynamicAttribute(bool[] transformFlags);
public extern List<bool> TransformFlags
{
get;
}
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public class CallSite
{
public extern CallSiteBinder Binder
{
get;
}
public static extern CallSite Create(Type delegateType, CallSiteBinder binder);
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class CallSite<T> : CallSite where T : class
{
public extern T Update
{
get;
}
public T Target;
public static extern CallSite<T> Create(CallSiteBinder binder);
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public abstract class CallSiteBinder
{
public static extern LabelTarget UpdateLabel
{
get;
}
public extern T BindDelegate<T>(CallSite<T> site, object[] args) where T : class;
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public struct AsyncVoidMethodBuilder
{
public static extern AsyncVoidMethodBuilder Create();
public extern void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine;
public extern void SetStateMachine(IAsyncStateMachine stateMachine);
public extern void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine;
public extern void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine;
public extern void SetResult();
public extern void SetException(Exception exception);
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public struct AsyncTaskMethodBuilder
{
public extern Task Task
{
get;
}
public static extern AsyncTaskMethodBuilder Create();
public extern void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine;
public extern void SetStateMachine(IAsyncStateMachine stateMachine);
public extern void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine;
public extern void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine;
public extern void SetResult();
public extern void SetException(Exception exception);
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public struct AsyncTaskMethodBuilder<TResult>
{
public extern Task<TResult> Task
{
get;
}
public static extern AsyncTaskMethodBuilder<TResult> Create();
public extern void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine;
public extern void SetStateMachine(IAsyncStateMachine stateMachine);
public extern void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine;
public extern void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine;
public extern void SetResult(TResult result);
public extern void SetException(Exception exception);
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public interface IAsyncStateMachine
{
void MoveNext();
void SetStateMachine(IAsyncStateMachine stateMachine);
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public interface INotifyCompletion
{
void OnCompleted(Action continuation);
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public interface ICriticalNotifyCompletion : INotifyCompletion
{
void UnsafeOnCompleted(Action continuation);
}
}
namespace Microsoft.CSharp.RuntimeBinder
{
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public static class Binder
{
public static extern CallSiteBinder BinaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
public static extern CallSiteBinder Convert(CSharpBinderFlags flags, Type type, Type context);
public static extern CallSiteBinder GetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
public static extern CallSiteBinder GetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
public static extern CallSiteBinder Invoke(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
public static extern CallSiteBinder InvokeMember(CSharpBinderFlags flags, string name, IEnumerable<Type> typeArguments, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
public static extern CallSiteBinder InvokeConstructor(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
public static extern CallSiteBinder IsEvent(CSharpBinderFlags flags, string name, Type context);
public static extern CallSiteBinder SetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
public static extern CallSiteBinder SetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
public static extern CallSiteBinder UnaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo);
}
[Bridge.External]
[Bridge.NonScriptable]
public enum CSharpBinderFlags
{
None = 0,
CheckedContext = 1,
InvokeSimpleName = 2,
InvokeSpecialName = 4,
BinaryOperationLogical = 8,
ConvertExplicit = 16,
ConvertArrayIndex = 32,
ResultIndexed = 64,
ValueFromCompoundAssignment = 128,
ResultDiscarded = 256,
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.NonScriptable]
public sealed class CSharpArgumentInfo
{
public static extern CSharpArgumentInfo Create(CSharpArgumentInfoFlags flags, string name);
}
[Bridge.External]
[Bridge.NonScriptable]
public enum CSharpArgumentInfoFlags
{
None = 0,
UseCompileTimeType = 1,
Constant = 2,
NamedArgument = 4,
IsRef = 8,
IsOut = 16,
IsStaticType = 32,
}
}
namespace System.Threading
{
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Bridge.External]
[Bridge.NonScriptable]
public static class Interlocked
{
public static extern int CompareExchange(ref int location1, int value, int comparand);
public static extern T CompareExchange<T>(ref T location1, T value, T comparand) where T : class;
}
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Bridge.External]
[Bridge.NonScriptable]
public static class Monitor
{
public static extern void Enter(object obj);
public static extern void Enter(object obj, ref bool b);
public static extern void Exit(object obj);
}
}
| |
// 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.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[CLSCompliant(false)]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct UInt32 : IComparable, IConvertible, IFormattable, IComparable<UInt32>, IEquatable<UInt32>, ISpanFormattable
{
private uint m_value; // Do not rename (binary serialization)
public const uint MaxValue = (uint)0xffffffff;
public const uint MinValue = 0U;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt32, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is UInt32)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
uint i = (uint)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeUInt32);
}
public int CompareTo(UInt32 value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is UInt32))
{
return false;
}
return m_value == ((UInt32)obj).m_value;
}
[NonVersionable]
public bool Equals(UInt32 obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return ((int)m_value);
}
// The base 10 representation of the number with no extra padding.
public override String ToString()
{
return Number.FormatUInt32(m_value, null, null);
}
public String ToString(IFormatProvider provider)
{
return Number.FormatUInt32(m_value, null, provider);
}
public String ToString(String format)
{
return Number.FormatUInt32(m_value, format, null);
}
public String ToString(String format, IFormatProvider provider)
{
return Number.FormatUInt32(m_value, format, provider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
{
return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten);
}
[CLSCompliant(false)]
public static uint Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(String s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static bool TryParse(String s, out UInt32 result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, out uint result)
{
return Number.TryParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out uint result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.UInt32;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return m_value;
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System;
using System.Threading.Tasks;
using Content.Server.DoAfter;
using Content.Server.Hands.Components;
using Content.Shared.ActionBlocker;
using Content.Shared.Cuffs.Components;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Helpers;
using Content.Shared.Popups;
using Content.Shared.Sound;
using Content.Shared.Stunnable;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Player;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Cuffs.Components
{
[RegisterComponent]
[ComponentReference(typeof(SharedHandcuffComponent))]
public sealed class HandcuffComponent : SharedHandcuffComponent, IAfterInteract
{
[Dependency] private readonly IEntityManager _entities = default!;
/// <summary>
/// The time it takes to apply a <see cref="CuffedComponent"/> to an entity.
/// </summary>
[ViewVariables]
[DataField("cuffTime")]
public float CuffTime { get; set; } = 5f;
/// <summary>
/// The time it takes to remove a <see cref="CuffedComponent"/> from an entity.
/// </summary>
[ViewVariables]
[DataField("uncuffTime")]
public float UncuffTime { get; set; } = 5f;
/// <summary>
/// The time it takes for a cuffed entity to remove <see cref="CuffedComponent"/> from itself.
/// </summary>
[ViewVariables]
[DataField("breakoutTime")]
public float BreakoutTime { get; set; } = 30f;
/// <summary>
/// If an entity being cuffed is stunned, this amount of time is subtracted from the time it takes to add/remove their cuffs.
/// </summary>
[ViewVariables]
[DataField("stunBonus")]
public float StunBonus { get; set; } = 2f;
/// <summary>
/// Will the cuffs break when removed?
/// </summary>
[ViewVariables]
[DataField("breakOnRemove")]
public bool BreakOnRemove { get; set; }
/// <summary>
/// The path of the RSI file used for the player cuffed overlay.
/// </summary>
[ViewVariables]
[DataField("cuffedRSI")]
public string? CuffedRSI { get; set; } = "Objects/Misc/handcuffs.rsi";
/// <summary>
/// The iconstate used with the RSI file for the player cuffed overlay.
/// </summary>
[ViewVariables]
[DataField("bodyIconState")]
public string? OverlayIconState { get; set; } = "body-overlay";
/// <summary>
/// The iconstate used for broken handcuffs
/// </summary>
[ViewVariables]
[DataField("brokenIconState")]
public string? BrokenState { get; set; }
/// <summary>
/// The iconstate used for broken handcuffs
/// </summary>
[ViewVariables]
[DataField("brokenName")]
public string BrokenName { get; set; } = default!;
/// <summary>
/// The iconstate used for broken handcuffs
/// </summary>
[ViewVariables]
[DataField("brokenDesc")]
public string BrokenDesc { get; set; } = default!;
[ViewVariables]
public bool Broken
{
get
{
return _isBroken;
}
set
{
if (_isBroken != value)
{
_isBroken = value;
Dirty();
}
}
}
[DataField("startCuffSound")]
public SoundSpecifier StartCuffSound { get; set; } = new SoundPathSpecifier("/Audio/Items/Handcuffs/cuff_start.ogg");
[DataField("endCuffSound")]
public SoundSpecifier EndCuffSound { get; set; } = new SoundPathSpecifier("/Audio/Items/Handcuffs/cuff_end.ogg");
[DataField("startBreakoutSound")]
public SoundSpecifier StartBreakoutSound { get; set; } = new SoundPathSpecifier("/Audio/Items/Handcuffs/cuff_breakout_start.ogg");
[DataField("startUncuffSound")]
public SoundSpecifier StartUncuffSound { get; set; } = new SoundPathSpecifier("/Audio/Items/Handcuffs/cuff_takeoff_start.ogg");
[DataField("endUncuffSound")]
public SoundSpecifier EndUncuffSound { get; set; } = new SoundPathSpecifier("/Audio/Items/Handcuffs/cuff_takeoff_end.ogg");
[DataField("color")]
public Color Color { get; set; } = Color.White;
// Non-exposed data fields
private bool _isBroken = false;
/// <summary>
/// Used to prevent DoAfter getting spammed.
/// </summary>
private bool _cuffing;
public override ComponentState GetComponentState()
{
return new HandcuffedComponentState(Broken ? BrokenState : string.Empty);
}
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (_cuffing) return true;
if (eventArgs.Target is not {Valid: true} target ||
!_entities.TryGetComponent<CuffableComponent?>(eventArgs.Target.Value, out var cuffed))
{
return false;
}
if (eventArgs.Target == eventArgs.User)
{
eventArgs.User.PopupMessage(Loc.GetString("handcuff-component-target-self-error"));
return true;
}
if (Broken)
{
eventArgs.User.PopupMessage(Loc.GetString("handcuff-component-cuffs-broken-error"));
return true;
}
if (!_entities.TryGetComponent<HandsComponent?>(target, out var hands))
{
eventArgs.User.PopupMessage(Loc.GetString("handcuff-component-target-has-no-hands-error",("targetName", eventArgs.Target)));
return true;
}
if (cuffed.CuffedHandCount >= hands.Count)
{
eventArgs.User.PopupMessage(Loc.GetString("handcuff-component-target-has-no-free-hands-error",("targetName", eventArgs.Target)));
return true;
}
if (!eventArgs.CanReach)
{
eventArgs.User.PopupMessage(Loc.GetString("handcuff-component-too-far-away-error"));
return true;
}
eventArgs.User.PopupMessage(Loc.GetString("handcuff-component-start-cuffing-target-message",("targetName", eventArgs.Target)));
eventArgs.User.PopupMessage(target, Loc.GetString("handcuff-component-start-cuffing-by-other-message",("otherName", eventArgs.User)));
SoundSystem.Play(Filter.Pvs(Owner), StartCuffSound.GetSound(), Owner);
TryUpdateCuff(eventArgs.User, target, cuffed);
return true;
}
/// <summary>
/// Update the cuffed state of an entity
/// </summary>
private async void TryUpdateCuff(EntityUid user, EntityUid target, CuffableComponent cuffs)
{
var cuffTime = CuffTime;
if (_entities.HasComponent<StunnedComponent>(target))
{
cuffTime = MathF.Max(0.1f, cuffTime - StunBonus);
}
var doAfterEventArgs = new DoAfterEventArgs(user, cuffTime, default, target)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
BreakOnDamage = true,
BreakOnStun = true,
NeedHand = true
};
_cuffing = true;
var result = await EntitySystem.Get<DoAfterSystem>().WaitDoAfter(doAfterEventArgs);
_cuffing = false;
if (result != DoAfterStatus.Cancelled)
{
if (cuffs.TryAddNewCuffs(user, Owner))
{
SoundSystem.Play(Filter.Pvs(Owner), EndCuffSound.GetSound(), Owner);
user.PopupMessage(Loc.GetString("handcuff-component-cuff-other-success-message",("otherName", target)));
target.PopupMessage(Loc.GetString("handcuff-component-cuff-by-other-success-message", ("otherName", user)));
}
}
else
{
user.PopupMessage(Loc.GetString("handcuff-component-cuff-interrupt-message",("targetName", target)));
target.PopupMessage(Loc.GetString("handcuff-component-cuff-interrupt-other-message",("otherName", user)));
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using WsdlNS = System.Web.Services.Description;
class WsdlWrapper : IXmlSerializable
{
WsdlNS.ServiceDescription wsdl;
public WsdlWrapper(WsdlNS.ServiceDescription wsdl)
{
this.wsdl = wsdl;
}
public void WriteXml(XmlWriter xmlWriter)
{
if (wsdl != null)
{
using (MemoryStream ms = new MemoryStream())
{
wsdl.Write(ms);
XmlDictionaryReaderQuotas quota = new XmlDictionaryReaderQuotas();
quota.MaxDepth = 32;
quota.MaxStringContentLength = 8192;
quota.MaxArrayLength = 16384;
quota.MaxBytesPerRead = 4096;
quota.MaxNameTableCharCount = 16384;
ms.Seek(0, SeekOrigin.Begin);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(ms, null, quota, null);
if ((reader.MoveToContent() == XmlNodeType.Element) && (reader.Name == "wsdl:definitions"))
{
xmlWriter.WriteNode(reader, false);
}
reader.Close();
}
}
}
public void ReadXml(XmlReader xmlReader)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
public XmlSchema GetSchema()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
}
[DataContract(Name = "ComPlusServiceHost")]
class ComPlusServiceHostSchema : TraceRecord
{
[DataMember(Name = "appid")]
Guid appid;
[DataMember(Name = "clsid")]
Guid clsid;
public ComPlusServiceHostSchema(Guid appid, Guid clsid)
{
this.appid = appid;
this.clsid = clsid;
}
internal override string EventId { get { return BuildEventId("ComPlusServiceHost"); } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
public override string ToString()
{
return SR.GetString(SR.ComPlusServiceSchema, this.appid.ToString(), this.clsid.ToString());
}
}
[DataContract(Name = "ComPlusServiceHostCreatedServiceContract")]
class ComPlusServiceHostCreatedServiceContractSchema : ComPlusServiceHostSchema
{
// ContractDescription has [DataContract] attribute, but its serialization appears to fail.
// So explicitly write the needed properties
[DataMember(Name = "ContractQName")]
XmlQualifiedName contractQname;
[DataMember(Name = "Contract")]
string contract;
public ComPlusServiceHostCreatedServiceContractSchema(Guid appid, Guid clsid,
XmlQualifiedName contractQname, string contract)
: base(appid, clsid)
{
this.contractQname = contractQname;
this.contract = contract;
}
internal override string EventId { get { return BuildEventId("ComPlusServiceHostCreatedServiceContract"); } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
}
[DataContract(Name = "ComPlusServiceHostStartedServiceDetails")]
class ComPlusServiceHostStartedServiceDetailsSchema : ComPlusServiceHostSchema
{
[DataMember(Name = "ServiceDescription")]
WsdlWrapper wsdlWrapper;
public ComPlusServiceHostStartedServiceDetailsSchema(Guid appid, Guid clsid, WsdlNS.ServiceDescription wsdl)
: base(appid, clsid)
{
this.wsdlWrapper = new WsdlWrapper(wsdl);
}
internal override string EventId { get { return BuildEventId("ComPlusServiceHostStartedServiceDetails"); } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
}
[DataContract(Name = "ComPlusServiceHostCreatedServiceEndpoint")]
class ComPlusServiceHostCreatedServiceEndpointSchema : ComPlusServiceHostSchema
{
[DataMember(Name = "Contract")]
string contract;
[DataMember(Name = "Address")]
Uri address;
[DataMember(Name = "Binding")]
string binding;
public ComPlusServiceHostCreatedServiceEndpointSchema(Guid appid, Guid clsid, string contract,
Uri address, string binding)
: base(appid, clsid)
{
this.contract = contract;
this.address = address;
this.binding = binding;
}
internal override string EventId { get { return BuildEventId("ComPlusServiceHostCreatedServiceEndpoint"); } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
}
[DataContract(Name = "ComPlusDllHostInitializer")]
class ComPlusDllHostInitializerSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusDllHostInitializer" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
public override string ToString()
{
return SR.GetString(SR.ComPlusServiceSchemaDllHost, this.appid.ToString());
}
[DataMember(Name = "appid")]
Guid appid;
public ComPlusDllHostInitializerSchema(
Guid appid
)
{
this.appid = appid;
}
}
[DataContract(Name = "ComPlusDllHostInitializerAddingHost")]
class ComPlusDllHostInitializerAddingHostSchema : ComPlusDllHostInitializerSchema
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusDllHostInitializerAddingHost" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "clsid")]
Guid clsid;
[DataMember(Name = "BehaviorConfiguration")]
string behaviorConfiguration;
[DataMember(Name = "ServiceType")]
string serviceType;
[DataMember(Name = "Address")]
string address;
[DataMember(Name = "BindingConfiguration")]
string bindingConfiguration;
[DataMember(Name = "BindingName")]
string bindingName;
[DataMember(Name = "BindingNamespace")]
string bindingNamespace;
[DataMember(Name = "BindingSectionName")]
string bindingSectionName;
[DataMember(Name = "ContractType")]
string contractType;
public ComPlusDllHostInitializerAddingHostSchema(
Guid appid,
Guid clsid,
string behaviorConfiguration,
string serviceType,
string address,
string bindingConfiguration,
string bindingName,
string bindingNamespace,
string bindingSectionName,
string contractType
)
: base(appid)
{
this.clsid = clsid;
this.behaviorConfiguration = behaviorConfiguration;
this.serviceType = serviceType;
this.address = address;
this.bindingConfiguration = bindingConfiguration;
this.bindingName = bindingName;
this.bindingNamespace = bindingNamespace;
this.bindingSectionName = bindingSectionName;
this.contractType = contractType;
}
}
[DataContract(Name = "ComPlusTLBImport")]
class ComPlusTLBImportSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusTLBImport" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
public override string ToString()
{
return SR.GetString(SR.ComPlusTLBImportSchema, this.iid.ToString(), this.typeLibraryID.ToString());
}
[DataMember(Name = "InterfaceID")]
Guid iid;
[DataMember(Name = "TypeLibraryID")]
Guid typeLibraryID;
public ComPlusTLBImportSchema(
Guid iid,
Guid typeLibraryID
)
{
this.iid = iid;
this.typeLibraryID = typeLibraryID;
}
}
[DataContract(Name = "ComPlusTLBImportFromAssembly")]
class ComPlusTLBImportFromAssemblySchema : ComPlusTLBImportSchema
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusTLBImportFromAssembly" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "Assembly")]
string assembly;
public ComPlusTLBImportFromAssemblySchema(
Guid iid,
Guid typeLibraryID,
string assembly
)
: base(iid, typeLibraryID)
{
this.assembly = assembly;
}
}
[DataContract(Name = "ComPlusTLBImportConverterEvent")]
class ComPlusTLBImportConverterEventSchema : ComPlusTLBImportSchema
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusTLBImportConverterEvent" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "EventKind")]
ImporterEventKind eventKind;
[DataMember(Name = "EventCode")]
int eventCode;
[DataMember(Name = "EventMessage")]
string eventMessage;
public ComPlusTLBImportConverterEventSchema(
Guid iid,
Guid typeLibraryID,
ImporterEventKind eventKind,
int eventCode,
string eventMessage
)
: base(iid, typeLibraryID)
{
this.eventKind = eventKind;
this.eventCode = eventCode;
this.eventMessage = eventMessage;
}
}
[DataContract(Name = "ComPlusInstanceCreationRequest")]
class ComPlusInstanceCreationRequestSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusInstanceCreationRequest" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
public override string ToString()
{
return SR.GetString(SR.ComPlusInstanceCreationRequestSchema,
this.from.ToString(),
this.appid.ToString(),
this.clsid.ToString(),
this.incomingTransactionID.ToString(),
this.requestingIdentity);
}
[DataMember(Name = "From")]
Uri from;
[DataMember(Name = "appid")]
Guid appid;
[DataMember(Name = "clsid")]
Guid clsid;
[DataMember(Name = "IncomingTransactionID")]
Guid incomingTransactionID;
[DataMember(Name = "RequestingIdentity")]
string requestingIdentity;
public ComPlusInstanceCreationRequestSchema(
Guid appid,
Guid clsid,
Uri from,
Guid incomingTransactionID,
string requestingIdentity
)
{
this.from = from;
this.appid = appid;
this.clsid = clsid;
this.incomingTransactionID = incomingTransactionID;
this.requestingIdentity = requestingIdentity;
}
}
[DataContract(Name = "ComPlusInstanceCreationSuccess")]
class ComPlusInstanceCreationSuccessSchema : ComPlusInstanceCreationRequestSchema
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusInstanceCreationSuccess" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "InstanceID")]
int instanceID;
public ComPlusInstanceCreationSuccessSchema(
Guid appid,
Guid clsid,
Uri from,
Guid incomingTransactionID,
string requestingIdentity,
int instanceID
)
: base(appid, clsid, from, incomingTransactionID, requestingIdentity)
{
this.instanceID = instanceID;
}
}
[DataContract(Name = "ComPlusInstanceReleased")]
class ComPlusInstanceReleasedSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusInstanceReleased" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "appid")]
Guid appid;
[DataMember(Name = "clsid")]
Guid clsid;
[DataMember(Name = "InstanceID")]
int instanceID;
public ComPlusInstanceReleasedSchema(
Guid appid,
Guid clsid,
int instanceID
)
{
this.appid = appid;
this.clsid = clsid;
this.instanceID = instanceID;
}
}
[DataContract(Name = "ComPlusActivity")]
class ComPlusActivitySchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusActivity" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "ActivityID")]
Guid activityID;
[DataMember(Name = "LogicalThreadID")]
Guid logicalThreadID;
[DataMember(Name = "ManagedThreadID")]
int managedThreadID;
[DataMember(Name = "UnmanagedThreadID")]
int unmanagedThreadID;
public ComPlusActivitySchema(
Guid activityID,
Guid logicalThreadID,
int managedThreadID,
int unmanagedThreadID
)
{
this.activityID = activityID;
this.logicalThreadID = logicalThreadID;
this.managedThreadID = managedThreadID;
this.unmanagedThreadID = unmanagedThreadID;
}
}
[DataContract(Name = "ComPlusMethodCall")]
class ComPlusMethodCallSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusMethodCall" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
public override string ToString()
{
return SR.GetString(SR.ComPlusMethodCallSchema,
this.from.ToString(),
this.appid.ToString(),
this.clsid.ToString(),
this.iid.ToString(),
this.action,
this.instanceID.ToString(CultureInfo.CurrentCulture),
this.managedThreadID.ToString(CultureInfo.CurrentCulture),
this.unmanagedThreadID.ToString(CultureInfo.CurrentCulture),
this.requestingIdentity);
}
[DataMember(Name = "From")]
Uri from;
[DataMember(Name = "appid")]
Guid appid;
[DataMember(Name = "clsid")]
Guid clsid;
[DataMember(Name = "iid")]
Guid iid;
[DataMember(Name = "Action")]
string action;
[DataMember(Name = "InstanceID")]
int instanceID;
[DataMember(Name = "ManagedThreadID")]
int managedThreadID;
[DataMember(Name = "UnmanagedThreadID")]
int unmanagedThreadID;
[DataMember(Name = "RequestingIdentity")]
string requestingIdentity;
public ComPlusMethodCallSchema(
Uri from,
Guid appid,
Guid clsid,
Guid iid,
string action,
int instanceID,
int managedThreadID,
int unmanagedThreadID,
string requestingIdentity
)
{
this.from = from;
this.appid = appid;
this.clsid = clsid;
this.iid = iid;
this.action = action;
this.instanceID = instanceID;
this.managedThreadID = managedThreadID;
this.unmanagedThreadID = unmanagedThreadID;
this.requestingIdentity = requestingIdentity;
}
}
[DataContract(Name = "ComPlusMethodCallTxMismatch")]
class ComPlusMethodCallTxMismatchSchema : ComPlusMethodCallSchema
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusMethodCallTxMismatch" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
[DataMember(Name = "IncomingTransactionID")]
Guid incomingTransactionID;
[DataMember(Name = "CurrentTransactionID")]
Guid currentTransactionID;
public ComPlusMethodCallTxMismatchSchema(
Uri from,
Guid appid,
Guid clsid,
Guid iid,
string action,
int instanceID,
int managedThreadID,
int unmanagedThreadID,
string requestingIdentity,
Guid incomingTransactionID,
Guid currentTransactionID)
: base(from, appid, clsid, iid, action, instanceID, managedThreadID, unmanagedThreadID, requestingIdentity)
{
this.incomingTransactionID = incomingTransactionID;
this.currentTransactionID = currentTransactionID;
}
}
[DataContract(Name = "ComPlusMethodCallNewTx")]
class ComPlusMethodCallNewTxSchema : ComPlusMethodCallSchema
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusMethodCallNewTx" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
[DataMember(Name = "NewTransactionID")]
Guid newTransactionID;
public ComPlusMethodCallNewTxSchema(
Uri from,
Guid appid,
Guid clsid,
Guid iid,
string action,
int instanceID,
int managedThreadID,
int unmanagedThreadID,
string requestingIdentity,
Guid newTransactionID)
: base(from, appid, clsid, iid, action, instanceID, managedThreadID, unmanagedThreadID, requestingIdentity)
{
this.newTransactionID = newTransactionID;
}
}
[DataContract(Name = "ComPlusMethodCallContextTx")]
class ComPlusMethodCallContextTxSchema : ComPlusMethodCallSchema
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusMethodCallContextTx" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
[DataMember(Name = "ContextTransactionID")]
Guid contextTransactionID;
public ComPlusMethodCallContextTxSchema(
Uri from,
Guid appid,
Guid clsid,
Guid iid,
string action,
int instanceID,
int managedThreadID,
int unmanagedThreadID,
string requestingIdentity,
Guid contextTransactionID)
: base(from, appid, clsid, iid, action, instanceID, managedThreadID, unmanagedThreadID, requestingIdentity)
{
this.contextTransactionID = contextTransactionID;
}
}
[DataContract(Name = "ComPlusServiceMoniker")]
class ComPlusServiceMonikerSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusServiceMoniker" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "Address")]
string address;
[DataMember(Name = "Contract")]
string contract;
[DataMember(Name = "ContractNamespace")]
string contractNamespace;
[DataMember(Name = "Wsdl")]
WsdlWrapper wsdlWrapper;
[DataMember(Name = "SpnIdentity")]
string spnIdentity;
[DataMember(Name = "UpnIdentity")]
string upnIdentity;
[DataMember(Name = "DnsIdentity")]
string dnsIdentity;
[DataMember(Name = "Binding")]
string binding;
[DataMember(Name = "BindingConfiguration")]
string bindingConfiguration;
[DataMember(Name = "BindingNamespace")]
string bindingNamespace;
[DataMember(Name = "mexSpnIdentity")]
string mexSpnIdentity;
[DataMember(Name = "mexUpnIdentity")]
string mexUpnIdentity;
[DataMember(Name = "mexDnsIdentity")]
string mexDnsIdentity;
[DataMember(Name = "mexAddress")]
string mexAddress;
[DataMember(Name = "mexBinding")]
string mexBinding;
[DataMember(Name = "mexBindingConfiguration")]
string mexBindingConfiguration;
public ComPlusServiceMonikerSchema(
string address,
string contract,
string contractNamespace,
WsdlNS.ServiceDescription wsdl,
string spnIdentity,
string upnIdentity,
string dnsIdentity,
string binding,
string bindingConfiguration,
string bindingNamespace,
string mexAddress,
string mexBinding,
string mexBindingConfiguration,
string mexSpnIdentity,
string mexUpnIdentity,
string mexDnsIdentity
)
{
this.address = address;
this.contract = contract;
this.contractNamespace = contractNamespace;
this.wsdlWrapper = new WsdlWrapper(wsdl);
this.spnIdentity = spnIdentity;
this.upnIdentity = spnIdentity;
this.dnsIdentity = spnIdentity;
this.binding = binding;
this.bindingConfiguration = bindingConfiguration;
this.bindingNamespace = bindingNamespace;
this.mexSpnIdentity = mexSpnIdentity;
this.mexUpnIdentity = mexUpnIdentity;
this.mexDnsIdentity = mexDnsIdentity;
this.mexAddress = mexAddress;
this.mexBinding = mexBinding;
this.mexBindingConfiguration = mexBindingConfiguration;
}
}
[DataContract(Name = "ComPlusWsdlChannelBuilder")]
class ComPlusWsdlChannelBuilderSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusWsdlChannelBuilder" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "BindingQName")]
XmlQualifiedName bindingQname;
[DataMember(Name = "ContractQName")]
XmlQualifiedName contractQname;
[DataMember(Name = "ServiceQName")]
XmlQualifiedName serviceQname;
[DataMember(Name = "ImportedContract")]
string importedContract;
[DataMember(Name = "ImportedBinding")]
string importedBinding;
[DataMember(Name = "XmlSchemaSet")]
XmlSchemaWrapper schema;
public ComPlusWsdlChannelBuilderSchema(
XmlQualifiedName bindingQname,
XmlQualifiedName contractQname,
XmlQualifiedName serviceQname,
string importedContract,
string importedBinding,
XmlSchema schema
)
{
this.bindingQname = bindingQname;
this.contractQname = contractQname;
this.serviceQname = serviceQname;
this.importedContract = importedContract;
this.importedBinding = importedBinding;
this.schema = new XmlSchemaWrapper(schema);
}
class XmlSchemaWrapper : IXmlSerializable
{
XmlSchema schema;
public XmlSchemaWrapper(XmlSchema schema)
{
this.schema = schema;
}
public void WriteXml(XmlWriter xmlWriter)
{
StringWriter textWriter = new StringWriter(CultureInfo.InvariantCulture);
XmlTextWriter writer = new XmlTextWriter(textWriter);
schema.Write(writer);
writer.Flush();
UTF8Encoding utf8 = new UTF8Encoding();
byte[] wsdlText = utf8.GetBytes(textWriter.ToString());
XmlDictionaryReaderQuotas quota = new XmlDictionaryReaderQuotas();
quota.MaxDepth = 32;
quota.MaxStringContentLength = 8192;
quota.MaxArrayLength = 16384;
quota.MaxBytesPerRead = 4096;
quota.MaxNameTableCharCount = 16384;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(wsdlText, 0, wsdlText.GetLength(0), null, quota, null);
if ((reader.MoveToContent() == XmlNodeType.Element) && (reader.Name == "xs:schema"))
{
xmlWriter.WriteNode(reader, false);
}
reader.Close();
}
public void ReadXml(XmlReader xmlReader)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
public XmlSchema GetSchema()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
}
}
[DataContract(Name = "ComPlusTypedChannelBuilder")]
class ComPlusTypedChannelBuilderSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusTypedChannelBuilder" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "Contract")]
string contract;
[DataMember(Name = "Binding")]
string binding;
public ComPlusTypedChannelBuilderSchema(
string contract,
string binding
)
{
this.contract = contract;
this.binding = binding;
}
}
[DataContract(Name = "ComPlusMexChannelBuilder")]
class ComPlusMexChannelBuilderSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusMexChannelBuilder" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "Contract")]
string contract;
[DataMember(Name = "contractNamespace")]
string contractNamespace;
[DataMember(Name = "bindingNamespace")]
string bindingNamespace;
[DataMember(Name = "Binding")]
string binding;
[DataMember(Name = "Address")]
string address;
public ComPlusMexChannelBuilderSchema(
string contract,
string contractNamespace,
string binding,
string bindingNamespace,
string address
)
{
this.contract = contract;
this.binding = binding;
this.contractNamespace = contractNamespace;
this.bindingNamespace = bindingNamespace;
this.address = address;
}
}
[DataContract(Name = "ComPlusMexBuilderMetadataRetrievedEndpoint")]
class ComPlusMexBuilderMetadataRetrievedEndpoint : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusMexBuilderMetadataRetrievedEndpoint" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "Binding")]
string binding;
[DataMember(Name = "BindingNamespace")]
string bindingNamespace;
[DataMember(Name = "Address")]
string address;
[DataMember(Name = "Contract")]
string contract;
[DataMember(Name = "ContractNamespace")]
string contractNamespace;
public ComPlusMexBuilderMetadataRetrievedEndpoint(ServiceEndpoint endpoint)
{
this.binding = endpoint.Binding.Name;
this.bindingNamespace = endpoint.Binding.Namespace;
this.address = endpoint.Address.ToString();
this.contract = endpoint.Contract.Name;
this.contractNamespace = endpoint.Contract.Namespace;
}
}
[DataContract(Name = "ComPlusMexBuilderMetadataRetrieved")]
class ComPlusMexBuilderMetadataRetrievedSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusMexBuilderMetadataRetrieved" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "bindingNamespaces")]
ComPlusMexBuilderMetadataRetrievedEndpoint[] endpoints;
public ComPlusMexBuilderMetadataRetrievedSchema(
ComPlusMexBuilderMetadataRetrievedEndpoint[] endpoints
)
{
this.endpoints = endpoints;
}
}
[DataContract(Name = "ComPlusChannelCreated")]
class ComPlusChannelCreatedSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusChannelCreated" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "Address")]
Uri address;
[DataMember(Name = "Contract")]
string contract;
public ComPlusChannelCreatedSchema(
Uri address,
string contract
)
{
this.address = address;
this.contract = contract;
}
}
[DataContract(Name = "ComPlusDispatchMethodSchema")]
class ComPlusDispatchMethodSchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusDispatchMethod" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "Name")]
string name;
[DataMember(Name = "ParameterInfo")]
List<System.ServiceModel.ComIntegration.DispatchProxy.ParamInfo> paramList;
[DataMember(Name = "ReturnValueInfo")]
System.ServiceModel.ComIntegration.DispatchProxy.ParamInfo returnValue;
public ComPlusDispatchMethodSchema(
string name,
List<System.ServiceModel.ComIntegration.DispatchProxy.ParamInfo> paramList,
System.ServiceModel.ComIntegration.DispatchProxy.ParamInfo returnValue
)
{
this.name = name;
this.paramList = paramList;
this.returnValue = returnValue;
}
}
[DataContract(Name = "ComPlusTxProxySchema")]
class ComPlusTxProxySchema : TraceRecord
{
const string schemaId = TraceRecord.EventIdBase + "ComPlusTxProxyTx" + TraceRecord.NamespaceSuffix;
internal override string EventId { get { return schemaId; } }
internal override void WriteTo(XmlWriter xmlWriter)
{
ComPlusTraceRecord.SerializeRecord(xmlWriter, this);
}
[DataMember(Name = "appid")]
Guid appid;
[DataMember(Name = "clsid")]
Guid clsid;
[DataMember(Name = "TransactionID")]
Guid transactionID;
[DataMember(Name = "InstanceID")]
int instanceID;
public ComPlusTxProxySchema(Guid appid, Guid clsid,
Guid transactionID, int instanceID)
{
this.appid = appid;
this.clsid = clsid;
this.transactionID = transactionID;
this.instanceID = instanceID;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// CryptoAPITransform.cs
//
namespace System.Security.Cryptography {
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
#if FEATURE_MACL && FEATURE_CRYPTO && !MONO
[Serializable]
internal enum CryptoAPITransformMode {
Encrypt = 0,
Decrypt = 1
}
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class CryptoAPITransform : ICryptoTransform {
private int BlockSizeValue;
private byte[] IVValue;
private CipherMode ModeValue;
private PaddingMode PaddingValue;
private CryptoAPITransformMode encryptOrDecrypt;
private byte[] _rgbKey;
private byte[] _depadBuffer = null;
[System.Security.SecurityCritical] // auto-generated
private SafeKeyHandle _safeKeyHandle;
[System.Security.SecurityCritical] // auto-generated
private SafeProvHandle _safeProvHandle;
private CryptoAPITransform () {}
[System.Security.SecurityCritical] // auto-generated
internal CryptoAPITransform(int algid, int cArgs, int[] rgArgIds,
Object[] rgArgValues, byte[] rgbKey, PaddingMode padding,
CipherMode cipherChainingMode, int blockSize,
int feedbackSize, bool useSalt,
CryptoAPITransformMode encDecMode) {
int dwValue;
byte[] rgbValue;
BlockSizeValue = blockSize;
ModeValue = cipherChainingMode;
PaddingValue = padding;
encryptOrDecrypt = encDecMode;
// Copy the input args
int _cArgs = cArgs;
int[] _rgArgIds = new int[rgArgIds.Length];
Array.Copy(rgArgIds, _rgArgIds, rgArgIds.Length);
_rgbKey = new byte[rgbKey.Length];
Array.Copy(rgbKey, _rgbKey, rgbKey.Length);
Object[] _rgArgValues = new Object[rgArgValues.Length];
// an element of rgArgValues can only be an int or a byte[]
for (int j = 0; j < rgArgValues.Length; j++) {
if (rgArgValues[j] is byte[]) {
byte[] rgbOrig = (byte[]) rgArgValues[j];
byte[] rgbNew = new byte[rgbOrig.Length];
Array.Copy(rgbOrig, rgbNew, rgbOrig.Length);
_rgArgValues[j] = rgbNew;
continue;
}
if (rgArgValues[j] is int) {
_rgArgValues[j] = (int) rgArgValues[j];
continue;
}
if (rgArgValues[j] is CipherMode) {
_rgArgValues[j] = (int) rgArgValues[j];
continue;
}
}
_safeProvHandle = Utils.AcquireProvHandle(new CspParameters(Utils.DefaultRsaProviderType));
SafeKeyHandle safeKeyHandle = SafeKeyHandle.InvalidHandle;
// _ImportBulkKey will check for failures and throw an exception
Utils._ImportBulkKey(_safeProvHandle, algid, useSalt, _rgbKey, ref safeKeyHandle);
_safeKeyHandle = safeKeyHandle;
for (int i=0; i<cArgs; i++) {
switch (rgArgIds[i]) {
case Constants.KP_IV:
IVValue = (byte[]) _rgArgValues[i];
rgbValue = IVValue;
Utils.SetKeyParamRgb(_safeKeyHandle, _rgArgIds[i], rgbValue, rgbValue.Length);
break;
case Constants.KP_MODE:
ModeValue = (CipherMode) _rgArgValues[i];
dwValue = (Int32) _rgArgValues[i];
SetAsDWord:
Utils.SetKeyParamDw(_safeKeyHandle, _rgArgIds[i], dwValue);
break;
case Constants.KP_MODE_BITS:
dwValue = (Int32) _rgArgValues[i];
goto SetAsDWord;
case Constants.KP_EFFECTIVE_KEYLEN:
dwValue = (Int32) _rgArgValues[i];
goto SetAsDWord;
default:
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeyParameter"), "_rgArgIds[i]");
}
}
}
public void Dispose() {
Clear();
}
[System.Security.SecuritySafeCritical] // auto-generated
public void Clear() {
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecurityCritical] // auto-generated
private void Dispose(bool disposing) {
if (disposing) {
// We need to always zeroize the following fields because they contain sensitive data
if (_rgbKey != null) {
Array.Clear(_rgbKey,0,_rgbKey.Length);
_rgbKey = null;
}
if (IVValue != null) {
Array.Clear(IVValue,0,IVValue.Length);
IVValue = null;
}
if (_depadBuffer != null) {
Array.Clear(_depadBuffer, 0, _depadBuffer.Length);
_depadBuffer = null;
}
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) {
_safeKeyHandle.Dispose();
}
if (_safeProvHandle != null && !_safeProvHandle.IsClosed) {
_safeProvHandle.Dispose();
}
}
}
//
// public properties
//
public IntPtr KeyHandle {
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get { return _safeKeyHandle.DangerousGetHandle(); }
}
public int InputBlockSize {
get { return(BlockSizeValue/8); }
}
public int OutputBlockSize {
get { return(BlockSizeValue/8); }
}
public bool CanTransformMultipleBlocks {
get { return(true); }
}
public bool CanReuseTransform {
get { return(true); }
}
//
// public methods
//
// This routine resets the internal state of the CryptoAPITransform
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public void Reset() {
_depadBuffer = null;
// just ensure we've called CryptEncrypt with the true flag
byte[] temp = null;
Utils._EncryptData(_safeKeyHandle, EmptyArray<Byte>.Value, 0, 0, ref temp, 0, PaddingValue, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) {
// Note: special handling required if decrypting & using padding because the padding adds to the end of the last
// block, we have to buffer an entire block's worth of bytes in case what I just transformed turns out to be
// the last block Then in TransformFinalBlock we strip off the padding.
if (inputBuffer == null) throw new ArgumentNullException("inputBuffer");
if (outputBuffer == null) throw new ArgumentNullException("outputBuffer");
if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ((inputCount <= 0) || (inputCount % InputBlockSize != 0) || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (encryptOrDecrypt == CryptoAPITransformMode.Encrypt) {
// if we're encrypting we can always push out the bytes because no padding mode
// removes bytes during encryption
return Utils._EncryptData(_safeKeyHandle, inputBuffer, inputOffset, inputCount, ref outputBuffer, outputOffset, PaddingValue, false);
} else {
if (PaddingValue == PaddingMode.Zeros || PaddingValue == PaddingMode.None) {
// like encryption, if we're using None or Zeros padding on decrypt we can write out all
// the bytes. Note that we cannot depad a block partially padded with Zeros because
// we can't tell if those zeros are plaintext or pad.
return Utils._DecryptData(_safeKeyHandle, inputBuffer, inputOffset, inputCount, ref outputBuffer, outputOffset, PaddingValue, false);
} else {
// OK, now we're in the special case. Check to see if this is the *first* block we've seen
// If so, buffer it and return null zero bytes
if (_depadBuffer == null) {
_depadBuffer = new byte[InputBlockSize];
// copy the last InputBlockSize bytes to _depadBuffer everything else gets processed and returned
int inputToProcess = inputCount - InputBlockSize;
Buffer.InternalBlockCopy(inputBuffer, inputOffset+inputToProcess, _depadBuffer, 0, InputBlockSize);
return Utils._DecryptData(_safeKeyHandle, inputBuffer, inputOffset, inputToProcess, ref outputBuffer, outputOffset, PaddingValue, false);
} else {
// we already have a depad buffer, so we need to decrypt that info first & copy it out
int r = Utils._DecryptData(_safeKeyHandle, _depadBuffer, 0, _depadBuffer.Length, ref outputBuffer, outputOffset, PaddingValue, false);
outputOffset += OutputBlockSize;
int inputToProcess = inputCount - InputBlockSize;
Buffer.InternalBlockCopy(inputBuffer, inputOffset+inputToProcess, _depadBuffer, 0, InputBlockSize);
r = Utils._DecryptData(_safeKeyHandle, inputBuffer, inputOffset, inputToProcess, ref outputBuffer, outputOffset, PaddingValue, false);
return (OutputBlockSize + r);
}
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) {
if (inputBuffer == null) throw new ArgumentNullException("inputBuffer");
if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if ((inputCount < 0) || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (encryptOrDecrypt == CryptoAPITransformMode.Encrypt) {
// If we're encrypting we can always return what we compute because there's no _depadBuffer
byte[] transformedBytes = null;
Utils._EncryptData(_safeKeyHandle, inputBuffer, inputOffset, inputCount, ref transformedBytes, 0, PaddingValue, true);
Reset();
return transformedBytes;
} else {
if (inputCount%InputBlockSize != 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_SSD_InvalidDataSize"));
if (_depadBuffer == null) {
byte[] transformedBytes = null;
Utils._DecryptData(_safeKeyHandle, inputBuffer, inputOffset, inputCount, ref transformedBytes, 0, PaddingValue, true);
Reset();
return transformedBytes;
} else {
byte[] temp = new byte[_depadBuffer.Length + inputCount];
Buffer.InternalBlockCopy(_depadBuffer, 0, temp, 0, _depadBuffer.Length);
Buffer.InternalBlockCopy(inputBuffer, inputOffset, temp, _depadBuffer.Length, inputCount);
byte[] transformedBytes = null;
Utils._DecryptData(_safeKeyHandle, temp, 0, temp.Length, ref transformedBytes, 0, PaddingValue, true);
Reset();
return transformedBytes;
}
}
}
}
#endif // FEATURE_MACL && FEATURE_CRYPTO
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[Flags]
public enum CspProviderFlags {
NoFlags = 0x0000,
UseMachineKeyStore = 0x0001,
UseDefaultKeyContainer = 0x0002,
UseNonExportableKey = 0x0004,
UseExistingKey = 0x0008,
UseArchivableKey = 0x0010,
UseUserProtectedKey = 0x0020,
NoPrompt = 0x0040,
CreateEphemeralKey = 0x0080
}
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class CspParameters
{
public int ProviderType;
public string ProviderName;
[ResourceExposure(ResourceScope.Machine)]
public string KeyContainerName;
public int KeyNumber;
private int m_flags;
public CspProviderFlags Flags {
get { return (CspProviderFlags) m_flags; }
set {
int allFlags = 0x00FF; // this should change if more values are added to CspProviderFlags
Contract.Assert((CspProviderFlags.UseMachineKeyStore |
CspProviderFlags.UseDefaultKeyContainer |
CspProviderFlags.UseNonExportableKey |
CspProviderFlags.UseExistingKey |
CspProviderFlags.UseArchivableKey |
CspProviderFlags.UseUserProtectedKey |
CspProviderFlags.NoPrompt |
CspProviderFlags.CreateEphemeralKey) == (CspProviderFlags)allFlags, "allFlags does not match all CspProviderFlags");
int flags = (int) value;
if ((flags & ~allFlags) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)value), "value");
m_flags = flags;
}
}
#if FEATURE_MACL || MONO
private CryptoKeySecurity m_cryptoKeySecurity;
public CryptoKeySecurity CryptoKeySecurity {
get {
return m_cryptoKeySecurity;
}
set {
m_cryptoKeySecurity = value;
}
}
#endif
#if (FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS) || FEATURE_CORECLR
private SecureString m_keyPassword;
public SecureString KeyPassword {
get {
return m_keyPassword;
}
set {
m_keyPassword = value;
// Parent handle and PIN are mutually exclusive.
m_parentWindowHandle = IntPtr.Zero;
}
}
private IntPtr m_parentWindowHandle;
public IntPtr ParentWindowHandle {
[ResourceExposure(ResourceScope.Machine)]
get {
return m_parentWindowHandle;
}
[ResourceExposure(ResourceScope.Machine)]
set {
m_parentWindowHandle = value;
// Parent handle and PIN are mutually exclusive.
m_keyPassword = null;
}
}
#endif
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public CspParameters () : this(Utils.DefaultRsaProviderType, null, null) {}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public CspParameters (int dwTypeIn) : this(dwTypeIn, null, null) {}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public CspParameters (int dwTypeIn, string strProviderNameIn) : this(dwTypeIn, strProviderNameIn, null) {}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public CspParameters (int dwTypeIn, string strProviderNameIn, string strContainerNameIn) :
this (dwTypeIn, strProviderNameIn, strContainerNameIn, CspProviderFlags.NoFlags) {}
#if MONO || (FEATURE_MACL && FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS)
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public CspParameters (int providerType, string providerName, string keyContainerName,
CryptoKeySecurity cryptoKeySecurity, SecureString keyPassword)
: this (providerType, providerName, keyContainerName) {
m_cryptoKeySecurity = cryptoKeySecurity;
m_keyPassword = keyPassword;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public CspParameters (int providerType, string providerName, string keyContainerName,
CryptoKeySecurity cryptoKeySecurity, IntPtr parentWindowHandle)
: this (providerType, providerName, keyContainerName) {
m_cryptoKeySecurity = cryptoKeySecurity;
m_parentWindowHandle = parentWindowHandle;
}
#endif // #if FEATURE_MACL && FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS
[ResourceExposure(ResourceScope.Machine)]
internal CspParameters (int providerType, string providerName, string keyContainerName, CspProviderFlags flags) {
ProviderType = providerType;
ProviderName = providerName;
KeyContainerName = keyContainerName;
KeyNumber = -1;
Flags = flags;
}
// copy constructor
internal CspParameters (CspParameters parameters) {
ProviderType = parameters.ProviderType;
ProviderName = parameters.ProviderName;
KeyContainerName = parameters.KeyContainerName;
KeyNumber = parameters.KeyNumber;
Flags = parameters.Flags;
#if FEATURE_MACL || MONO
m_cryptoKeySecurity = parameters.m_cryptoKeySecurity;
#endif // FEATURE_MACL
#if FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS
m_keyPassword = parameters.m_keyPassword;
m_parentWindowHandle = parameters.m_parentWindowHandle;
#endif // FEATURE_CRYPTO && FEATURE_X509_SECURESTRINGS
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Data.SqlClient
{
internal sealed class SNILoadHandle : SafeHandle
{
internal static readonly SNILoadHandle SingletonInstance = new SNILoadHandle();
internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate ReadAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(ReadDispatcher);
internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate WriteAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(WriteDispatcher);
private readonly UInt32 _sniStatus = TdsEnums.SNI_UNINITIALIZED;
private readonly EncryptionOptions _encryptionOption;
private SNILoadHandle() : base(IntPtr.Zero, true)
{
// From security review - SafeHandle guarantees this is only called once.
// The reason for the safehandle is guaranteed initialization and termination of SNI to
// ensure SNI terminates and cleans up properly.
try { }
finally
{
_sniStatus = SNINativeMethodWrapper.SNIInitialize();
UInt32 value = 0;
// VSDevDiv 479597: If initialize fails, don't call QueryInfo.
if (TdsEnums.SNI_SUCCESS == _sniStatus)
{
// Query OS to find out whether encryption is supported.
SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, ref value);
}
_encryptionOption = (value == 0) ? EncryptionOptions.NOT_SUP : EncryptionOptions.OFF;
base.handle = (IntPtr)1; // Initialize to non-zero dummy variable.
}
}
public override bool IsInvalid
{
get
{
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle()
{
if (base.handle != IntPtr.Zero)
{
if (TdsEnums.SNI_SUCCESS == _sniStatus)
{
LocalDBAPI.ReleaseDLLHandles();
SNINativeMethodWrapper.SNITerminate();
}
base.handle = IntPtr.Zero;
}
return true;
}
public UInt32 Status
{
get
{
return _sniStatus;
}
}
public EncryptionOptions Options
{
get
{
return _encryptionOption;
}
}
private static void ReadDispatcher(IntPtr key, IntPtr packet, UInt32 error)
{
// This is the app-domain dispatcher for all async read callbacks, It
// simply gets the state object from the key that it is passed, and
// calls the state object's read callback.
Debug.Assert(IntPtr.Zero != key, "no key passed to read callback dispatcher?");
if (IntPtr.Zero != key)
{
// NOTE: we will get a null ref here if we don't get a key that
// contains a GCHandle to TDSParserStateObject; that is
// very bad, and we want that to occur so we can catch it.
GCHandle gcHandle = (GCHandle)key;
TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
if (null != stateObj)
{
stateObj.ReadAsyncCallback(IntPtr.Zero, packet, error);
}
}
}
private static void WriteDispatcher(IntPtr key, IntPtr packet, UInt32 error)
{
// This is the app-domain dispatcher for all async write callbacks, It
// simply gets the state object from the key that it is passed, and
// calls the state object's write callback.
Debug.Assert(IntPtr.Zero != key, "no key passed to write callback dispatcher?");
if (IntPtr.Zero != key)
{
// NOTE: we will get a null ref here if we don't get a key that
// contains a GCHandle to TDSParserStateObject; that is
// very bad, and we want that to occur so we can catch it.
GCHandle gcHandle = (GCHandle)key;
TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
if (null != stateObj)
{
stateObj.WriteAsyncCallback(IntPtr.Zero, packet, error);
}
}
}
}
internal sealed class SNIHandle : SafeHandle
{
private readonly UInt32 _status = TdsEnums.SNI_UNINITIALIZED;
private readonly bool _fSync = false;
// creates a physical connection
internal SNIHandle(
SNINativeMethodWrapper.ConsumerInfo myInfo,
string serverName,
byte[] spnBuffer,
bool ignoreSniOpenTimeout,
int timeout,
out byte[] instanceName,
bool flushCache,
bool fSync,
bool fParallel)
: base(IntPtr.Zero, true)
{
try { }
finally
{
_fSync = fSync;
instanceName = new byte[256]; // Size as specified by netlibs.
if (ignoreSniOpenTimeout)
{
timeout = Timeout.Infinite; // -1 == native SNIOPEN_TIMEOUT_VALUE / INFINITE
}
_status = SNINativeMethodWrapper.SNIOpenSyncEx(myInfo, serverName, ref base.handle,
spnBuffer, instanceName, flushCache, fSync, timeout, fParallel);
}
}
// constructs SNI Handle for MARS session
internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true)
{
try { }
finally
{
_status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync);
}
}
public override bool IsInvalid
{
get
{
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle()
{
// NOTE: The SafeHandle class guarantees this will be called exactly once.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
if (IntPtr.Zero != ptr)
{
if (0 != SNINativeMethodWrapper.SNIClose(ptr))
{
return false; // SNIClose should never fail.
}
}
return true;
}
internal UInt32 Status
{
get
{
return _status;
}
}
}
internal sealed class SNIPacket : SafeHandle
{
internal SNIPacket(SafeHandle sniHandle) : base(IntPtr.Zero, true)
{
SNINativeMethodWrapper.SNIPacketAllocate(sniHandle, SNINativeMethodWrapper.IOType.WRITE, ref base.handle);
if (IntPtr.Zero == base.handle)
{
throw SQL.SNIPacketAllocationFailure();
}
}
public override bool IsInvalid
{
get
{
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle()
{
// NOTE: The SafeHandle class guarantees this will be called exactly once.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
if (IntPtr.Zero != ptr)
{
SNINativeMethodWrapper.SNIPacketRelease(ptr);
}
return true;
}
}
internal sealed class WritePacketCache : IDisposable
{
private bool _disposed;
private Stack<SNIPacket> _packets;
public WritePacketCache()
{
_disposed = false;
_packets = new Stack<SNIPacket>();
}
public SNIPacket Take(SNIHandle sniHandle)
{
SNIPacket packet;
if (_packets.Count > 0)
{
// Success - reset the packet
packet = _packets.Pop();
SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
}
else
{
// Failed to take a packet - create a new one
packet = new SNIPacket(sniHandle);
}
return packet;
}
public void Add(SNIPacket packet)
{
if (!_disposed)
{
_packets.Push(packet);
}
else
{
// If we're disposed, then get rid of any packets added to us
packet.Dispose();
}
}
public void Clear()
{
while (_packets.Count > 0)
{
_packets.Pop().Dispose();
}
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
Clear();
}
}
}
}
| |
// Copyright(C) 2002-2012 Hugo Rumayor Montemayor, All rights reserved.
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using ID3Lib.Exceptions;
using ID3Lib.Frames;
namespace ID3Lib
{
/// <summary>
/// Manage ID3v1 frames
/// </summary>
/// <remarks>
/// The <b>ID3v1</b> class can read an ID3v1 frame form a mp3 file returning the <see cref="FrameModel"/> and
/// write an ID3v1 form the FrameModel to a mp3 file, it will ignore any fields not supported in ID3v1 tag format.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "It is the name of the standard"),
SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "v")]
public class ID3v1
{
#region Constants
private static readonly byte[] _id3 = { 0x54, 0x41, 0x47 }; //"TAG"
private static readonly string[] _genres =
{
"Blues","Classic Rock","Country","Dance","Disco","Funk","Grunge","Hip-Hop","Jazz","Metal",
"New Age","Oldies","Other","Pop","R&B","Rap","Reggae","Rock","Techno","Industrial",
"Alternative","Ska","Death Metal","Pranks","Soundtrack","Euro-Techno","Ambient","Trip-Hop",
"Vocal","Jazz+Funk","Fusion","Trance","Classical","Instrumental","Acid","House",
"Game","Sound Clip","Gospel","Noise","Alternative Rock","Bass","Soul","Punk","Space",
"Meditative","Instrumental Pop","Instrumental Rock","Ethnic","Gothic",
"Darkwave","Techno-Industrial","Electronic","Pop-Folk","Eurodance","Dream",
"Southern Rock","Comedy","Cult","Gangsta","Top 40","Christian Rap","Pop/Funk","Jungle",
"Native American","Cabaret","New Wave","Psychadelic","Rave","Showtunes","Trailer","Lo-Fi",
"Tribal","Acid Punk","Acid Jazz","Polka","Retro","Musical","Rock & Roll","Hard Rock","Folk",
"Folk/Rock","National Folk","Swing","Fast-Fusion","Bebob","Latin","Revival","Celtic","Bluegrass",
"Avantgarde","Gothic Rock","Progressive Rock","Psychedelic Rock","Symphonic Rock","Slow Rock",
"Big Band","Chorus","Easy Listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber Music",
"Sonata","Symphony","Booty Bass","Primus","Porn Groove","Satire","Slow Jam","Club",
"Tango","Samba","Folklore","Ballad","Power Ballad","Rhytmic Soul","Freestyle","Duet",
"Punk Rock","Drum Solo","Acapella","Euro-House","Dance Hall","Goa","Drum & Bass","Club-House",
"Hardcore","Terror","Indie","BritPop","Negerpunk","Polsk Punk","Beat","Christian Gangsta Rap",
"Heavy Metal","Black Metal","Crossover","Contemporary Christian",
"Christian Rock","Merengue","Salsa","Trash Metal","Anime","JPop","SynthPop"
};
#endregion
#region Fields
private string _song;
private string _artist;
private string _album;
private string _year;
private string _comment;
private byte _track;
private byte _genre;
#endregion
#region Properties
/// <summary>
/// ID3v1 tag length
/// </summary>
public static uint TagLength
{
get { return 128; }
}
/// <summary>
/// Get the title/song name/content description.
/// </summary>
public string Song
{
get { return _song; }
}
/// <summary>
/// Get the lead performer/soloist.
/// </summary>
public string Artist
{
get { return _artist; }
}
/// <summary>
/// Get the production year.
/// </summary>
public string Year
{
get { return _year; }
}
/// <summary>
/// Get the album title.
/// </summary>
public string Album
{
get { return _album; }
}
/// <summary>
/// Get the track/artist comment.
/// </summary>
public string Comment
{
get { return _comment; }
}
/// <summary>
/// Get the track number.
/// </summary>
public byte Track
{
get { return _track; }
}
/// <summary>
/// Get the track genre.
/// </summary>
public byte Genre
{
get { return _genre; }
}
/// <summary>
/// Get or set the ID3v2 FrameModel.
/// </summary>
public TagModel FrameModel
{
get { return GetFrameModel(); }
set { SetFrameModel(value); }
}
private TagModel GetFrameModel()
{
var frameModel = new TagModel();
var frameText = new FrameText("TIT2");
frameText.TextCode = TextCode.Ascii;
frameText.Text = _song;
frameModel.Add(frameText);
frameText = new FrameText("TPE1");
frameText.TextCode = TextCode.Ascii;
frameText.Text = _artist;
frameModel.Add(frameText);
frameText = new FrameText("TALB");
frameText.TextCode = TextCode.Ascii;
frameText.Text = _album;
frameModel.Add(frameText);
frameText = new FrameText("TYER");
frameText.TextCode = TextCode.Ascii;
frameText.Text = _year;
frameModel.Add(frameText);
frameText = new FrameText("TRCK");
frameText.TextCode = TextCode.Ascii;
frameText.Text = _track.ToString(CultureInfo.InvariantCulture);
frameModel.Add(frameText);
var frameFullText = new FrameFullText("COMM");
frameFullText.TextCode = TextCode.Ascii;
frameFullText.Language = "eng";
frameFullText.Description = "";
frameFullText.Text = _comment;
frameModel.Add(frameFullText);
if (_genre >= 0 && _genre < _genres.Length)
{
// from suggestion in http://sourceforge.net/tracker2/?func=detail&aid=920249&group_id=89188&atid=589317
frameText = new FrameText("TCON");
frameText.TextCode = TextCode.Ascii;
frameText.Text = _genres[_genre];
frameModel.Add(frameText);
}
//TODO: Fix this code!!!!!!!!
frameModel.Header.TagSize = 0; //TODO: Invalid size, not filled in until write
frameModel.Header.Version = 3; // ID3v2.[3].[0]
frameModel.Header.Revision = 0;
frameModel.Header.Unsync = false;
frameModel.Header.Experimental = false;
frameModel.Header.Footer = false;
frameModel.Header.ExtendedHeader = false;
return frameModel;
}
private void SetFrameModel(TagModel frameModel)
{
Clear();
foreach (var frame in frameModel)
{
switch (frame.FrameId)
{
case "TIT2":
_song = GetTagText(frame);
break;
case "TPE1":
_artist = GetTagText(frame);
break;
case "TALB":
_album = GetTagText(frame);
break;
case "TYER":
_year = GetTagText(frame);
break;
case "TRCK":
if (!byte.TryParse(GetTagText(frame), out _track))
_track = 0;
break;
case "TCON":
_genre = ParseGenre(GetTagText(frame));
break;
case "COMM":
_comment = GetTagText(frame);
break;
}
}
}
private static string GetTagText(FrameBase tag)
{
var frameText = tag as FrameText;
if (frameText != null)
return frameText.Text;
var frameFullText = tag as FrameFullText;
if (frameFullText != null)
return frameFullText.Text;
return null;
}
private static byte ParseGenre(string sGenre)
{
if (String.IsNullOrEmpty(sGenre))
return 255;
// test for a simple number in the field
byte nGenre;
if (byte.TryParse(sGenre, out nGenre))
return nGenre;
// "References to the ID3v1 genres can be made by, as first byte,
// enter "(" followed by a number from the genres list (appendix A)
// and ended with a ")" character."
if (sGenre[0] == '(' && sGenre[1] != '(')
{
int close = sGenre.IndexOf(')');
if (close != -1)
{
string sGNum = sGenre.Substring(1, close - 1);
if (Byte.TryParse(sGNum, out nGenre))
return nGenre;
}
}
// not a number, see if it's one of the predefined genre name strings
byte index = 0;
foreach (string name in _genres)
{
if (String.Equals(name.Trim(), sGenre, StringComparison.OrdinalIgnoreCase))
return index;
++index;
}
return 12; // "Other"
}
#endregion
#region Constructors
/// <summary>
/// ID3v1 tag manager
/// </summary>
public ID3v1()
{
Clear();
}
#endregion
#region Methods
private void Clear()
{
_song = "";
_artist = "";
_album = "";
_year = "";
_comment = "";
_track = 0;
_genre = 255;
}
private static string GetString(Encoding encoding, byte[] tag)
{
// I had to use Memory.FindByte function because the encoding function
// retrieves the 0x00 values and doesn't stop on the first zero. so makes strings with
// many trailing zeros at the end when converted to XML these are added in binary text.
int index = Memory.FindByte(tag, 0x00, 0);
return index < 0 ? encoding.GetString(tag) : encoding.GetString(tag, 0, index);
}
/// <summary>
/// Load tag from stream
/// </summary>
/// <param name="src">Binary stream to load</param>
public void Deserialize(Stream stream)
{
BinaryReader reader = new BinaryReader(stream);
var encoding = Encoding.GetEncoding(1252); // Should be ASCII
// check for ID3v1 tag
reader.BaseStream.Seek(-128, SeekOrigin.End);
byte[] idTag = new byte[3];
// Read the tag identifier
reader.Read(idTag, 0, 3);
// Compare the read tag
if (Memory.Compare(_id3, idTag) != true)
throw new TagNotFoundException("ID3v1 tag was not found");
byte[] tag = new byte[30]; // Allocate ID3 tag
reader.Read(tag, 0, 30);
_song = GetString(encoding, tag);
reader.Read(tag, 0, 30);
_artist = GetString(encoding, tag);
reader.Read(tag, 0, 30);
_album = GetString(encoding, tag);
reader.Read(tag, 0, 4);
_year = (tag[0] != 0 && tag[1] != 0 && tag[2] != 0 && tag[3] != 0) ? encoding.GetString(tag, 0, 4) : String.Empty;
reader.Read(tag, 0, 30);
if (tag[28] == 0) //Track number was stored at position 29 later hack of the original standard.
{
_track = tag[29];
_comment = encoding.GetString(tag, 0, Memory.FindByte(tag, 0x00, 0));
}
else
{
_track = 0;
_comment = GetString(encoding, tag);
}
_genre = reader.ReadByte();
}
/// <summary>
/// Save tag from stream
/// </summary>
/// <param name="stream">Binary stream to save</param>
public void Serialize(Stream stream)
{
var idTag = new byte[3];
// open a reader on the underlying stream but don't use 'using'
// or Dispose will close the underlying stream at the end
var reader = new BinaryReader(stream);
// check for ID3v1 tag
reader.BaseStream.Seek(-128, SeekOrigin.End);
// Read the tag identifier
reader.Read(idTag, 0, 3);
// Is there a ID3v1 tag already?
if (Memory.Compare(_id3, idTag) == true)
{
//Found a ID3 tag so we will over write the old tag
// (and the 'TAG' label too, so WriteAtStreamPosition is clean)
stream.Seek(-128, SeekOrigin.End);
Write(stream);
}
else
{
//Create a new Tag
var position = stream.Position;
stream.Seek(0, SeekOrigin.End);
//TODO: fix this ugly code, at first make the error visible to the user by some means,
// a start can be throwing the exception in an inner exception
try
{
Write(stream);
}
catch (Exception e)
{
// There was an error while creating the tag
// Restore the file to the original state, I hope.
stream.SetLength(position);
throw e;
}
}
}
/// <summary>
/// overwrite or append ID3v1 tag at current location in the stream
/// </summary>
/// <param name="stream"></param>
public void Write(Stream stream)
{
// open a writer on the underlying stream but don't use 'using'
// or Dispose will close the underlying stream at the end
var writer = new BinaryWriter(stream);
var encoding = Encoding.GetEncoding(1252); // Should be ASCII
writer.Write(_id3, 0, 3); // Write the ID3 TAG ID: 'TAG'
byte[] tag = new byte[30];
if (_song.Length > 30)
{
_song = _song.Substring(0, 30);
}
encoding.GetBytes(_song, 0, _song.Length, tag, 0);
writer.Write(tag, 0, 30);
Memory.Clear(tag, 0, 30);
if (_artist.Length > 30)
{
_artist = _artist.Substring(0, 30);
}
encoding.GetBytes(_artist, 0, _artist.Length, tag, 0);
writer.Write(tag, 0, 30);
Memory.Clear(tag, 0, 30);
if (_album.Length > 30)
{
_album = _album.Substring(0, 30);
}
encoding.GetBytes(_album, 0, _album.Length, tag, 0);
writer.Write(tag, 0, 30);
Memory.Clear(tag, 0, 30);
if (String.IsNullOrEmpty(_year))
{
Memory.Clear(tag, 0, 30);
}
else
{
UInt16 year;
if (!UInt16.TryParse(_year, out year))
_year = "0";
if (year > 9999)
_year = "0";
encoding.GetBytes(_year, 0, _year.Length, tag, 0);
}
writer.Write(tag, 0, 4);
Memory.Clear(tag, 0, 30);
if (_comment.Length > 28)
_comment = _comment.Substring(0, 28);
encoding.GetBytes(_comment, 0, _comment.Length, tag, 0);
writer.Write(tag, 0, 28);
Memory.Clear(tag, 0, 30);
writer.Write((byte)0);
writer.Write((byte)_track);
writer.Write((byte)_genre);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MyCustomWebService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace NotJavaScript.Tree
{
public class EmptyStatment : Statement
{
public void _PhpOf(Environment E, StringWriter O)
{
O.Write(";");
}
public void _WellType(Environment E)
{
}
}
public class Assert : Statement
{
public Expression Guard;
public Block Code;
DebugInformation Debug;
public Assert(Expression e, Block b, DebugInformation di)
{
Guard = e;
Code = b;
Debug = di;
}
public void _WellType(Environment E)
{
if (!(Guard._TypeOf(E) is Type_Boolean))
{
throw new Exception("argh");
}
if (Code != null)
Code._WellType(E);
}
public void _PhpOf(Environment E, StringWriter O)
{
O.WriteLine("if(!(");
Guard._PhpOf(E, O);
O.Write(")) { SYSTEM_KIRA_assert(" + Debug.LineNumber + "," + Debug.CharacterNum + ");");
if (Code != null)
{
O.WriteLine();
Code._PhpOf2(E, O);
}
else
{
O.WriteLine(" }");
}
}
}
public class StatementWrap : Statement
{
DebugInformation Debug;
Statement S;
public StatementWrap(Statement s, DebugInformation d)
{
S = s;
Debug = d;
}
public void _WellType(Environment E)
{
S._WellType(E);
}
public void _PhpOf(Environment E, StringWriter O)
{
S._PhpOf(E, O);
}
}
public class CodePump : Statement
{
public string IdentName;
public Block Code;
public CodePump(string ident)
{
IdentName = ident;
Code = null;
}
public void Use(Environment E)
{
if (Code == null)
{
try
{
Code = E.Segments[IdentName];
}
catch (Exception erz)
{
Console.Error.WriteLine("[TODO] Failed to find Segment");
throw erz;
}
}
}
public void _WellType(Environment E)
{
Use(E);
Code._WellType(E);
}
public void _PhpOf(Environment E, StringWriter O)
{
Use(E);
Code._PhpOf2(E, O);
}
}
public class Block : Statement
{
List<Statement> Statements;
public DebugRange Debug;
public Block()
{
Statements = new List<Statement>();
}
public void SetDebug(DebugRange dr)
{
Debug = dr;
}
public void Add(Statement s)
{
Statements.Add(s);
}
public void _WellType(Environment E)
{
E.Push();
bool Err = false;
int k = 0;
foreach (Statement S in Statements)
{
try
{
S._WellType(E);
}
catch (Exception err)
{
string zea = err.ToString();
Err = true;
Console.Error.WriteLine(Debug.ErrorPrefix(2000) + "Statement " + k + " can not be well typed");
}
k++;
}
E.Pop();
if (Err)
{
throw new Exception("Block Failure");
}
}
public void _PhpOfR(Environment E, StringWriter O, bool Br)
{
E.Push();
StringWriter Inn = new StringWriter();
foreach (Statement S in Statements)
{
StringWriter L = new StringWriter();
S._PhpOf(E, L);
Inn.Write(L.ToString());
}
if (Br) O.WriteLine("{");
List<string> D = E.GetScopeDifferential();
List<string> G = E.GetPotentialGarbage();
string uP = "" + E.AnonyClassCounter;
foreach (string x in D)
{
O.WriteLine("$__" + uP + "__" + x + "=$" + x + ";");
}
O.Write(Inn);
foreach (string g in G)
{
if (!D.Contains(g))
{
O.WriteLine("unset($" + g + ");");
}
}
foreach (string x in D)
{
O.WriteLine("$" + x + "=$__" + uP + "__" + x + ";");
}
if (Br) O.WriteLine("}");
E.Pop();
}
public void _PhpOf(Environment E, StringWriter O)
{
_PhpOfR(E, O, true);
}
public void _PhpOf2(Environment E, StringWriter O)
{
_PhpOfR(E, O, false);
/*
E.Push();
int k = 0;
foreach (Statement S in Statements)
{
StringWriter L = new StringWriter();
S._PhpOf(E, L);
O.Write(L.ToString());
}
E.Pop();
*/
}
public bool hasDatabase()
{
foreach (Statement S in Statements)
{
if (S is Block)
{
if ((S as Block).hasDatabase())
return true;
}
if (S is DatabaseConn) return true;
}
return false;
}
}
public class SingleDecl
{
public string X;
public Expression V;
public DebugInformation Debug;
}
public class Declaration : Statement
{
List<SingleDecl> Variables;
gType Typing;
public Declaration(gType Typ)
{
Typing = Typ;
Variables = new List<SingleDecl>();
}
public void Decl(string x)
{
SingleDecl SD = new SingleDecl();
SD.X = x;
SD.V = new Constant_Empty();
Variables.Add(SD);
}
public void Assign(string x, Expression e, DebugInformation di)
{
foreach (SingleDecl SD in Variables)
{
if (SD.X.Equals(x))
{
SD.V = e;
SD.Debug = di;
}
}
}
public void _WellType(Environment E)
{
if (Typing != null)
{
bool Err = false;
int k = 0;
foreach (SingleDecl D in Variables)
{
E.Declare(D.X, Typing);
if (!(D.V is Constant_Empty))
{
gType T;
try
{
T = D.V._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(D.Debug.ErrorPrefix(1000) + "Expression could not type");
throw er;
}
if (T is Type_Unknown)
{
}
else
{
if (!Typing.Suitable(E, T))
{
Err = true;
Console.Error.WriteLine(D.Debug.ErrorPrefix(2001) + "Declared assignment(" + k + ") failed due to typing, expecting [" + Typing.str() + "] got [" + T.str() + "]");
}
}
}
k++;
}
if (Err)
{
throw new Exception("Declared Assignement");
}
}
else
{
foreach (SingleDecl D in Variables)
{
if ((D.V is Constant_Empty))
{
// [ NEW ERROR HERE ]
throw new Exception("ugh");
//Console.Error.WriteLine(D.Debug.ErrorPrefix(2001) + "Declared assignment(" + k + ") failed due to typing, expecting [" + Typing.str() + "] got [" + T.str() + "]");
}
gType T;
try
{
T = D.V._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(D.Debug.ErrorPrefix(1000) + "Expression could not type");
throw er;
}
E.Declare(D.X, T);
}
}
}
public void _PhpOf(Environment E, StringWriter O)
{
if (Typing != null)
{
int k = 0;
foreach (SingleDecl D in Variables)
{
E.Declare(D.X, Typing);
//O.WriteLine("/* DECLARE[" + D.X + ":" + Typing.str() + "] */");
if (!(D.V is Constant_Empty))
{
gType TT = D.V._TypeOf(E);
if (!(TT is Type_Unknown))
{
if (Typing.Suitable(E, TT))
{
O.Write("$" + D.X + "=");
D.V._PhpOf(E, O);
O.WriteLine(";");
}
else
{
throw new Exception("Typing Failure 001: Expecting:" + Typing.str() + ", got:" + D.V._TypeOf(E).str());
}
}
}
k++;
}
}
else
{
foreach (SingleDecl D in Variables)
{
if ((D.V is Constant_Empty))
{
// [ NEW ERROR HERE ]
throw new Exception("ugh");
//Console.Error.WriteLine(D.Debug.ErrorPrefix(2001) + "Declared assignment(" + k + ") failed due to typing, expecting [" + Typing.str() + "] got [" + T.str() + "]");
}
gType T;
try
{
T = D.V._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(D.Debug.ErrorPrefix(1000) + "Expression could not type");
throw er;
}
E.Declare(D.X, T);
O.Write("$" + D.X + "=");
D.V._PhpOf(E, O);
O.WriteLine(";");
}
}
}
}
public class Assignment
{
Expression exprL;
Expression exprR;
string AssOp;
bool I;
bool D;
DebugInformation Debug;
public Assignment(Expression e, DebugInformation di)
{
exprL = e;
I = false;
D = false;
Debug = di;
}
public Assignment(Expression e)
{
exprL = e;
I = false;
D = false;
}
public void SetDebug(DebugInformation di)
{
Debug = di;
}
public void SetRight(string o, Expression e)
{
AssOp = o;
exprR = e;
}
public void Inc()
{
I = true;
}
public void Dec()
{
D = true;
}
public bool SimpleLeft()
{
if (exprL is ArrayReference)
{
return ((exprL as ArrayReference).expr is Variable);
}
if (exprL is DotReference)
{
return ((exprL as DotReference).expr is Variable);
}
return true;
}
public string _PhpAssignOp2BinaryOp(string x)
{
if (x.Equals("+=")) return "+";
if (x.Equals("||=")) return "||";
if (x.Equals("&&=")) return "&&";
if (x.Equals("^^=")) return " xor ";
if (x.Equals("-=")) return "-";
if (x.Equals("*=")) return "%";
if (x.Equals("/=")) return "/";
if (x.Equals("%=")) return "%";
if (x.Equals("@=")) return ".";
return ".";
}
public string _PhpFixOp(string x)
{
if (x.Equals("@=")) return ".=";
if (x.Equals("&&=")) return "&=";
if (x.Equals("||=")) return "|=";
if (x.Equals("^^=")) return "^=";
return x;
}
public void _WellType(Environment E)
{
gType T;
try
{
T = exprL._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type");
throw er;
}
if (SimpleLeft())
{
if (I)
{
if (!(T is Type_Unknown))
{
if (!(T is Type_Real || T is Type_Integer))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1500) + "Shorthand ++/-- requires numeric type");
throw new Exception("Invalidate Assignment Yo!");
}
}
return;
}
if (D)
{
if (!(T is Type_Unknown))
{
if (!(T is Type_Real || T is Type_Integer))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1500) + "Shorthand ++/-- requires numeric type");
throw new Exception("Invalidate Assignment Yo!");
}
}
return;
}
}
else
{
gType T2;
try
{
T2 = exprR._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type (Right Hand)");
throw er;
}
if (!(T is Type_Unknown || T2 is Type_Unknown))
{
if (AssOp.Equals("+=") || AssOp.Equals("-=") || AssOp.Equals("/=") || AssOp.Equals("*=") || AssOp.Equals("%="))
{
if (!(T is Type_Real || T is Type_Integer))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1501) + "Left hand of assignment should be numeric");
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
if (!(T2 is Type_Real || T2 is Type_Integer))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1501) + "Right hand of assignment should be numeric");
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
}
if (AssOp.Equals("&&=") || AssOp.Equals("||=") || AssOp.Equals("^^="))
{
if (!(T is Type_Boolean))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1502) + "Left hand of assignment should be boolean");
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
if (!(T2 is Type_Boolean))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1502) + "Right hand of assignment should be boolean");
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
}
if (AssOp.Equals("@="))
{
if (!(T is Type_String))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1503) + "Left hand of assignment should be a string");
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
if (!(T2 is Type_String))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1503) + "Right hand of assignment should be a string");
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
}
if (AssOp.Equals("="))
{
if (!T.Suitable(E, T2))
{
Console.Error.WriteLine(Debug.ErrorPrefix(1503) + "Right hand of assignment expecting [" + T.str() + "] got [" + T2.str() + "]");
throw new Exception("Invalidate Assignment Yo! " + AssOp + "[" + T.str() + " <= " + T2.str());
}
}
}
}
}
public void _PhpOf(Environment E, StringWriter O)
{
if (SimpleLeft())
{
// Need to give more Logic Here
exprL._PhpOf(E, O);
gType T = exprL._TypeOf(E);
if (I)
{
if (!(T is Type_Unknown))
{
if (!(T is Type_Real || T is Type_Integer))
{
throw new Exception("Invalidate Assignment Yo!");
}
}
O.Write("++");
return;
}
if (D)
{
if (!(T is Type_Unknown))
{
if (!(T is Type_Real || T is Type_Integer))
{
throw new Exception("Invalidate Assignment Yo!");
}
}
O.Write("--");
return;
}
gType T2 = exprR._TypeOf(E);
if (!(T is Type_Unknown || T2 is Type_Unknown))
{
if (AssOp.Equals("+=") || AssOp.Equals("-=") || AssOp.Equals("/=") || AssOp.Equals("*=") || AssOp.Equals("%="))
{
if (!(T is Type_Real || T is Type_Integer))
{
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
if (!(T2 is Type_Real || T2 is Type_Integer))
{
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
}
if (AssOp.Equals("&&=") || AssOp.Equals("||=") || AssOp.Equals("^^="))
{
if (!(T is Type_Boolean))
{
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
if (!(T2 is Type_Boolean))
{
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
}
if (AssOp.Equals("="))
{
if (!T.Suitable(E, T2))
{
throw new Exception("Invalidate Assignment Yo! " + AssOp + "[" + T.str() + " <= " + T2.str());
}
}
if (AssOp.Equals("@="))
{
if (!(T is Type_String))
{
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
if (!(T2 is Type_String))
{
throw new Exception("Invalidate Assignment Yo!" + AssOp);
}
}
}
O.Write(_PhpFixOp(AssOp));
exprR._PhpOf(E, O);
}
else
{
StringWriter NSS = new StringWriter();
if (I || D)
{
exprL._PhpOf(E, NSS);
string X = NSS.ToString();
if (I) X += "+1";
if (D) X += "-1";
(exprL as PhpOf2)._PhpOf2(E, O, X);
return;
}
StringWriter NSS2 = new StringWriter();
exprL._PhpOf(E, NSS);
exprR._PhpOf(E, NSS2);
string A = NSS.ToString();
string B = NSS2.ToString();
if (AssOp.Equals("="))
{
(exprL as PhpOf2)._PhpOf2(E, O, B);
}
else
{
(exprL as PhpOf2)._PhpOf2(E, O, A + _PhpAssignOp2BinaryOp(AssOp) + B);
}
}
}
}
public class AssignmentStatement : Statement
{
Assignment ass;
public AssignmentStatement(Assignment a)
{
ass = a;
}
public void _PhpOf(Environment E, StringWriter O)
{
ass._PhpOf(E, O);
O.WriteLine(";");
}
public void _WellType(Environment E)
{
ass._WellType(E);
}
}
public class Return : Statement
{
Expression e;
DebugInformation Debug;
public Return(DebugInformation di)
{
Debug = di;
e = new Constant_Empty();
}
public void Ev(Expression x)
{
e = x;
}
public void _WellType(Environment E)
{
if (E.CurrentReturnType is Type_Unit)
{
if (e is Constant_Empty)
{
return;
}
Console.Error.WriteLine(Debug.ErrorPrefix(2012) + "return not expecting result");
throw new Exception("err");
}
gType T;
try
{
T = e._TypeOf(E);
}
catch (Exception err)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type");
throw err;
}
if (!E.CurrentReturnType.Suitable(E, T))
{
Console.Error.WriteLine(Debug.ErrorPrefix(2002) + "Return type does not match function return, expecting [" + E.CurrentReturnType.str() + "] got [" + T.str() + "]");
throw new Exception("Return invalid");
}
}
public void _PhpOf(Environment E, StringWriter O)
{
if (E.InsideDatabaseConnection)
{
Console.Error.WriteLine(Debug.ErrorPrefix(3000) + "Can not return while inside a database connection");
throw new Exception("can't return while inside a database connection");
}
if (E.CurrentReturnType is Type_Unit)
{
O.Write("return ;");
return;
}
if (E.CurrentReturnType.Suitable(E, e._TypeOf(E)))
{
O.Write("return ");
if (!(e is Constant_Empty))
{
e._PhpOf(E, O);
}
O.WriteLine(";");
return;
}
throw new Exception("Return invalid");
}
}
public class Print : Statement
{
Expression Ex;
public Print(Expression e)
{
Ex = e;
}
public void _WellType(Environment E)
{
gType T = Ex._TypeOf(E);
}
public void _PhpOf(Environment E, StringWriter O)
{
gType T = Ex._TypeOf(E);
if (T is Type_ArrayOf || T is Type_ContractByMembers || T is Type_NamedType)
{
O.Write("print_r(");
Ex._PhpOf(E, O);
O.WriteLine(");");//echo(\": " + Ex._TypeOf(E).str() + "\");echo(\"<br />\");");
}
else
{
O.Write("echo(");
Ex._PhpOf(E, O);
O.WriteLine(");");//echo(\": " + Ex._TypeOf(E).str() + "\");echo(\"<br />\");");
}
}
}
public class Delay : Statement
{
Expression Ex;
DebugInformation Debug;
public Delay(Expression e, DebugInformation di)
{
Ex = e;
Debug = di;
}
public void _WellType(Environment E)
{
gType T;
try
{
T = Ex._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type");
throw er;
}
if (T is Type_Functional)
{
if (!T.str().Equals("void->void"))
{
Console.Error.WriteLine(Debug.ErrorPrefix(2013) + "Delay expecting unit->unit, not " + T.str());
throw new Exception("boo");
}
}
}
public void _PhpOf(Environment E, StringWriter O)
{
O.Write("KIRA_SYSTEM_delay('" + E.CurrentNameSpace + "',");
Ex._PhpOf(E, O);
O.WriteLine(");");
}
}
public class Compute : Statement
{
Expression EXP;
public Compute(Expression ex)
{
EXP = ex;
}
public void _PhpOf(Environment E, StringWriter O)
{
EXP._PhpOf(E, O);
O.WriteLine(";");
}
public void _WellType(Environment E)
{
}
}
public interface For : Statement
{
void SetCode(Statement s);
}
public class ForEach : For
{
public string var;
public Expression Set;
public Statement Code;
DebugInformation Debug;
public ForEach(string x, Expression e, DebugInformation di)
{
var = x;
Set = e;
Debug = di;
}
public void SetCode(Statement s)
{
Code = s;
}
public void _PhpOf(Environment E, StringWriter O)
{
gType T = Set._TypeOf(E);
gType eT = (T as Type_ArrayOf).Base;
O.Write("foreach(");
Set._PhpOf(E, O);
O.Write(" as $" + var);
O.WriteLine(")");
E.Push();
E.Declare(var, eT);
E.Pop();
}
public void _WellType(Environment E)
{
gType T;
try
{
T = Set._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type");
throw er;
}
if (!(T is Type_ArrayOf))
{
throw new Exception("Not Done");
}
gType eT = (T as Type_ArrayOf).Base;
E.Push();
E.Declare(var, eT);
Code._WellType(E);
E.Pop();
/*
gType T;
try
{
T = exprL._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type");
throw er;
}
*/
}
}
public class ForLoop : For
{
public Statement Init;
public Expression Cond;
public Assignment Mod;
public Statement Code;
DebugInformation Debug;
public ForLoop(Statement i, DebugInformation di)
{
Init = i;
Cond = null;
Mod = null;
Debug = di;
}
public void SetCode(Statement s)
{
Code = s;
}
public void _PhpOf(Environment E, StringWriter O)
{
StringWriter T = new StringWriter();
O.Write("for(");
Init._PhpOf(E, T); O.Write(T.ToString().Trim());
if (Cond != null) { if (!(Cond._TypeOf(E) is Type_Boolean)) { throw new Exception("need boolean guard on forloop std"); } T = new StringWriter(); Cond._PhpOf(E, T); O.Write(T.ToString().Trim()); }
O.Write(";");
if (Mod != null) { T = new StringWriter(); Mod._PhpOf(E, T); O.Write(T.ToString().Trim()); }
O.WriteLine(")");
Code._PhpOf(E, O);
}
public void _WellType(Environment E)
{
try
{
Init._WellType(E);
gType T;
try
{
T = Cond._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type (Condition)");
throw er;
}
if (!(T is Type_Boolean))
{
Console.Error.WriteLine(Debug.ErrorPrefix(2003) + "for(;...;) loop condition not a boolean");
throw new Exception("err");
}
if (Cond is Constant_Boolean)
{
Console.Error.WriteLine(Debug.ErrorPrefix(2004) + "for(;...;) loop condition is a constant");
throw new Exception("err");
}
Mod._WellType(E);
Code._WellType(E);
}
catch (Exception err)
{
Console.Error.WriteLine(Debug.ErrorPrefix(2006) + "for(;...;) loop not well typed");
throw err;
}
}
/*
public string str()
{
string x = "for(" + Init.str();
if(Cond != null) x += Cond.str();
x += ";";
if(Mod != null) x+= Mod.str();
return x + ")" + Code.str();
}
*/
}
public class DoWhileLoop : Statement
{
Statement Code;
Expression Cond;
DebugInformation Debug;
public DoWhileLoop(Expression b, Statement c, DebugInformation di)
{
Cond = b;
Code = c;
Debug = di;
}
public void _WellType(Environment E)
{
try
{
gType T;
try
{
T = Cond._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type (Condition)");
throw er;
}
if (!(T is Type_Boolean))
{
Console.Error.WriteLine(Debug.ErrorPrefix(2006) + "do/while loop condition not a boolean");
throw new Exception("err");
}
if (Cond is Constant_Boolean)
{
Console.Error.WriteLine(Debug.ErrorPrefix(2007) + "do/while loop condition is a constant");
throw new Exception("err");
}
Code._WellType(E);
}
catch (Exception err)
{
Console.Error.WriteLine(Debug.ErrorPrefix(2006) + "do/while loop not well typed");
throw err;
}
}
public void _PhpOf(Environment E, StringWriter O)
{
StringWriter T = new StringWriter();
if (Cond._TypeOf(E) is Type_Boolean)
{
O.Write("do ");
Code._PhpOf(E, O);
O.Write(" while(");
Cond._PhpOf(E, T);
O.Write(T.ToString().Trim());
O.Write(");");
return;
}
throw new Exception("While loop guard must be boolean");
}
}
public class WhileLoop : Statement
{
Statement Code;
Expression Cond;
public void _WellType(Environment E)
{
try
{
gType T;
try
{
T = Cond._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type (Condition)");
throw er;
}
if (!(T is Type_Boolean))
{
Console.Error.WriteLine(Debug.ErrorPrefix(2006) + "do/while loop condition not a boolean");
throw new Exception("err");
}
if (Cond is Constant_Boolean)
{
Console.Error.WriteLine(Debug.ErrorPrefix(2007) + "do/while loop condition is a constant");
throw new Exception("err");
}
Code._WellType(E);
}
catch (Exception err)
{
Console.Error.WriteLine(Debug.ErrorPrefix(2006) + "do/while loop not well typed");
throw err;
}
}
DebugInformation Debug;
public WhileLoop(Expression b, Statement c, DebugInformation di)
{
Cond = b;
Code = c;
Debug = di;
}
public void _PhpOf(Environment E, StringWriter O)
{
StringWriter T = new StringWriter();
if (Cond._TypeOf(E) is Type_Boolean)
{
O.Write("while(");
Cond._PhpOf(E, T);
O.Write(T.ToString().Trim());
O.Write(")");
Code._PhpOf(E, O);
return;
}
throw new Exception("While loop guard must be boolean");
}
}
public class IfElse : Statement
{
Expression Guard;
Statement BranchTrue;
Statement BranchFalse;
DebugInformation Debug;
public IfElse(Expression g, Statement bt, DebugInformation di)
{
Guard = g;
BranchTrue = bt;
BranchFalse = null;
Debug = di;
}
public void _WellType(Environment E)
{
try
{
gType T;
try
{
T = Guard._TypeOf(E);
}
catch (Exception er)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type (Condition)");
throw er;
}
if (!(T is Type_Boolean))
{
Console.Error.WriteLine(Debug.ErrorPrefix(2009) + "if/else condition not a boolean");
throw new Exception("err");
}
if (Guard is Constant_Boolean)
{
Console.Error.WriteLine(Debug.ErrorPrefix(2010) + "if/else condition is a constant");
throw new Exception("err");
}
BranchTrue._WellType(E);
if (BranchFalse != null)
BranchFalse._WellType(E);
}
catch (Exception err)
{
Console.Error.WriteLine(Debug.ErrorPrefix(2011) + "if/else loop not well typed");
throw (err);
}
}
public void SetElse(Statement bf)
{
BranchFalse = bf;
}
public void _PhpOf(Environment E, StringWriter O)
{
StringWriter T = new StringWriter();
if (Guard._TypeOf(E) is Type_Boolean)
{
O.Write("if(");
Guard._PhpOf(E, T);
O.Write(T.ToString().Trim());
O.Write(") { ");
BranchTrue._PhpOf(E, O);
O.Write("}");
if (BranchFalse != null)
{
O.Write(" else {");
BranchFalse._PhpOf(E, O);
O.Write("}");
}
return;
}
}
}
public class ThrowStatement : Statement
{
Expression e;
DebugInformation Debug;
public ThrowStatement(Expression z, DebugInformation di)
{
e = z;
Debug = di;
}
public void _PhpOf(Environment E, StringWriter O)
{
O.Write("throw new Exception(");
e._PhpOf(E, O);
O.Write(");");
}
public void _WellType(Environment E)
{
gType T;
try
{
T = e._TypeOf(E);
}
catch (Exception err)
{
Console.Error.WriteLine(Debug.ErrorPrefix(1000) + "Expression could not type");
throw err;
}
}
}
/*
//ThrowStatement
//ThrowStatement
public class DeleteStatement : Statement
{
Expression e;
public DeleteStatement(Expression z)
{
e = z;
}
public string str()
{
return "delete " + e.str() + ";";
}
}
public class TryCatch : Statement
{
string var;
Statement BranchGood;
Statement BranchFuck;
public TryCatch(Statement bt)
{
BranchGood = bt;
BranchFuck = null;
}
public void SetFuck(string v, Statement bf)
{
var = v;
BranchFuck = bf;
}
public string str()
{
string x = "try " + BranchGood.str();
if(BranchFuck != null) x += "catch(" + var + ")" + BranchFuck.str();
return x;
}
}
*/
}
| |
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.Virtualization;
using Microsoft.JSInterop;
using LionFire.Vos.Blazor;
using LionFire.Vos;
using Blazorise;
using LionFire.Referencing;
using LionFire.Threading;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using LionFire.Persistence;
using System.Reflection;
using LionFire.Resolves;
using MudBlazor;
namespace LionFire.Vos.Blazor
{
public partial class VosExplorer
{
#region CurrentObject
[Parameter]
public object CurrentObject
{
get => currentObject;
set
{
if (currentObject == value)
return;
if (currentObject != null && currentObject is System.ComponentModel.INotifyPropertyChanged inpcDisabling)
{
inpcDisabling.PropertyChanged -= OnCurrentObjectPropertyChanged;
}
currentObject = value;
if (currentObject != null && currentObject is System.ComponentModel.INotifyPropertyChanged inpcEnabling)
{
inpcEnabling.PropertyChanged += OnCurrentObjectPropertyChanged;
}
}
}
private object? currentObject;
#endregion
private void OnCurrentObjectPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
InvokeAsync(async () =>
{
Logger.LogTrace("OnCurrentObjectPropertyChanged");
await Refresh();
StateHasChanged();
});
}
#region Parameters
[Parameter]
public string Root { get; set; }
#region Path
[Parameter]
public string Path
{
get => path;
set
{
if (value == null)
{
value = "";
}
if (!value.Contains(":"))
{
if (!value.StartsWith("/") && !value.StartsWith("\\"))
{
value = "/" + value;
}
value = $"vos:{value}";
}
path = value;
}
}
private string path;
#endregion
#endregion
#region State
Stack<object> History = new Stack<object>();
Stack<(object, string)> ForwardHistory = new Stack<(object, string)>();
Stack<string> BreadCrumbPath = new Stack<string>();
private Listing<object>[] listings;
//private List<IReadHandle<object>> readHandles;
#endregion
#region Initialization
protected override async Task OnInitializedAsync()
{
var x = ServiceProvider.GetService(typeof(IReferenceProviderService));
navManager.LocationChanged += OnLocationChanged;
await UpdateRoot();
await Refresh();
await base.OnInitializedAsync();
}
#endregion
#region Refresh
private async Task UpdateRoot()
{
//logger.LogInformation("OnInitializedAsync " + uri);
//System.Diagnostics.Debug.WriteLine("Uri: " + uri);
//if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("Root", out var param))
//{
// System.Diagnostics.Debug.WriteLine("Root: " + param);
// Root = param.First();
//}
//else
//{
// System.Diagnostics.Debug.WriteLine("Uri could not find root: " + uri);
//}
Root = this.Path;
//this.Path = Root;
await Refresh();
StateHasChanged();
}
private async void OnLocationChanged(object sender, LocationChangedEventArgs args)
{
Logger.LogInformation("OnLocationChanged " + uri);
await UpdateRoot();
}
public Task GoToPath(string child)
{
if (child == "..")
{
Path = LionPath.GetParent(Path);
}
else
{
Path = LionPath.Combine(Path, child);
}
return Refresh();
}
public async Task RetrieveValue()
{
object newValue = null;
try
{
var rh = Path?.ToReference()?.GetReadHandle<object>(); // TODO - get available types
if (rh != null)
{
var result = (await rh.TryGetValue().ConfigureAwait(false));
newValue = result.Value;
if (result.IsSuccess != true)
{
Logger.Debug($"Failed to retrieve {Path}: {result}");
}
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Exception when retrieving handle or value");
}
CurrentObject = newValue;
}
public async Task Refresh()
{
var root = rootManager.Get();
var path = Path;
if (path != null)
{
if (LionUri.TryGetUriScheme(path) == null)
{
path = "vos:" + path;
}
//if (path.StartsWith("file:"))
//{
// path = "/file";
//}
}
#if OLD
//var hList = ((IReference)root[path].Reference).GetListingsHandle();
#else
var reference = path?.ToReference();
var hList = reference?.GetListingsHandle();
#endif
if (hList == null)
{
listings = null;
return;
}
var result = await hList.Resolve();
listings = result?.Value.Value?.ToArray() ?? Array.Empty<Listing<object>>();
if (listings.Length == 0)
{
// FIXME - why is hList empty?????????
var list = new List<Listing<object>>();
var vob = root[reference.Path];
foreach (var x in vob)
{
list.Add(new Listing<object>(x.Name));
}
listings = list.ToArray();
}
//var newReadHandles = new List<IReadHandle<object>>();
foreach (var listing in listings)
{
try
{
var childPath = LionPath.Combine(path, listing.Name);
var handle = childPath.ToReference<object>().GetReadHandle<object>();
//newReadHandles.Add(handle);
listing.Type = (await handle.GetValue().ConfigureAwait(false))?.GetType().Name;
}
catch
{
listing.Type = "?";
}
}
//readHandles = newReadHandles;
await RetrieveValue().ConfigureAwait(false);
}
#endregion
void Pop()
{
ForwardHistory.Push((CurrentObject, BreadCrumbPath.Pop()));
CurrentObject = History.Pop();
}
void Push(object val, string name, bool fromForward = false)
{
if (val == null)
return;
if (!fromForward && ForwardHistory.Any() && Object.ReferenceEquals(ForwardHistory.Peek().Item1, val))
{
Forward();
return;
}
History.Push(CurrentObject);
BreadCrumbPath.Push(name);
CurrentObject = val;
if (!fromForward)
{
ForwardHistory.Clear();
}
}
void Back()
{
if (History.Count > 0)
{
Pop();
}
}
void Forward()
{
if (ForwardHistory.Count == 0)
{
return;
}
var next = ForwardHistory.Pop();
Push(next.Item1, next.Item2, fromForward: true);
}
#region (Private) Utility methods
private Uri uri => navManager.ToAbsoluteUri(navManager.Uri);
public string IconClasses(Listing<object> listing)
{
if (listing.IsDirectory)
{
return "oi oi-folder";
}
return "oi oi-chevron-right";
}
#endregion
}
}
| |
using System.Collections.Generic;
using UnityEngine;
namespace SE.DC {
public class OctreeDrawInfo
{
public int index;
public int corners;
public Vector3 position;
public Vector3 averageNormal;
public QEF.QEFSolver qef;
public OctreeDrawInfo()
{
index = -1;
corners = 0;
}
};
public class OctreeNode
{
public DCC.OctreeNodeType type;
public Vector3 min;
public int size;
public OctreeNode[] children;
public OctreeDrawInfo drawInfo;
public static int numMinNodes = 0;
public SE.IsosurfaceAlgorithm.Sample sample;
public float isovalue;
public OctreeNode()
{
type = DCC.OctreeNodeType.Node_Internal;
min = Vector3.zero;
size = 0;
drawInfo = null;
children = new OctreeNode[8];
for (int i = 0; i < 8; i++)
{
children[i] = null;
}
}
public OctreeNode(DCC.OctreeNodeType _type)
{
type = _type;
min = Vector3.zero;
size = 0;
drawInfo = null;
for (int i = 0; i < 8; i++)
{
children[i] = null;
}
}
public static readonly Vector3[] CHILD_MIN_OFFSETS = {
new Vector3(0, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0), new Vector3(0, 1, 1),
new Vector3(1, 0, 0), new Vector3(1, 0, 1), new Vector3(1, 1, 0), new Vector3(1, 1, 1)
};
public static OctreeNode ConstructOctreeNodes(OctreeNode node)
{
if(node == null) return null;
if(node.size == 1) {
return ConstructLeaf(node);
}
int childSize = node.size / 2;
bool hasChildren = false;
for(int i = 0; i < 8; i++) {
OctreeNode child = new OctreeNode();
child.size = childSize;
child.min = node.min + (CHILD_MIN_OFFSETS[i] * childSize);
child.type = DCC.OctreeNodeType.Node_Internal;
child.isovalue = node.isovalue;
child.sample = node.sample;
node.children[i] = ConstructOctreeNodes(child);
hasChildren |= node.children[i] != null;
}
if(!hasChildren) {
return null;
}
return node;
}
public static void DrawGizmos(OctreeNode node) {
if(node == null) return;
if(node.type == DCC.OctreeNodeType.Node_Internal) {
for(int i = 0; i < 8; i++) {
DrawGizmos(node.children[i]);
}
}
Gizmos.color = colors[(int)Mathf.Log(node.size, 2)];
Gizmos.DrawWireCube(node.min + (Vector3.one * (node.size/2f)), Vector3.one * node.size);
}
private static Color[] colors = {
new Color(1, 0, 0, 1f),
new Color(0, 1, 0, 1f),
new Color(0, 0, 1, 1f),
new Color(1, 1, 0, 1f),
new Color(0, 1, 1, 1f),
new Color(1, 0, 1, 1f),
new Color(1, 1, 1, 1f)
};
public static OctreeNode ConstructLeaf(OctreeNode leaf) {
int corners = 0;
for(int i = 0; i < 8; i++) {
Vector3 cornerPos = leaf.min + CHILD_MIN_OFFSETS[i];
float density = leaf.sample(cornerPos);
int material = density < leaf.isovalue ? DCC.Material_Solid : DCC.Material_Air;
corners |= (material << i);
}
if(corners == 0 || corners == 255) return null;
Vector3[] positions = new Vector3[DCC.MAX_CROSSINGS];
Vector3[] normals = new Vector3[DCC.MAX_CROSSINGS];
int edgeCount = 0;
for(int i = 0; i < 12 && edgeCount < DCC.MAX_CROSSINGS; i++) {
int c1 = DCC.edgevmap[i][0];
int c2 = DCC.edgevmap[i][1];
int m1 = (corners >> c1) & 1;
int m2 = (corners >> c2) & 1;
if((m1 == DCC.Material_Air && m2 == DCC.Material_Air) ||
(m1 == DCC.Material_Solid && m2 == DCC.Material_Solid)) {
continue;
}
Vector3 p1 = leaf.min + CHILD_MIN_OFFSETS[c1];
Vector3 p2 = leaf.min + CHILD_MIN_OFFSETS[c2];
Vector3 p = ApproximateZeroCrossingPosition(p1, p2, leaf.sample);
positions[edgeCount] = p;
normals[edgeCount] = CalculateSurfaceNormal(p, leaf.sample);
edgeCount++;
}
OctreeDrawInfo drawInfo = new SE.DC.OctreeDrawInfo();
drawInfo.qef = new QEF.QEFSolver();
for(int i = 0; i < edgeCount; i++) {
drawInfo.qef.Add(positions[i], normals[i]);
}
drawInfo.position = drawInfo.qef.Solve(1e-6f, 4, 1e-6f);
Vector3 min = leaf.min;
Vector3 max = leaf.min + Vector3.one * leaf.size;
if (drawInfo.position.x < min.x || drawInfo.position.x > max.x ||
drawInfo.position.y < min.y || drawInfo.position.y > max.y ||
drawInfo.position.z < min.z || drawInfo.position.z > max.z)
{
drawInfo.position = drawInfo.qef.MassPoint;
}
for (int i = 0; i < edgeCount; i++)
{
drawInfo.averageNormal += normals[i];
}
drawInfo.averageNormal = drawInfo.averageNormal.normalized;
drawInfo.corners = corners;
leaf.type = DCC.OctreeNodeType.Node_Leaf;
leaf.drawInfo = drawInfo;
OctreeNode.numMinNodes++;
return leaf;
}
public static Vector3 ApproximateZeroCrossingPosition(Vector3 p0, Vector3 p1, SE.IsosurfaceAlgorithm.Sample sample)
{
// approximate the zero crossing by finding the min value along the edge
float minValue = 100000;
float t = 0;
float currentT = 0;
const int steps = 8;
const float increment = 1f / (float)steps;
while (currentT <= 1f)
{
Vector3 p = p0 + ((p1 - p0) * currentT);
float density = Mathf.Abs(sample(p));
if (density < minValue)
{
minValue = density;
t = currentT;
}
currentT += increment;
}
return p0 + ((p1 - p0) * t);
}
public static Vector3 QuickZeroCrossingPosition(Vector3 p0, Vector3 p1, SE.IsosurfaceAlgorithm.Sample sample) {
if (Mathf.Abs(sample(p0)) < 0.00001)
return(p0);
if (Mathf.Abs(sample(p1)) < 0.00001)
return(p1);
if (Mathf.Abs(sample(p0)-sample(p1)) < 0.00001)
return(p1);
float mu = (- sample(p0)) / (sample(p1) - sample(p0));
return p0 + mu * (p1 - p0);
}
public static Vector3 CalculateSurfaceNormal(Vector3 p, SE.IsosurfaceAlgorithm.Sample sample) {
const float H = 0.001f;
float dx = sample(p + new Vector3(H, 0, 0)) - sample(p - new Vector3(H, 0, 0));
float dy = sample(p + new Vector3(0, H, 0)) - sample(p - new Vector3(0, H, 0));
float dz = sample(p + new Vector3(0, 0, H)) - sample(p - new Vector3(0, 0, H));
return new Vector3(dx, dy, dz).normalized;
}
public static void GenerateVertexIndices(OctreeNode node, List<Vector3> vertices, List<Vector3> normals) {
if(node == null) return;
if(node.type != DCC.OctreeNodeType.Node_Leaf) {
for(int i = 0; i < node.children.Length; i++) {
GenerateVertexIndices(node.children[i], vertices, normals);
}
}
else {
OctreeDrawInfo d = node.drawInfo;
d.index = vertices.Count;
vertices.Add(d.position);
normals.Add(d.averageNormal);
}
}
static bool[] gotHere = {false, false, false, false};
public static void ContourProcessEdge(OctreeNode[] nodes, int dir, List<int> indices) {
int minSize = 1000000; // arbitrary big number
int minIndex = 0;
int[] indices_ = { -1, -1, -1, -1 };
bool flip = false;
bool[] signChange = { false, false, false, false };
for (int i = 0; i < 4; i++) {
if(!gotHere[0]) {
Debug.Log("got here");
gotHere[0] = true;
}
int edge = DCC.processEdgeMask[dir][i];
int c1 = DCC.edgevmap[edge][0];
int c2 = DCC.edgevmap[edge][1];
int m1 = (nodes[i].drawInfo.corners >> c1) & 1;
int m2 = (nodes[i].drawInfo.corners >> c2) & 1;
if (nodes[i].size < minSize) {
minSize = nodes[i].size;
minIndex = i;
flip = m1 != DCC.Material_Air;
}
indices_[i] = nodes[i].drawInfo.index;
signChange[i] =
(m1 == DCC.Material_Air && m2 != DCC.Material_Air) ||
(m1 != DCC.Material_Air && m2 == DCC.Material_Air);
}
if (signChange[minIndex]) {
if (!flip) {
indices.Add(indices_[0]);
indices.Add(indices_[1]);
indices.Add(indices_[3]);
indices.Add(indices_[0]);
indices.Add(indices_[3]);
indices.Add(indices_[2]);
}
else {
indices.Add(indices_[0]);
indices.Add(indices_[3]);
indices.Add(indices_[1]);
indices.Add(indices_[0]);
indices.Add(indices_[2]);
indices.Add(indices_[3]);
}
}
}
public static void ContourEdgeProc(OctreeNode[] nodes, int dir, List<int> indices) {
if(!gotHere[1]) {
Debug.Log("ContourProcEdge called.");
gotHere[1] = true;
}
for(int i = 0; i < 4; i++) if(nodes[i] == null) return;
if (nodes[0].type != DCC.OctreeNodeType.Node_Internal &&
nodes[1].type != DCC.OctreeNodeType.Node_Internal &&
nodes[2].type != DCC.OctreeNodeType.Node_Internal &&
nodes[3].type != DCC.OctreeNodeType.Node_Internal) {
ContourProcessEdge(nodes, dir, indices);
}
else {
for (int i = 0; i < 2; i++) {
OctreeNode[] edgeNodes = new OctreeNode[4];
int[] c = {
DCC.edgeProcEdgeMask[dir][i][0],
DCC.edgeProcEdgeMask[dir][i][1],
DCC.edgeProcEdgeMask[dir][i][2],
DCC.edgeProcEdgeMask[dir][i][3],
};
for (int j = 0; j < 4; j++) {
if (nodes[j].type == DCC.OctreeNodeType.Node_Leaf || nodes[j].type == DCC.OctreeNodeType.Node_Psuedo) {
edgeNodes[j] = nodes[j];
}
else {
edgeNodes[j] = nodes[j].children[c[j]];
}
}
ContourEdgeProc(edgeNodes, DCC.edgeProcEdgeMask[dir][i][4], indices);
}
}
}
public static void ContourFaceProc(OctreeNode[] nodes, int dir, List<int> indices) {
if (nodes[0] == null || nodes[1] == null) {
return;
}
if (nodes[0].type == DCC.OctreeNodeType.Node_Internal ||
nodes[1].type == DCC.OctreeNodeType.Node_Internal)
{
for (int i = 0; i < 4; i++) {
OctreeNode[] faceNodes = new OctreeNode[2];
int[] c = {
DCC.faceProcFaceMask[dir][i][0],
DCC.faceProcFaceMask[dir][i][1],
};
for (int j = 0; j < 2; j++) {
if (nodes[j].type != DCC.OctreeNodeType.Node_Internal) {
faceNodes[j] = nodes[j];
}
else {
faceNodes[j] = nodes[j].children[c[j]];
}
}
ContourFaceProc(faceNodes, DCC.faceProcFaceMask[dir][i][2], indices);
}
int[][] orders = {
new int[] { 0, 0, 1, 1 },
new int[] { 0, 1, 0, 1 },
};
for (int i = 0; i < 4; i++) {
OctreeNode[] edgeNodes = new OctreeNode[4];
int[] c = {
DCC.faceProcEdgeMask[dir][i][1],
DCC.faceProcEdgeMask[dir][i][2],
DCC.faceProcEdgeMask[dir][i][3],
DCC.faceProcEdgeMask[dir][i][4],
};
int[] order = orders[DCC.faceProcEdgeMask[dir][i][0]];
for (int j = 0; j < 4; j++) {
if (nodes[order[j]].type == DCC.OctreeNodeType.Node_Leaf ||
nodes[order[j]].type == DCC.OctreeNodeType.Node_Psuedo) {
edgeNodes[j] = nodes[order[j]];
}
else {
edgeNodes[j] = nodes[order[j]].children[c[j]];
}
}
ContourEdgeProc(edgeNodes, DCC.faceProcEdgeMask[dir][i][5], indices);
}
}
}
public static void ContourCellProc(OctreeNode node, List<int> indices) {
if (node == null) return;
if (node.type == DCC.OctreeNodeType.Node_Internal) {
if(!gotHere[2]) {
gotHere[2] = true;
Debug.Log("node type is internal");
}
for (int i = 0; i < 8; i++) {
ContourCellProc(node.children[i], indices);
}
for (int i = 0; i < 12; i++) {
OctreeNode[] faceNodes = new OctreeNode[2];
int[] c = { DCC.cellProcFaceMask[i][0], DCC.cellProcFaceMask[i][1] };
faceNodes[0] = node.children[c[0]];
faceNodes[1] = node.children[c[1]];
ContourFaceProc(faceNodes, DCC.cellProcFaceMask[i][2], indices);
}
for (int i = 0; i < 6; i++) {
OctreeNode[] edgeNodes = new OctreeNode[4];
int[] c = {
DCC.cellProcEdgeMask[i][0],
DCC.cellProcEdgeMask[i][1],
DCC.cellProcEdgeMask[i][2],
DCC.cellProcEdgeMask[i][3],
};
for (int j = 0; j < 4; j++) {
edgeNodes[j] = node.children[c[j]];
}
ContourEdgeProc(edgeNodes, DCC.cellProcEdgeMask[i][4], indices);
}
}
}
};
}
| |
//---------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Description: Implementation of CombinedGeometry
//
// History:
// 2004/11/11-Michka
// Created it
//
//---------------------------------------------------------------------------
using System;
using MS.Internal;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Windows.Media;
using System.Windows;
using System.Windows.Media.Composition;
using System.Text.RegularExpressions;
using System.Windows.Media.Animation;
using System.Windows.Markup;
using System.Runtime.InteropServices;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media
{
/// <summary>
/// CombinedGeometry
/// </summary>
public sealed partial class CombinedGeometry : Geometry
{
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public CombinedGeometry()
{
}
/// <summary>
/// Constructor from 2 operands
/// </summary>
/// <param name="geometry1">
/// First geometry to combine
/// </param>
/// <param name="geometry2">
/// Second geometry to combine
/// </param>
public CombinedGeometry(
Geometry geometry1,
Geometry geometry2
)
{
Geometry1 = geometry1;
Geometry2 = geometry2;
}
/// <summary>
/// Constructor from combine mode and 2 operands
/// </summary>
/// <param name="geometryCombineMode">
/// Combine mode - Union, Intersect, Exclude or Xor
/// </param>
/// <param name="geometry1">
/// First geometry to combine
/// </param>
/// <param name="geometry2">
/// Second geometry to combine
/// </param>
public CombinedGeometry(
GeometryCombineMode geometryCombineMode,
Geometry geometry1,
Geometry geometry2
)
{
GeometryCombineMode = geometryCombineMode;
Geometry1 = geometry1;
Geometry2 = geometry2;
}
/// <summary>
/// Constructor from combine mode, 2 operands and a transformation
/// </summary>
/// <param name="geometryCombineMode">
/// Combine mode - Union, Intersect, Exclude or Xor
/// </param>
/// <param name="geometry1">
/// First geometry to combine
/// </param>
/// <param name="geometry2">
/// Second geometry to combine
/// </param>
/// <param name="transform">
/// Transformation to apply to the result
/// </param>
public CombinedGeometry(
GeometryCombineMode geometryCombineMode,
Geometry geometry1,
Geometry geometry2,
Transform transform)
{
GeometryCombineMode = geometryCombineMode;
Geometry1 = geometry1;
Geometry2 = geometry2;
Transform = transform;
}
#endregion
#region Bounds
/// <summary>
/// Gets the bounds of this Geometry as an axis-aligned bounding box
/// </summary>
public override Rect Bounds
{
get
{
ReadPreamble();
// GetAsPathGeometry() checks if the geometry is valid
return GetAsPathGeometry().Bounds;
}
}
#endregion
#region GetBoundsInternal
/// <summary>
/// Gets the bounds of this Geometry as an axis-aligned bounding box given a Pen and/or Transform
/// </summary>
internal override Rect GetBoundsInternal(Pen pen, Matrix matrix, double tolerance, ToleranceType type)
{
if (IsObviouslyEmpty())
{
return Rect.Empty;
}
return GetAsPathGeometry().GetBoundsInternal(pen, matrix, tolerance, type);
}
#endregion
#region Hit Testing
/// <summary>
/// Returns if point is inside the filled geometry.
/// </summary>
internal override bool ContainsInternal(Pen pen, Point hitPoint, double tolerance, ToleranceType type)
{
if (pen == null)
{
ReadPreamble();
// Hit the two operands
bool hit1 = false;
bool hit2 = false;
Transform transform = Transform;
if (transform != null && !transform.IsIdentity)
{
// Inverse-transform the hit point
Matrix matrix = transform.Value;
if (matrix.HasInverse)
{
matrix.Invert();
hitPoint *= matrix;
}
else
{
// The matrix will collapse the geometry to nothing, containing nothing
return false;
}
}
Geometry geometry1 = Geometry1;
Geometry geometry2 = Geometry2;
if (geometry1 != null)
{
hit1 = geometry1.ContainsInternal(pen, hitPoint, tolerance, type);
}
if (geometry2 != null)
{
hit2 = geometry2.ContainsInternal(pen, hitPoint, tolerance, type);
}
// Determine containment according to the theoretical definition
switch (GeometryCombineMode)
{
case GeometryCombineMode.Union:
return hit1 || hit2;
case GeometryCombineMode.Intersect:
return hit1 && hit2;
case GeometryCombineMode.Exclude:
return hit1 && !hit2;
case GeometryCombineMode.Xor:
return hit1 != hit2;
}
// We should have returned from one of the cases
Debug.Assert(false);
return false;
}
else
{
// pen != null
return base.ContainsInternal(pen, hitPoint, tolerance, type);
}
}
#endregion
/// <summary>
/// Gets the area of this geometry
/// </summary>
/// <param name="tolerance">The computational error tolerance</param>
/// <param name="type">The way the error tolerance will be interpreted - realtive or absolute</param>
public override double GetArea(double tolerance, ToleranceType type)
{
ReadPreamble();
// Potential speedup, to be done if proved important: As the result of a Combine
// operation, the result of GetAsPathGeometry() is guaranteed to be organized into
// flattened well oriented figures. Its area can therefore be computed much faster
// without the heavy machinary of CArea. This will require writing an internal
// CShapeBase::GetRawArea method, and a utility to invoke it. For now:
return GetAsPathGeometry().GetArea(tolerance, type);
}
#region Internal
internal override PathFigureCollection GetTransformedFigureCollection(Transform transform)
{
return GetAsPathGeometry().GetTransformedFigureCollection(transform);
}
/// <summary>
/// GetPathGeometryData - returns a struct which contains this Geometry represented
/// as a path geometry's serialized format.
/// </summary>
internal override PathGeometryData GetPathGeometryData()
{
if (IsObviouslyEmpty())
{
return Geometry.GetEmptyPathGeometryData();
}
PathGeometry pathGeometry = GetAsPathGeometry();
return pathGeometry.GetPathGeometryData();
}
internal override PathGeometry GetAsPathGeometry()
{
// Get the operands, interpreting null as empty PathGeometry
Geometry g1 = Geometry1;
Geometry g2 = Geometry2;
PathGeometry geometry1 = (g1 == null) ?
new PathGeometry() :
g1.GetAsPathGeometry();
Geometry geometry2 = (g2 == null) ?
new PathGeometry() :
g2.GetAsPathGeometry();
// Combine them and return the result
return Combine(geometry1, geometry2, GeometryCombineMode, Transform);
}
#endregion
#region IsEmpty
/// <summary>
/// Returns true if this geometry is empty
/// </summary>
public override bool IsEmpty()
{
return GetAsPathGeometry().IsEmpty();
}
internal override bool IsObviouslyEmpty()
{
// See which operand is obviously empty
Geometry geometry1 = Geometry1;
Geometry geometry2 = Geometry2;
bool empty1 = geometry1 == null || geometry1.IsObviouslyEmpty();
bool empty2 = geometry2 == null || geometry2.IsObviouslyEmpty();
// Depending on the operation --
if (GeometryCombineMode == GeometryCombineMode.Intersect)
{
return empty1 || empty2;
}
else if (GeometryCombineMode == GeometryCombineMode.Exclude)
{
return empty1;
}
else
{
// Union or Xor
return empty1 && empty2;
}
}
#endregion IsEmpty
/// <summary>
/// Returns true if this geometry may have curved segments
/// </summary>
public override bool MayHaveCurves()
{
Geometry geometry1 = Geometry1;
Geometry geometry2 = Geometry2;
return ((geometry1 != null) && geometry1.MayHaveCurves())
||
((geometry2 != null) && geometry2.MayHaveCurves());
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Threading;
using System.Runtime.Serialization;
// Copyright (c) 2006 by Hugh Pyle, inguzaudio.com
// SoundObj interface structure based originally on Garbe.Sound
namespace DSPUtil
{
// [ServiceContract]
public interface ISoundObj : IEnumerable<ISample>
{
ISoundObj Input { get; set;}
IEnumerator<ISample> Samples { get; }
IEnumerator<ISample> GetBufferedEnumerator();
int Run();
void Reset();
int Iterations { get; }
ushort NumChannels { get; }
uint SampleRate { get; set; }
bool Enabled { get; set; }
SingleChannel Channel(ushort n);
}
/// <summary> Basic implementation of ISoundObj interface </summary>
// This is not abstract, but it's not very useful unless subclassed... :-)
//
// Note: to enable remoting, derive from MarshalByRefObject
// but performance is almost halved (guess due mostly to inlining?)
// - Future may be worthwhile optimizing by hand for that
// - Current remoting implementation not likely to be worthwhile
public class SoundObj : /* MarshalByRefObject, */ ISoundObj
{
// input to this object
protected ISoundObj _input;
protected bool _enabled = true;
protected bool _useBuff = true;
protected uint _sr;
protected ushort _nc;
public SoundObj()
{
// _input = null;
}
public SoundObj(ISoundObj input)
{
Input = input;
}
// public void Dispose()
//{
//}
/// <summary> Get or Set the input object </summary>
public virtual ISoundObj Input
{
get { return (_input); }
set
{
_input = value;
_nc = (_input == null) ? (ushort)0 : _input.NumChannels;
_sr = (_input == null) ? (uint)0 : _input.SampleRate;
}
}
/// <summary> Get or Set whether this processor is enabled. False means this processor simply passes its input unchanged. </summary>
public bool Enabled
{
get { return (_enabled); }
set { _enabled = value; }
}
// Run() with no arguments: we don't care about the "output" from this,
public int Run()
{
int j = 0;
SampleEnum e = new SampleEnum(this);
e.SkipAll(out j);
return j;
}
public int Run(int nSamples)
{
int j = 0;
bool bMore = false;
SampleEnum e = new SampleEnum(this);
e.Skip(nSamples, out j, out bMore);
return j;
}
/// <summary>
/// Default iterator for samples. Most implementations will override this.
/// </summary>
public virtual IEnumerator<ISample> Samples
{
get
{
if (_input == null)
{
yield break;
}
foreach (ISample sample in Input)
{
yield return sample;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.Samples as IEnumerator;
}
IEnumerator<ISample> IEnumerable<ISample>.GetEnumerator()
{
return this.Samples as IEnumerator<ISample>;
}
public IEnumerator<ISample> GetBufferedEnumerator()
{
return new SampleEnum(this);
}
public virtual void Reset()
{
if (_input == null)
{
return;
}
_input.Reset();
}
// Each channel is accessible as its own SoundObj
public virtual SingleChannel Channel(ushort n)
{
return new SingleChannel(this, n);
}
/// <summary> Number of iterations expected to do the signal processing </summary>
public virtual int Iterations
{
get { return (_input==null ? 0 : _input.Iterations); }
}
/// <summary> Gets the sample rate of the signal </summary>
public virtual uint SampleRate
{
get { return ((_sr==0) ? (_input == null ? 0 : _input.SampleRate) : _sr); }
set { _sr = value; }
}
/// <summary> Gets the number of channels of the signal </summary>
public virtual ushort NumChannels
{
get { return ((_nc==0) ? (_input == null ? (ushort)0 : _input.NumChannels) : _nc); }
set { _nc = value; }
}
}
// SampleEnum: a buffering enumerator.
// Used as the default enumerator for ISoundObj for a couple reasons:
// - Buffering generally more efficient
// - Dramatically so if you're remote
// - This can be made serializable (unlike the default enumerator provided by 'yield')
public class SampleEnum : /* MarshalByRefObject, */ ISampleBuffer, IEnumerator<ISample>
{
ISoundObj _obj;
IEnumerator<ISample> _enum;
ISample[] _cache;
int _cacheCount;
int _cachePos;
ushort _nc;
private ISample[] _buff;
private int _bufflen;
private Complex[][] _cbuff;
private int _cbufflen;
private bool _moreSamples = true; // there are samples in the source which we have not yet read
public SampleEnum(ISoundObj obj)
{
_obj = obj;
_nc = _obj.NumChannels;
Reset();
}
object IEnumerator.Current { get { return _cache[_cachePos]; } }
public ISample Current
{
get
{
return _cache[_cachePos];
}
}
public bool MoveNext()
{
_cachePos++;
if (_cache!=null && _cachePos >= _cacheCount)
{
_cache = null;
}
if (_cache==null && _moreSamples)
{
_cache = Read(DSPUtil.BUFSIZE, out _cacheCount, out _moreSamples);
_cachePos = 0;
}
return (_cachePos < _cacheCount);
}
public void Reset()
{
_obj.Reset();
_enum = _obj.Samples;
}
public void Dispose()
{
_enum.Dispose();
_enum = null;
_obj = null;
}
public void Skip(int n, out int nn, out bool moreRemaining)
{
bool more = true;
int j = 0;
for (j = 0; j < n && more; j++)
{
more = _enum.MoveNext();
}
nn = more ? j : (j - 1);
moreRemaining = more;
}
public void SkipAll(out int nn)
{
bool more = true;
int j = 0;
for (j = 0; more; j++)
{
more = _enum.MoveNext();
}
nn = j - 1;
}
public ISample[] Read(int n, out int nn, out bool moreRemaining)
{
ISample[] buff;
if (_obj is ISampleBuffer)
{
buff = (_obj as ISampleBuffer).Read(n, out nn, out moreRemaining);
}
else
{
if (_buff == null || _bufflen < n)
{
_buff = new ISample[n];
_bufflen = n;
}
buff = _buff;
moreRemaining = true;
int j;
for (j = 0; j < n && moreRemaining; j++)
{
if (_enum.MoveNext())
{
buff[j] = _enum.Current;
}
else
{
moreRemaining = false;
}
}
nn = moreRemaining ? j : (j - 1);
}
return buff;
}
/// <summary>
/// Read, into an array of Complex.
/// Unused elements in the array are guaranteed null.
/// </summary>
/// <param name="n"></param>
/// <param name="nn"></param>
/// <param name="moreRemaining"></param>
/// <returns></returns>
public Complex[][] ReadComplex(int n, out int nn, out bool moreRemaining)
{
if (_obj is ISampleBuffer)
{
return (_obj as ISampleBuffer).ReadComplex(n, out nn, out moreRemaining);
}
if (_cbuff == null || _cbufflen < n)
{
_cbuff = new Complex[_nc][];
for (ushort c = 0; c < _nc; c++)
{
_cbuff[c] = new Complex[n];
}
_cbufflen = n;
}
else
{
for (ushort c = 0; c < _nc; c++)
{
Array.Clear(_cbuff[c], 0, n);
}
}
moreRemaining = true;
int j;
for (j = 0; j < n && moreRemaining; j++)
{
if (_enum.MoveNext())
{
ISample s = _enum.Current;
for (ushort c = 0; c < _nc; c++)
{
_cbuff[c][j].Re = s[c];
}
}
else
{
moreRemaining = false;
}
}
nn = moreRemaining ? j : (j - 1);
return _cbuff;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
namespace OmniSharp.Roslyn
{
public class BufferManager
{
private readonly OmnisharpWorkspace _workspace;
private readonly IDictionary<string, IEnumerable<DocumentId>> _transientDocuments = new Dictionary<string, IEnumerable<DocumentId>>(StringComparer.OrdinalIgnoreCase);
private readonly ISet<DocumentId> _transientDocumentIds = new HashSet<DocumentId>();
private readonly object _lock = new object();
public BufferManager(OmnisharpWorkspace workspace)
{
_workspace = workspace;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
}
public async Task UpdateBuffer(Request request)
{
var buffer = request.Buffer;
var changes = request.Changes;
var updateRequest = request as UpdateBufferRequest;
if (updateRequest != null && updateRequest.FromDisk)
{
buffer = File.ReadAllText(updateRequest.FileName);
}
if (request.FileName == null || (buffer == null && changes == null))
{
return;
}
var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(request.FileName);
if (!documentIds.IsEmpty)
{
if (changes == null)
{
var sourceText = SourceText.From(buffer);
foreach (var documentId in documentIds)
{
_workspace.OnDocumentChanged(documentId, sourceText);
}
}
else
{
foreach (var documentId in documentIds)
{
var document = _workspace.CurrentSolution.GetDocument(documentId);
var sourceText = await document.GetTextAsync();
foreach (var change in request.Changes)
{
var startOffset = sourceText.Lines.GetPosition(new LinePosition(change.StartLine - 1, change.StartColumn - 1));
var endOffset = sourceText.Lines.GetPosition(new LinePosition(change.EndLine - 1, change.EndColumn - 1));
sourceText = sourceText.WithChanges(new[] {
new TextChange(new TextSpan(startOffset, endOffset - startOffset), change.NewText)
});
}
_workspace.OnDocumentChanged(documentId, sourceText);
}
}
}
else if(buffer != null)
{
TryAddTransientDocument(request.FileName, buffer);
}
}
public async Task UpdateBuffer(ChangeBufferRequest request)
{
if (request.FileName == null)
{
return;
}
var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(request.FileName);
if (!documentIds.IsEmpty)
{
foreach (var documentId in documentIds)
{
var document = _workspace.CurrentSolution.GetDocument(documentId);
var sourceText = await document.GetTextAsync();
var startOffset = sourceText.Lines.GetPosition(new LinePosition(request.StartLine - 1, request.StartColumn - 1));
var endOffset = sourceText.Lines.GetPosition(new LinePosition(request.EndLine - 1, request.EndColumn - 1));
sourceText = sourceText.WithChanges(new[] {
new TextChange(new TextSpan(startOffset, endOffset - startOffset), request.NewText)
});
_workspace.OnDocumentChanged(documentId, sourceText);
}
}
else
{
// TODO@joh ensure the edit is an insert at offset zero
TryAddTransientDocument(request.FileName, request.NewText);
}
}
private bool TryAddTransientDocument(string fileName, string fileContent)
{
if (string.IsNullOrWhiteSpace(fileName))
{
return false;
}
var projects = FindProjectsByFileName(fileName);
if (projects.Count() == 0)
{
return false;
}
var sourceText = SourceText.From(fileContent);
var documents = new List<DocumentInfo>();
foreach (var project in projects)
{
var id = DocumentId.CreateNewId(project.Id);
var version = VersionStamp.Create();
var document = DocumentInfo.Create(id, fileName, filePath: fileName, loader: TextLoader.From(TextAndVersion.Create(sourceText, version)));
documents.Add(document);
}
lock (_lock)
{
var documentIds = documents.Select(document => document.Id);
_transientDocuments.Add(fileName, documentIds);
_transientDocumentIds.UnionWith(documentIds);
}
foreach (var document in documents)
{
_workspace.AddDocument(document);
}
return true;
}
private IEnumerable<Project> FindProjectsByFileName(string fileName)
{
var dirInfo = new FileInfo(fileName).Directory;
var candidates = _workspace.CurrentSolution.Projects
.GroupBy(project => new FileInfo(project.FilePath).Directory.FullName)
.ToDictionary(grouping => grouping.Key, grouping => grouping.ToList());
List<Project> projects = null;
while (dirInfo != null)
{
if (candidates.TryGetValue(dirInfo.FullName, out projects))
{
return projects;
}
dirInfo = dirInfo.Parent;
}
return Enumerable.Empty<Project>();
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
string fileName = null;
if (args.Kind == WorkspaceChangeKind.DocumentAdded)
{
fileName = args.NewSolution.GetDocument(args.DocumentId).FilePath;
}
else if (args.Kind == WorkspaceChangeKind.DocumentRemoved)
{
fileName = args.OldSolution.GetDocument(args.DocumentId).FilePath;
}
if (fileName == null)
{
return;
}
lock (_lock)
{
if (_transientDocumentIds.Contains(args.DocumentId))
{
return;
}
IEnumerable<DocumentId> documentIds;
if (!_transientDocuments.TryGetValue(fileName, out documentIds))
{
return;
}
_transientDocuments.Remove(fileName);
foreach (var documentId in documentIds)
{
_workspace.RemoveDocument(documentId);
_transientDocumentIds.Remove(documentId);
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// ContextDialogContainer Class - Example Use
//-----------------------------------------------------------------------------
//
//%MyContextDialog = new ScriptObject()
//{
// class = ContextDialogContainer;
// superClass = GuiThumbnailPopup;
// dialog = %myContainedDialog.getID();
// thumbType = "GuiThumbnailClass";
// listType = "StaticSpriteThumbs";
//};
// %MyContextDialog.show( %positionX, %positionY );
// %MyContextDialog.hide();
//
// NOTES
//
// - thumbType describes a script namespace that will be linked to the creation
// of the actual thumbs in the list. This allows you to override their display
// - listType describes a script namespace that will be linked to the creation
// of the list and will have refresh and destroy called on it when you need
// to add objects to the list. to add an object, call %this.AddObject on you
// get a refresh call.
//
//
//function MyCallbackNamespace::onContextActivate( %this )
//{
// echo("Dialog has been pushed onto canvas, clicking outside of it will pop it!");
//}
//function MyCallbackNamespace::onContextDeactivate( %this )
//{
// echo("Dialog has lost it's context and has thus been popped from the canvas!");
//}
//
//
// Object Hierarchy
// [%scriptObject] ScriptObject (GuiThumbnailPopup)
// .superClass (ContextDialogContainer)
// (%scriptObject)->[%dialogCtrl]
// | GuiScrollCtrl [%scrollCtrl] (GuiThumbnailArray)
// | GuiDynamicCtrlArrayCtrl [%objectList] (GuiThumbnailCreator)
// .superClass ( listType )
// .thumbType = %thumbType
// .base = %this
//
function GuiThumbnailPopup::CreateThumbPopup( %this, %parent, %thumbType, %label )
{
%base = new GuiWindowCtrl()
{
profile = "GuiWindowProfile";
horizSizing = "right";
vertSizing = "bottom";
position = "0 0";
extent = "260 200";
minExtent = "140 200";
visible = "1";
text = %label;
maxLength = "255";
resizeWidth = "1";
resizeHeight = "1";
canMove = "1";
canClose = "0";
canMinimize = "0";
canMaximize = "0";
};
%scroll = new GuiScrollCtrl()
{
canSaveDynamicFields = "0";
Profile = "GuiScrollProfile";
class = "GuiThumbnailArray";
internalName = "thumbnailScroll";
HorizSizing = "width";
VertSizing = "height";
Position = "5 13";
Extent = "250 178";
MinExtent = "8 2";
canSave = "1";
Visible = "1";
hovertime = "1000";
hScrollBar = "alwaysOff";
vScrollBar = "alwaysOn";
lockHorizScroll = "true";
lockVertScroll = "false";
constantThumbHeight = "1";
Margin = "6 2";
thumbType = %thumbType; // Special Tag - Class of thumbObject
};
%base.add(%scroll);
%objectList = new GuiDynamicCtrlArrayControl()
{
canSaveDynamicFields = "0";
Profile = "GuiTransparentScrollProfile";
class = %this.listType;
superClass = "GuiThumbnailCreator";
HorizSizing = "width";
VertSizing = "height";
Position = "0 0";
Extent = "250 178";
MinExtent = "64 64";
canSave = "1";
Visible = "1";
internalName = "objectList";
hovertime = "1000";
colCount = "0";
colSize = %this.thumbSizeX;
rowSize = %this.thumbSizeY;
rowSpacing = "2";
colSpacing = "2";
thumbType = %thumbType; // Special Tag - Class of thumbObject
base = %this; // Special Tag - Link to base class for hiding of dlg
};
%scroll.add(%objectList);
%parent.add(%base);
return %base;
}
function GuiThumbnailPopup::onAdd(%this)
{
// Call parent.
if( !Parent::onAdd( %this ) )
return false;
if( %this.thumbType $= "" )
%this.thumbType = "GuiDefaultThumbnail";
%this.Dialog = %this.createThumbPopup( %this.base, %this.thumbType, %this.label );
if( !isObject( %this.Dialog ) )
{
warn("GuiThumbnailPopup::onAdd - Invalid Context Dialog Specified!");
return false;
}
}
function GuiThumbnailArray::onRemove(%this)
{
%this.destroy();
}
function GuiThumbnailArray::onWake( %this )
{
// Find objectList
%objectList = %this.findObjectByInternalName("ObjectList");
if( !isObject( %objectList ) )
return;
%objectList.refreshList();
}
function GuiThumbnailArray::refreshList(%this)
{
// Find objectList
%objectList = %this.findObjectByInternalName("ObjectList");
if( !isObject( %objectList ) )
return;
// Parent will clear
%objectList.destroy();
}
function GuiThumbnailArray::destroy(%this)
{
// Find objectList
%objectList = %this.findObjectByInternalName("ObjectList");
if( !isObject( %objectList ) )
return;
while( %objectList.getCount() > 0 )
{
%object = %objectList.getObject( 0 );
if( isObject( %object ) )
%object.delete();
else
%objectList.remove( %object );
}
}
//-----------------------------------------------------------------------------
// Add a T2D Object to the Object List
//-----------------------------------------------------------------------------
function GuiThumbnailCreator::AddObject( %this, %object, %data, %tooltip )
{
// Add to group
$LB::ObjectLibraryGroup.add( %object );
// Build Object Container
%container = new GuiControl() { profile = GuiButtonProfile; };
// Add to list.
%this.add( %container );
// Return Container
return %container;
}
| |
// 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.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLoption = Interop.Http.CURLoption;
using CurlProtocols = Interop.Http.CurlProtocols;
using CURLProxyType = Interop.Http.curl_proxytype;
using SafeCurlHandle = Interop.Http.SafeCurlHandle;
using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle;
using SafeCallbackHandle = Interop.Http.SafeCallbackHandle;
using SeekCallback = Interop.Http.SeekCallback;
using ReadWriteCallback = Interop.Http.ReadWriteCallback;
using ReadWriteFunction = Interop.Http.ReadWriteFunction;
using SslCtxCallback = Interop.Http.SslCtxCallback;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
internal readonly CurlHandler _handler;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal readonly HttpContentAsyncStream _requestContentStream;
internal SafeCurlHandle _easyHandle;
private SafeCurlSListHandle _requestHeaders;
internal NetworkCredential _networkCredential;
internal MultiAgent _associatedMultiAgent;
internal SendTransferState _sendTransferState;
internal bool _isRedirect = false;
internal Uri _targetUri;
private SafeCallbackHandle _callbackHandle;
public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_handler = handler;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
if (requestMessage.Content != null)
{
_requestContentStream = new HttpContentAsyncStream(requestMessage.Content);
}
_responseMessage = new CurlResponseMessage(this);
_targetUri = requestMessage.RequestUri;
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.Http.EasyCreate();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
// Configure the handle
SetUrl();
SetDebugging();
SetMultithreading();
SetRedirection();
SetVerb();
SetVersion();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler.GetNetworkCredentials(_handler._serverCredentials, _requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
SetSslOptions();
}
public void EnsureResponseMessagePublished()
{
bool result = TrySetResult(_responseMessage);
Debug.Assert(result || Task.Status == TaskStatus.RanToCompletion,
"If the task was already completed, it should have been completed succesfully; " +
"we shouldn't be completing as successful after already completing as failed.");
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
_responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream.
// Dispose of the input content stream if there was one. Nothing should be using it any more.
if (_requestContentStream != null)
_requestContentStream.Dispose();
// Dispose of the underlying easy handle. We're no longer processing it.
if (_easyHandle != null)
_easyHandle.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
if (_requestHeaders != null)
_requestHeaders.Dispose();
if (_callbackHandle != null)
_callbackHandle.Dispose();
}
private void SetUrl()
{
VerboseTrace(_requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS));
}
[Conditional(VerboseDebuggingConditional)]
private void SetDebugging()
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
// In addition to CURLOPT_VERBOSE, CURLOPT_DEBUGFUNCTION could be used here in the future to:
// - Route the verbose output to somewhere other than stderr
// - Dump additional data related to CURLINFO_DATA_* and CURLINFO_SSL_DATA_*
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
VerboseTrace(_handler._maxAutomaticRedirections.ToString());
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
}
private void SetVerb()
{
VerboseTrace(_requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_INFILESIZE, 0L);
}
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_POSTFIELDSIZE, 0L);
SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, string.Empty);
}
}
else if (_requestMessage.Method == HttpMethod.Trace)
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
if (_requestMessage.Content != null)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
}
}
}
private void SetVersion()
{
Version v = _requestMessage.Version;
if (v != null)
{
// Try to use the requested version, if a known version was explicitly requested.
// If an unknown version was requested, we simply use libcurl's default.
var curlVersion =
(v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 :
(v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 :
(v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 :
Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE;
if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE)
{
// Ask libcurl to use the specified version if possible.
CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion);
if (c == CURLcode.CURLE_OK)
{
// Success. The requested version will be used.
VerboseTrace("Set HTTP version to " + v);
}
else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL)
{
// The requested version is unsupported. Fall back to using the default version chosen by libcurl.
VerboseTrace("Unsupported protocol.");
}
else
{
// Some other error. Fail.
ThrowIfCURLEError(c);
}
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding);
VerboseTrace(encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (_handler._proxyPolicy == ProxyUsePolicy.DoNotUseProxy)
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("No proxy");
return;
}
if ((_handler._proxyPolicy == ProxyUsePolicy.UseDefaultProxy) ||
(_handler.Proxy == null))
{
VerboseTrace("Default proxy");
return;
}
Debug.Assert(_handler.Proxy != null, "proxy is null");
Debug.Assert(_handler._proxyPolicy == ProxyUsePolicy.UseCustomProxy, "_proxyPolicy is not UseCustomProxy");
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("Bypassed proxy");
return;
}
var proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
VerboseTrace("No proxy URI");
return;
}
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
VerboseTrace("Set proxy: " + proxyUri.ToString());
KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(_handler.Proxy.Credentials, _requestMessage.RequestUri);
NetworkCredential credentials = credentialScheme.Key;
if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
string.Format("{0}:{1}", credentials.UserName, credentials.Password) :
string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain);
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
VerboseTrace("Set proxy credentials");
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
_networkCredential = null;
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
CURLAUTH authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
_networkCredential = credentials;
VerboseTrace("Set credentials options");
}
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
VerboseTrace("Set cookies");
}
}
internal void SetRequestHeaders()
{
HttpContentHeaders contentHeaders = null;
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (_requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = _requestMessage.Content.Headers.ContentLength.Value;
_requestMessage.Content.Headers.ContentLength = null;
_requestMessage.Content.Headers.ContentLength = contentLength;
}
contentHeaders = _requestMessage.Content.Headers;
}
var slist = new SafeCurlSListHandle();
// Add request and content request headers
if (_requestMessage.Headers != null)
{
AddRequestHeaders(_requestMessage.Headers, slist);
}
if (contentHeaders != null)
{
AddRequestHeaders(contentHeaders, slist);
if (contentHeaders.ContentType == null)
{
if (!Interop.Http.SListAppend(slist, NoContentType))
{
throw CreateHttpRequestException();
}
}
}
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
if (!Interop.Http.SListAppend(slist, NoTransferEncoding))
{
throw CreateHttpRequestException();
}
}
if (!slist.IsInvalid)
{
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
VerboseTrace("Set headers");
}
else
{
slist.Dispose();
}
}
private void SetSslOptions()
{
// SSL Options should be set regardless of the type of the original request,
// in case an http->https redirection occurs.
//
// While this does slow down the theoretical best path of the request the code
// to decide that we need to register the callback is more complicated than, and
// potentially more expensive than, just always setting the callback.
SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions);
}
internal void SetCurlCallbacks(
IntPtr easyGCHandle,
ReadWriteCallback receiveHeadersCallback,
ReadWriteCallback sendCallback,
SeekCallback seekCallback,
ReadWriteCallback receiveBodyCallback)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
// Add callback for processing headers
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Header,
receiveHeadersCallback,
easyGCHandle,
ref _callbackHandle);
// If we're sending data as part of the request, add callbacks for sending request data
if (_requestMessage.Content != null)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Read,
sendCallback,
easyGCHandle,
ref _callbackHandle);
Interop.Http.RegisterSeekCallback(
_easyHandle,
seekCallback,
easyGCHandle,
ref _callbackHandle);
}
// If we're expecting any data in response, add a callback for receiving body data
if (_requestMessage.Method != HttpMethod.Head)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Write,
receiveBodyCallback,
easyGCHandle,
ref _callbackHandle);
}
}
internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
CURLcode result = Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle);
return result;
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
string headerValue = headers.GetHeaderString(header.Key);
string headerKeyAndValue = string.IsNullOrEmpty(headerValue) ?
header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent
header.Key + ": " + headerValue;
if (!Interop.Http.SListAppend(handle, headerKeyAndValue))
{
throw CreateHttpRequestException();
}
}
}
internal void SetCurlOption(CURLoption option, string value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, long value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, IntPtr value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, SafeHandle value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal sealed class SendTransferState
{
internal readonly byte[] _buffer = new byte[RequestBufferSize]; // PERF TODO: Determine if this should be optimized to start smaller and grow
internal int _offset;
internal int _count;
internal Task<int> _task;
internal void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
_task = task;
_offset = offset;
_count = count;
}
}
internal void SetRedirectUri(Uri redirectUri)
{
_targetUri = _requestMessage.RequestUri;
_requestMessage.RequestUri = redirectUri;
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null)
{
CurlHandler.VerboseTrace(text, memberName, easy: this, agent: null);
}
}
}
}
| |
namespace MiniUML.Plugins.UmlClassDiagram.Controls.ViewModel.Shape.Base
{
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Xml;
using MiniUML.Framework;
using MiniUML.Model.ViewModels;
using MiniUML.Model.ViewModels.Shapes;
using MiniUML.Plugins.UmlClassDiagram.Converter;
public abstract class UmlShapeBaseViewModel : ShapeSizeViewModelBase
{
#region fields
protected const string XmlComment = "#comment";
protected const string NameSpace = "MiniUml";
protected readonly string mElementName = string.Empty;
private readonly ShapeViewModelKey mShapeKey = ShapeViewModelKey.Undefined;
private readonly ShapeViewModelSubKeys mShapeViewModelSubKeys = ShapeViewModelSubKeys.Undefined;
private readonly UmlTypes mUmlType = UmlTypes.Undefined;
private readonly ObservableCollection<CommentViewModel> mComments = null;
#endregion fields
#region constructor
/// <summary>
/// Standard constructor
/// </summary>
/// <param name="parent"></param>
/// <param name="ElementName"></param>
/// <param name="shapeKey"></param>
/// <param name="shapeViewModelSubKeys"></param>
public UmlShapeBaseViewModel(IShapeParent parent,
ShapeViewModelKey shapeKey,
ShapeViewModelSubKeys shapeViewModelSubKeys,
UmlTypes umlType)
: base(parent)
{
this.mShapeKey = shapeKey;
this.mShapeViewModelSubKeys = shapeViewModelSubKeys;
this.mUmlType = umlType;
this.mComments = new ObservableCollection<CommentViewModel>();
this.mElementName = UmlTypeToStringConverter.Instance.Convert(umlType, umlType.GetType(), null,
CultureInfo.InvariantCulture) as string;
}
#endregion constructor
#region properties
/// <summary>
/// Get the (XML) key name of this objects class of elements.
/// </summary>
public override string XElementName
{
get
{
return this.mElementName;
}
}
/// <summary>
/// This key identifies the viewmodel implementation that is associated with a view control.
/// </summary>
public ShapeViewModelKey ShapeKey
{
get
{
return this.mShapeKey;
}
}
/// <summary>
/// Some viewmodels can manage multiple sub-views. This property holds
/// the key to those sub-view <-> sub-viewmodel association (if any).
/// </summary>
public ShapeViewModelSubKeys ShapeSubKey
{
get
{
return this.mShapeViewModelSubKeys;
}
}
/// <summary>
/// Get string identifier that represents the ImplementingViewModel
/// as <seealso cref="ShapeViewModelKey"/> does. This identifier can
/// be used by the TemplateSelector to find the implementing view
/// (this extra property avoids an extra string cast -
/// a string datatype is necessary since the template selector lives outside of this plug-in).
/// </summary>
public override string TypeKey
{
get
{
return ShapeViewModelKeyStrings.GetPresentationStringKey(this.mShapeKey);
}
}
/// <summary>
/// Get the unique enumerable type of the view-viewmodel type
/// that is managed in this object.
/// </summary>
public UmlTypes UmlDataType
{
get
{
return this.mUmlType;
}
}
/// <summary>
/// Sting representation of the UmlDataType property. This can be used when
/// direct string matching is required.
/// </summary>
public string UmlDataTypeString
{
get
{
object o = UmlTypeToStringConverter.Instance.Convert(this.UmlDataType, this.UmlDataType.GetType(),
null, CultureInfo.InvariantCulture);
if ((o is string) == false)
throw new ArgumentException(string.Format("Node name: '{0}' is not supported.", this.UmlDataType));
string umlType = o as string;
return umlType;
}
}
#endregion properties
#region methodes
/// <summary>
/// Read the complete content of the associated XML node for this type of object.
/// </summary>
/// <param name="reader"></param>
/// <param name="ret"></param>
/// <returns></returns>
public static string ReadDocument(XmlReader reader,
UmlShapeBaseViewModel ret)
{
// Read child elements of this XML node
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
string nodeName = reader.Name;
string error;
if ((error = ret.ReadXMLNode(nodeName, reader)) != string.Empty)
throw new NotImplementedException(error);
}
}
return string.Empty;
}
public void AddComment(CommentViewModel c)
{
this.mComments.Add(c);
}
/// <summary>
/// Persist the contents of this object into the given
/// parameter <paramref name="writer"/> object.
/// </summary>
/// <param name="writer"></param>
public void SaveDocument(System.Xml.XmlWriter writer)
{
// persist comment information as series of optional XML tags
foreach (var item in this.mComments)
{
item.SaveDocument(writer);
}
}
/// <summary>
/// Read the content of an XML node and return an error string
/// if the XML node was not known to this method.
/// </summary>
/// <param name="nodeName"></param>
/// <param name="reader"></param>
/// <returns></returns>
protected string ReadXMLNode(string nodeName, XmlReader reader)
{
switch (nodeName)
{
case CommentViewModel.Comment_TAG:
CommentViewModel c = CommentViewModel.ReadDocument(reader.ReadSubtree());
if (c != null) // Add into list of comments
this.AddComment(c);
return string.Empty;
default:
return string.Format("'{0}' is not a valid sub-node of {1}", reader.Name, this.XElementName);
}
}
/// <summary>
/// Save the attribute values of this class to XML.
/// </summary>
/// <param name="writer"></param>
protected virtual void SaveAttributes(System.Xml.XmlWriter writer)
{
writer.WriteAttributeString("Name", string.Format("{0}", this.Name));
writer.WriteAttributeString("ID", string.Format("{0}", this.ID));
writer.WriteAttributeString("Position", string.Format("{0},{1},{2},{3}",
this.Left, this.Top, this.Width, this.Height));
}
/// <summary>
/// Read the attribute values of this class from XML.
/// </summary>
/// <param name="readerName"></param>
/// <param name="readerValue"></param>
/// <returns></returns>
protected virtual bool ReadAttributes(string readerName, string readerValue)
{
switch (readerName)
{
case "Position":
double[] size = FrameworkUtilities.GetDoubleAttributes(readerValue, 4,
new double[] { 100, 100, 200, 200 });
this.Position = new System.Windows.Point(size[0], size[1]);
this.Width = size[2];
this.Height = size[3];
return true;
case "ID":
this.ID = readerValue;
return true;
case "Name":
this.Name = readerValue;
return true;
case "xmlns":
if (readerValue != NameSpace)
throw new ArgumentException("XML namespace:'" + readerValue + "' is not supported.");
return true;
default:
return false;
}
}
#endregion methods
}
}
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Redis
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// FirewallRulesOperations operations.
/// </summary>
internal partial class FirewallRulesOperations : IServiceOperations<RedisManagementClient>, IFirewallRulesOperations
{
/// <summary>
/// Initializes a new instance of the FirewallRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal FirewallRulesOperations(RedisManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RedisManagementClient
/// </summary>
public RedisManagementClient Client { get; private set; }
/// <summary>
/// Gets all firewall rules in the specified redis cache.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cacheName'>
/// The name of the Redis cache.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RedisFirewallRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string cacheName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (cacheName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "cacheName");
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Headers.TryAddWithoutValidation("redirect", "true");
_httpRequest.Method = new HttpMethod("FirewallRules_List");
_httpRequest.RequestUri = new System.Uri("https://bogus");
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
var @params = new Dictionary<string, object>
{
{ "subscriptionId", Client.SubscriptionId },
{ "resourceGroupName", resourceGroupName },
{ "cacheName", cacheName },
};
string _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(@params, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RedisFirewallRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RedisFirewallRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
return _result;
}
/// <summary>
/// Gets all firewall rules in the specified redis cache.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<RedisFirewallRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Headers.TryAddWithoutValidation("redirect", "true");
_httpRequest.Method = new HttpMethod("FirewallRules_List");
_httpRequest.RequestUri = new System.Uri("https://bogus");
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
var @params = new Dictionary<string, object>
{
{ "subscriptionId", Client.SubscriptionId },
{ "nextPageLink", nextPageLink },
};
string _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(@params, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<RedisFirewallRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RedisFirewallRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
return _result;
}
}
}
| |
// ============================================================================
// FileName: StorageLayer.cs
//
// Description:
// Provides common functionality to access different database and file storage
// layers.
//
// Author(s):
// Aaron Clauson
//
// History:
// 24 Dec 2004 Aaron Clauson Created.
// 19 Mar 2006 Aaron Clauson Added StoreLargeObject.
// 08 Sep 2006 Aaron Clauson Modified to work with non-pooled connections as Npgsql currently has big problems in its connection
// pooling mechanism.
// ? Aaron Clauson Isolated the problem in Npgsql connection pooling and workaround is to set MinPoolSize=0 in the connection
// string. Modified to work with connection pooling again.
// 16 Dec 2007 Aaron Clauson Added check for dangerous SQL.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using SIPSorcery.Sys;
using log4net;
using MySql.Data.MySqlClient;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.Persistence
{
public class StorageLayer
{
public const string FILENAME_DATETIME_FORMAT = "ddMMMyy-HHmmss";
// Constants used by Npgsql to decide whether a connection string is a pooling one or not.
// To be a non-pooled string Pooling=false and MinPoolsSize and MaxPoolSize must not be present.
public static readonly string Pooling = "POOLING=false";
public static readonly string MinPoolSize = "MINPOOLSIZE";
public static readonly string MaxPoolSize = "MAXPOOLSIZE";
private ILog logger = AppState.logger;
//private static string m_errorNotificationAddress = AppState.ErrorNotificationEmail;
private StorageTypes m_storageType;
private string m_dbConnStr = null;
public StorageLayer()
{}
public StorageLayer(StorageTypes storageType, string dbConnStr)
{
m_storageType = storageType;
m_dbConnStr = dbConnStr;
}
/// <summary>
/// Checks SQL queries to filter out ones that match an SQL injection attack.
/// </summary>
/// <param name="query"></param>
private void QuerySecurityCheck(string query)
{
// Run a security check on query for SQL injection attacks.
if (query != null && Regex.Match(query, @"'\S;").Success)
{
//SIPSorcerySMTP.SendEmail(m_errorNotificationAddress, m_errorNotificationAddress, "Illegal SQL Detected", query);
throw new ApplicationException("SQL not permitted: " + query);
}
}
public void ExecuteNonQuery(string query)
{
ExecuteNonQuery(m_storageType, m_dbConnStr, query);
}
public void ExecuteNonQuery(string query, Dictionary<string, object> parameters) {
ExecuteNonQuery(m_storageType, m_dbConnStr, query, parameters);
}
public void ExecuteNonQuery(StorageTypes storageType, string dbConnString, string query)
{
QuerySecurityCheck(query);
try
{
using (IDbConnection dbConn = GetDbConnection(storageType, dbConnString)) {
dbConn.Open();
IDbCommand command = GetDbCommand(storageType, dbConn, query);
command.ExecuteNonQuery();
}
}
catch(Exception excp)
{
logger.Error("Exception ExecuteNonQuery. " + excp.Message);
throw excp;
}
}
public void ExecuteNonQuery(StorageTypes storageType, string dbConnString, string query, Dictionary<string, object> parameters) {
try {
using (IDbConnection dbConn = GetDbConnection(storageType, dbConnString)) {
dbConn.Open();
IDbCommand command = GetDbCommand(storageType, dbConn, query);
if (parameters != null && parameters.Count > 0) {
foreach (KeyValuePair<string, object> parameter in parameters) {
command.Parameters.Add(GetDbParameter(storageType, parameter.Key, parameter.Value));
}
}
command.ExecuteNonQuery();
}
}
catch (Exception excp) {
logger.Error("Exception ExecuteNonQuery. " + excp.Message);
throw excp;
}
}
public object ExecuteScalar(string query)
{
return ExecuteScalar(m_storageType, m_dbConnStr, query);
}
public object ExecuteScalar(string query, Dictionary<string, object> parameters) {
return ExecuteScalar(m_storageType, m_dbConnStr, query, parameters);
}
public object ExecuteScalar(StorageTypes storageType, string dbConnString, string query) {
QuerySecurityCheck(query);
try {
using (IDbConnection dbConn = GetDbConnection(storageType, dbConnString)) {
dbConn.Open();
IDbCommand command = GetDbCommand(storageType, dbConn, query);
return command.ExecuteScalar();
}
}
catch (Exception excp) {
logger.Error("Exception ExecuteScalar. " + excp.Message);
throw excp;
}
}
public object ExecuteScalar(StorageTypes storageType, string dbConnString, string query, Dictionary<string, object> parameters) {
QuerySecurityCheck(query);
try {
using (IDbConnection dbConn = GetDbConnection(storageType, dbConnString)) {
dbConn.Open();
IDbCommand command = GetDbCommand(storageType, dbConn, query);
if (parameters != null && parameters.Count > 0) {
foreach (KeyValuePair<string, object> parameter in parameters) {
command.Parameters.Add(GetDbParameter(storageType, parameter.Key, parameter.Value));
}
}
return command.ExecuteScalar();
}
}
catch (Exception excp) {
logger.Error("Exception ExecuteScalar. " + excp.Message);
throw excp;
}
}
public DataSet GetDataSet(string query)
{
return GetDataSet(m_storageType, m_dbConnStr, query);
}
public DataSet GetDataSet(StorageTypes storageType, string dbConnString, string query)
{
QuerySecurityCheck(query);
try {
using (IDbConnection dbConn = GetDbConnection(storageType, dbConnString)) {
dbConn.Open();
IDataAdapter adapter = GetDataAdapter(storageType, dbConn, query);
DataSet resultSet = new DataSet();
adapter.Fill(resultSet);
return resultSet;
}
}
catch (Exception excp) {
logger.Error("Exception GetDataSet. " + excp.Message);
throw excp;
}
}
//public int StoreLargeObject(Stream largeObjectStream)
//{
// return StoreLargeObject(m_storageType, m_dbConnStr, largeObjectStream);
//}
//public int StoreLargeObject(StorageTypes storageType, string dbConnString, Stream largeObjectStream)
//{
// try
// {
// if(storageType == StorageTypes.Postgresql)
// {
// NpgsqlConnection connPgsql = new NpgsqlConnection(dbConnString);
// connPgsql.Open();
// NpgsqlTransaction t = connPgsql.BeginTransaction();
// LargeObjectManager lbm = new LargeObjectManager(connPgsql);
// int noid = lbm.Create(LargeObjectManager.READWRITE);
// LargeObject lo = lbm.Open(noid, LargeObjectManager.READWRITE);
// long offset = 0;
// while(offset < largeObjectStream.Length)
// {
// long bytesToWrite = (largeObjectStream.Length - offset > 1024) ? 1024 : largeObjectStream.Length - offset;
// byte[] buf = new byte[bytesToWrite];
// largeObjectStream.Read(buf, 0, (int)bytesToWrite);
// lo.Write(buf);
// offset += bytesToWrite;
// }
// lo.Close();
// t.Commit();
// // If using the Npgsql pooling close the connection to place it back in the pool.
// connPgsql.Close();
// return noid;
// }
// else
// {
// throw new ApplicationException("Not supported in StorageLayer.StoreLargeObject");
// }
// }
// catch(Exception excp)
// {
// logger.Error("Exception StoreLargeObject. " + excp.Message);
// throw excp;
// }
//}
//public byte[] GetLargeObject(int largeObjectId)
//{
// return GetLargeObject(m_storageType, m_dbConnStr, largeObjectId);
//}
//public byte[] GetLargeObject(StorageTypes storageType, string dbConnString, int largeObjectId)
//{
// try
// {
// if(storageType == StorageTypes.Postgresql)
// {
// NpgsqlConnection connPgsql = new NpgsqlConnection(dbConnString);
// connPgsql.Open();
// NpgsqlTransaction t = connPgsql.BeginTransaction();
// LargeObjectManager lbm = new LargeObjectManager(connPgsql);
// LargeObject lo = lbm.Open(largeObjectId, LargeObjectManager.READWRITE);
// byte[] buffer = lo.Read(lo.Size());
// lo.Close();
// t.Commit();
// // If using the Npgsql pooling close the connection to place it back in the pool.
// connPgsql.Close();
// return buffer;
// }
// else
// {
// throw new ApplicationException("Not supported in StorageLayer.StoreLargeObject");
// }
// }
// catch(Exception excp)
// {
// logger.Error("Exception StoreLargeObject. " + excp.Message);
// throw excp;
// }
//}
//public void StoreByteA(string query, byte[] buffer)
//{
// QuerySecurityCheck(query);
// try
// {
// if (m_storageType == StorageTypes.Postgresql)
// {
// NpgsqlConnection connPgsql = null;
// try
// {
// connPgsql = new NpgsqlConnection(m_dbConnStr);
// connPgsql.Open();
// NpgsqlCommand command = new NpgsqlCommand(query, connPgsql);
// NpgsqlParameter param = new NpgsqlParameter(":bytesData", DbType.Binary);
// param.Value = buffer;
// command.Parameters.Add(param);
// command.ExecuteNonQuery();
// }
// catch (Exception npgsqlExcp)
// {
// throw new ApplicationException("Exception StoreByteA (Npgsql Connection Pooling). Original exception type " + npgsqlExcp.GetType() + ". " + npgsqlExcp.Message);
// }
// finally
// {
// // If using the Npgsql pooling close the connection to place it back in the pool.
// connPgsql.Close();
// }
// }
// else
// {
// throw new ApplicationException("StorageType " + m_storageType + " not currently supported in ExecuteScalar");
// }
// }
// catch (Exception excp)
// {
// //logger.Error("Exception ExecuteScalar. " + excp.Message);
// throw excp;
// }
//}
/// <summary>
/// Used to determine whethe Npgsql will treat a connection string as pooling or not.
/// Npgsql assumes a connection string is pooling by default.
/// </summary>
public bool IsPooledConnectionString(string dbConnStr)
{
if(dbConnStr != null)
{
if(Regex.Match(dbConnStr, MinPoolSize, RegexOptions.IgnoreCase).Success)
{
return true;
}
else if(Regex.Match(dbConnStr, MaxPoolSize, RegexOptions.IgnoreCase).Success)
{
return true;
}
else if(Regex.Match(dbConnStr, Pooling , RegexOptions.IgnoreCase).Success)
{
return false;
}
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="column">Needs to be a bit data type from Postgresql.</param>
/// <returns></returns>
public bool ConvertToBool(object column)
{
//Npgsql, this works now in Npgsql version 0.99.3.
//return Convert.ToBoolean(column);
if(column.ToString() == "0")
{
return false;
}
else if(column.ToString() == "1")
{
return true;
}
else
{
throw new ApplicationException("Couldn't convert a database boolean type in StorageLayer.");
}
}
public static bool ConvertToBoolean(object column)
{
//Npgsql, this works now in Npgsql version 0.99.3.
//return Convert.ToBoolean(column);
if(column == null || column.ToString() == null)
{
return false;
}
else if (column.ToString() == "0" || column.ToString() == "f" || column.ToString() == "F" || Regex.Match(column.ToString(), "false", RegexOptions.IgnoreCase).Success)
{
return false;
}
else if (column.ToString() == "1" | column.ToString() == "t" || column.ToString() == "T" || Regex.Match(column.ToString(), "true", RegexOptions.IgnoreCase).Success)
{
return true;
}
else
{
throw new ApplicationException("Couldn't convert a database boolean type in StorageLayer.");
}
}
public static IDbConnection GetDbConnection(StorageTypes storageType, string dbConnStr) {
//if (storageType == StorageTypes.Postgresql) {
// return new NpgsqlConnection(dbConnStr);
//}
if (storageType == StorageTypes.MySQL) {
return new MySqlConnection(dbConnStr);
}
//else if (storageType == StorageTypes.MSSQL)
//{
// return new SqlConnection(dbConnStr);
//}
else
{
throw new ApplicationException("Storage type " + storageType + " is not supported by GetDbConnection.");
}
}
public static IDbCommand GetDbCommand(StorageTypes storageType, IDbConnection dbConn, string cmdText) {
//if (storageType == StorageTypes.Postgresql) {
// return new NpgsqlCommand(cmdText, (NpgsqlConnection)dbConn);
//}
if (storageType == StorageTypes.MySQL) {
return new MySqlCommand(cmdText, (MySqlConnection)dbConn);
}
//else if (storageType == StorageTypes.MSSQL)
//{
// return new SqlCommand(cmdText, (SqlConnection)dbConn);
//}
else
{
throw new ApplicationException("Storage type " + storageType + " is not supported by GetDbConnection.");
}
}
private IDataAdapter GetDataAdapter(StorageTypes storageType, IDbConnection dbConn, string cmdText) {
//if (storageType == StorageTypes.Postgresql) {
// return new NpgsqlDataAdapter(cmdText, (NpgsqlConnection)dbConn);
//}
if (storageType == StorageTypes.MySQL) {
return new MySqlDataAdapter(cmdText, (MySqlConnection)dbConn);
}
//else if (storageType == StorageTypes.MSSQL)
//{
// return new SqlDataAdapter(cmdText, (SqlConnection)dbConn);
//}
else
{
throw new ApplicationException("Storage type " + storageType + " is not supported by GetDbConnection.");
}
}
public static IDataParameter GetDbParameter(StorageTypes storageType, string name, object value) {
//if (storageType == StorageTypes.Postgresql) {
// return new NpgsqlParameter(name, value);
//}
if (storageType == StorageTypes.MySQL) {
return new MySqlParameter(name, value);
}
//else if (storageType == StorageTypes.MSSQL)
//{
// return new SqlParameter(name, value);
//}
else
{
throw new ApplicationException("Storage type " + storageType + " is not supported by GetDbParameter.");
}
}
#region Unit tests.
#if UNITTEST
[TestFixture]
public class StorageLayerUnitTests
{
[TestFixtureSetUp]
public void Init()
{
}
[TestFixtureTearDown]
public void Dispose()
{
}
[Test]
public void SampleTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsTrue(true, "True was false.");
}
[Test]
public void PoolingConnectionStringTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string poolingConnStr = "Server=127.0.0.1;Port=23001;User Id=user;Password=password;Database=postgres;MaxPoolSize=15;MinPoolSize=1;CommandTimeout=1;Encoding=UNICODE;";
StorageLayer storageLayer = new StorageLayer();
Assert.IsTrue(storageLayer.IsPooledConnectionString(poolingConnStr), "Connection string was not correctly recognised as pooling.");
}
[Test]
public void PoolingConnectionStringNoMinOrMaxTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string poolingConnStr = "Server=127.0.0.1;Port=23001;User Id=user;Password=password;Database=postgres;CommandTimeout=1;Encoding=UNICODE;";
StorageLayer storageLayer = new StorageLayer();
Assert.IsTrue(storageLayer.IsPooledConnectionString(poolingConnStr), "Connection string was not correctly recognised as pooling.");
}
[Test]
public void NonPoolingConnectionStringTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string poolingConnStr = "Server=127.0.0.1;Port=23001;User Id=user;Password=password;Database=postgres;Pooling=false;CommandTimeout=1;Encoding=UNICODE;";
StorageLayer storageLayer = new StorageLayer();
Assert.IsTrue(!storageLayer.IsPooledConnectionString(poolingConnStr), "Connection string was not correctly recognised as non pooling.");
}
}
#endif
#endregion
}
}
| |
using System;
/*
Gaigen 2.5 Test Suite
*/
/*
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
namespace c3ga_ns {
public class Parser {
private class BasisBlade
{
private int bitmap = 0;
private double scale = 1.0;
public int getBitmap() { return bitmap; }
public double getScale() { return scale; }
public void wedgeBasisVector(int bvIdx)
{
int b;
b = 1 << bvIdx;
if ((bitmap & b) != 0)
{ // bv ^ bv = 0
scale = 0.0;
return;
}
else
{
// add basis vector to bitmap
bitmap |= b;
bvIdx++;
for (; bvIdx <= 3; bvIdx++) // compute sign flips due to anti commuting basis vectors
if ((bitmap & (1 << bvIdx)) != 0) scale = -scale;
}
}
public void multiply(double scalar)
{
scale *= scalar;
}
}
private String inputString;
private String sourceString;
private int startIdx = 0;
private int endIdx = 0;
private int lineIdx = 0;
private int currentLineStart = 0;
private double[] coord = new double[8];
// TOKEN IDs: (for internal use only)
private const int T_BAD_IDENTIFIER = -100;
private const int T_BAD_NUMBER = -10;
private const int T_BAD_CHARACTER = -1;
private const int T_END_OF_STRING = 0;
private const int T_WEDGE = 1;
private const int T_MUL = 2;
private const int T_PLUS = 3;
private const int T_MINUS = 4;
private const int T_NUMBER = 10;
private const int T_FIRST_BASIS_VECTOR = 100;
private const int T_LAST_BASIS_VECTOR = 103;
private ParseException GetException(String reason)
{
return new ParseException(reason + " at " + sourceString + ", line " + (lineIdx+1) + ", column " + (startIdx - currentLineStart +1));
}
private Parser(String input, String source) {
inputString = input;
sourceString = source;
if ((sourceString == null) || (length(sourceString) == 0))
sourceString = "string";
}
private void sum(BasisBlade bb) {
int idx = c3ga.BasisElementIndexByBitmap[bb.getBitmap()];
coord[idx] += bb.getScale() / (double)c3ga.BasisElementSignByIndex[idx];
}
private static bool isLetter(char x) {
return Char.IsLetter(x);
}
private static bool isDigit(char x) {
return Char.IsDigit(x);
}
private static bool isLetterOrDigit(char x) {
return Char.IsLetterOrDigit(x);
}
private String substring(int startIdx, int endIdx) {
return inputString.Substring(startIdx, endIdx - startIdx + 1);
}
private static int length(String str) {
return str.Length;
}
private static char charAt(String str, int idx) {
return str[idx];
}
private int getNextToken() {
int l = length(inputString);
// skip all whitespace and other empty stuff, keep track of line index
while ((startIdx < l) && (charAt(inputString, startIdx) >= 0) && (charAt(inputString, startIdx) <= ' ')) {
if (charAt(inputString, startIdx) == 0x0A) { // start of new line
lineIdx++;
currentLineStart = startIdx+1;
}
startIdx++;
}
// detect end of string
if (startIdx == l) {
startIdx = endIdx;
return T_END_OF_STRING; // EOS
}
// operators
if (charAt(inputString, startIdx) == '^') {endIdx = startIdx; return T_WEDGE;} // ^
else if (charAt(inputString, startIdx) == '*') {endIdx = startIdx; return T_MUL;} // *
else if (charAt(inputString, startIdx) == '+') {endIdx = startIdx; return T_PLUS;} // +
else if (charAt(inputString, startIdx) == '-') {endIdx = startIdx; return T_MINUS;} // -
else if (isDigit(charAt(inputString, startIdx)) || (charAt(inputString, startIdx) == '.')) { // parse number?
endIdx = startIdx;
// eat up all digits and at most one point
bool pointFound = false;
while ((endIdx < l) && (isDigit(charAt(inputString, endIdx)) || (charAt(inputString, endIdx) == '.'))) {
endIdx++;
if (charAt(inputString, endIdx) == '.') {
endIdx++;
pointFound = true;
break;
}
}
if (pointFound) { // if point found, eat up all digits
while ((endIdx < l) && isDigit(charAt(inputString, endIdx))) {
endIdx++;
}
}
// see if there is a 'e' or 'E'
if ((charAt(inputString, endIdx) == 'e') || (charAt(inputString, endIdx) == 'E')) {
endIdx++;
// accept at most one +-
if ((charAt(inputString, endIdx) == '-') || (charAt(inputString, endIdx) == '+')) {
endIdx++;
}
// if there is an 'e', there must be some digit
if (!isDigit(charAt(inputString, endIdx))) return T_BAD_NUMBER; // bad number
// eat up all digits
while ((endIdx < l) && isDigit(charAt(inputString, endIdx))) {
endIdx++;
}
}
endIdx--; // end index is inclusive
return T_NUMBER;
}
else if (isLetter(charAt(inputString, startIdx)) || (charAt(inputString, startIdx) == '_')) { // parse identifier?
// find end of chain of numbers, letters and '_'
endIdx = startIdx + 1;
while ((endIdx < l) && (isLetterOrDigit(charAt(inputString, endIdx)) || (charAt(inputString, endIdx) == '_'))) endIdx++;
endIdx--; // end index is inclusive
// see which basis vector it is
String bvName = substring(startIdx, endIdx);
for (int i = 0; i < 3; i++)
if (c3ga.BasisVectorNames[i].Equals(bvName)) return T_FIRST_BASIS_VECTOR + i; // basis vector
return T_BAD_IDENTIFIER; // bad identifier
}
else return T_BAD_CHARACTER;
} // end of getNextToken()
/// <summary>Parses a multivector string (e.g., as created by mv.ToString())
/// Throws a ParseException when the input cannot be parsed.
///
/// </summary>
/// <param name="str">The multivector string.
/// </param>
/// <param name="strSourceName">Description of where the string came from (may be null). This string is used in exception messages.
/// </param>
public static mv Parse(String str, String strSourceName)
{
return new Parser(str, strSourceName).Parse();
}
private mv Parse() {
int token;
bool firstLoop = true;
// get the first token
token = getNextToken();
while (true) {
// reset for next basis blade
BasisBlade bb = new BasisBlade();
bool beDone = false; // basis element done
if (token == T_END_OF_STRING) break;
int cnt = 0;
while ((token == T_PLUS) || (token == T_MINUS)) { // accept all +-
cnt++;
startIdx = endIdx+1;
if (token == T_MINUS) bb.multiply(-1.0); // -
token = getNextToken();
}
// require at least one +- if this is not the first term:
if ((!firstLoop) && (cnt == 0)) {
throw GetException("Expected '+' or '-'");
}
if ((token == T_NUMBER) ||
((token >= T_FIRST_BASIS_VECTOR) && (token <= T_LAST_BASIS_VECTOR))) // must be number or basis vector
{
if (token == T_NUMBER) {
{ // multiply scale with value of number
try {
bb.multiply((double)Double.Parse(substring(startIdx, endIdx)));
} catch (Exception ) {
throw GetException("Cannot parse number");
}
}
startIdx = endIdx+1;
// * or ^ ?
token = getNextToken();
if ((token == T_WEDGE) || (token == T_MUL)) {
startIdx = endIdx+1;
// must find basis vector
token = getNextToken();
}
else { // just a single scalar is OK
startIdx = endIdx+1;
beDone = true;
}
}
if (!beDone) {
if ((token >= T_FIRST_BASIS_VECTOR) && (token <= T_LAST_BASIS_VECTOR)) {
int bvIdx = token - T_FIRST_BASIS_VECTOR;
bb.wedgeBasisVector(bvIdx);
startIdx = endIdx+1;
}
else {
throw GetException("Expected basis vector");
}
}
if (!beDone) {
// accept ^ basis vector as many times as it takes
while (true) {
// ^
token = getNextToken();
if (token != T_WEDGE) break;
startIdx = endIdx+1;
// basis vector
token = getNextToken();
if ((token >= T_FIRST_BASIS_VECTOR) && (token <= T_LAST_BASIS_VECTOR)) {
int bvIdx = token - T_FIRST_BASIS_VECTOR;
bb.wedgeBasisVector(bvIdx);
startIdx = endIdx+1;
}
else {
throw GetException("Expected basis vector");
}
}
}
} // end of 'if number or bv'
else if (token == T_BAD_CHARACTER) {
throw GetException("Bad character");
}
else if (token == T_BAD_NUMBER) {
throw GetException("Bad number");
}
else if (token == T_BAD_IDENTIFIER) {
throw GetException("Bad identifier");
}
else {
throw GetException("Unexpected token");
}
// add
sum(bb);
// remember that the first loop is done
firstLoop = false;
}
mv result = new mv(GroupBitmap.GRADE_0 | GroupBitmap.GRADE_1 | GroupBitmap.GRADE_2 | GroupBitmap.GRADE_3 | 0, coord);
result.Compress(0.0);
return result;
} // end of Parse()
} // end of class Parser
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using log4net;
using FluorineFx.Messaging.Api.Messaging;
using FluorineFx.Messaging.Api.Stream;
using FluorineFx.Messaging.Api.Stream.Support;
using FluorineFx.Messaging.Api;
using FluorineFx.Context;
using FluorineFx.Configuration;
namespace FluorineFx.Messaging.Rtmp.Stream
{
class StreamService : IStreamService
{
private static ILog log = LogManager.GetLogger(typeof(StreamService));
/// <summary>
/// Returns current stream id.
/// </summary>
/// <returns></returns>
private int GetCurrentStreamId()
{
return (int)FluorineContext.Current.Connection.GetAttribute(FluorineContext.FluorineStreamIdKey);
}
/// <summary>
/// Returns broadcast scope object for given scope and child scope name.
/// </summary>
/// <param name="scope">Scope object.</param>
/// <param name="name">Child scope name.</param>
/// <returns>Broadcast scope.</returns>
public IBroadcastScope GetBroadcastScope(IScope scope, string name)
{
IBasicScope basicScope = scope.GetBasicScope(Constants.BroadcastScopeType, name);
return basicScope as IBroadcastScope;
}
#region IStreamService Members
public void Start(ConfigurationSection configuration)
{
}
public void Shutdown()
{
}
public int createStream()
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return -1;
return (connection as IStreamCapableConnection).ReserveStreamId();
}
public void closeStream()
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IClientStream stream = (connection as IStreamCapableConnection).GetStreamById(GetCurrentStreamId());
if (stream != null)
{
if (stream is IClientBroadcastStream)
{
IClientBroadcastStream bs = stream as IClientBroadcastStream;
IBroadcastScope bsScope = GetBroadcastScope(connection.Scope, bs.PublishedName);
if (bsScope != null && connection is BaseConnection)
{
(connection as BaseConnection).UnregisterBasicScope(bsScope);
}
}
stream.Close();
}
(connection as IStreamCapableConnection).DeleteStreamById(GetCurrentStreamId());
}
public void deleteStream(int streamId)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
deleteStream(streamConnection, streamId);
}
public void deleteStream(IStreamCapableConnection connection, int streamId)
{
IClientStream stream = connection.GetStreamById(streamId);
if (stream != null)
{
if (stream is IClientBroadcastStream)
{
IClientBroadcastStream bs = stream as IClientBroadcastStream;
IBroadcastScope bsScope = GetBroadcastScope(connection.Scope, bs.PublishedName);
if (bsScope != null && connection is BaseConnection)
{
(connection as BaseConnection).UnregisterBasicScope(bsScope);
}
}
stream.Close();
}
connection.UnreserveStreamId(streamId);
}
public void releaseStream(string streamName)
{
}
public void play(bool dontStop)
{
if (!dontStop)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
int streamId = GetCurrentStreamId();
IClientStream stream = streamConnection.GetStreamById(streamId);
if (stream != null)
stream.Stop();
}
}
public void play(string name)
{
play(name, -2000, -1000, true);
}
public void play(string name, double start)
{
play(name, start, -1000, true);
}
public void play(string name, double start, double length)
{
play(name, start, length, true);
}
public void play(string name, double start, double length, bool flushPlaylist)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
IScope scope = connection.Scope;
int streamId = GetCurrentStreamId();
if (name == null || string.Empty.Equals(name))
{
SendNSFailed(streamConnection as RtmpConnection, "The stream name may not be empty.", name, streamId);
return;
}
IStreamSecurityService security = ScopeUtils.GetScopeService(scope, typeof(IStreamSecurityService)) as IStreamSecurityService;
if (security != null)
{
IEnumerator handlers = security.GetStreamPlaybackSecurity();
while(handlers.MoveNext())
{
IStreamPlaybackSecurity handler = handlers.Current as IStreamPlaybackSecurity;
if(!handler.IsPlaybackAllowed(scope, name, (long)start, (long)length, flushPlaylist))
{
SendNSFailed(streamConnection as RtmpConnection, "You are not allowed to play the stream.", name, streamId);
return;
}
}
}
IClientStream stream = streamConnection.GetStreamById(streamId);
bool created = false;
if (stream == null)
{
stream = streamConnection.NewPlaylistSubscriberStream(streamId);
stream.Start();
created = true;
}
if (!(stream is ISubscriberStream))
return;
ISubscriberStream subscriberStream = stream as ISubscriberStream;
SimplePlayItem item = new SimplePlayItem();
item.Name = name;
item.Start = (long)start;
item.Length = (long)length;
if (subscriberStream is IPlaylistSubscriberStream)
{
IPlaylistSubscriberStream playlistStream = subscriberStream as IPlaylistSubscriberStream;
if (flushPlaylist)
playlistStream.RemoveAllItems();
playlistStream.AddItem(item);
}
else if (subscriberStream is ISingleItemSubscriberStream)
{
ISingleItemSubscriberStream singleStream = subscriberStream as ISingleItemSubscriberStream;
singleStream.PlayItem = item;
}
else
{
// not supported by this stream service
return;
}
try
{
subscriberStream.Play();
} catch(System.IO.IOException ex)
{
if (created)
{
stream.Close();
streamConnection.DeleteStreamById(streamId);
}
SendNSFailed(streamConnection as RtmpConnection, ex.Message, name, streamId);
}
}
public void publish(string name)
{
publish(name, Constants.ClientStreamModeLive);
}
public void publish(string name, string mode)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
IScope scope = connection.Scope;
int streamId = GetCurrentStreamId();
if (name == null || string.Empty.Equals(name))
{
SendNSFailed(streamConnection as RtmpConnection, "The stream name may not be empty.", name, streamId);
return;
}
IStreamSecurityService security = ScopeUtils.GetScopeService(scope, typeof(IStreamSecurityService)) as IStreamSecurityService;
if (security != null)
{
IEnumerator handlers = security.GetStreamPublishSecurity();
while(handlers.MoveNext())
{
IStreamPublishSecurity handler = handlers.Current as IStreamPublishSecurity;
if (!handler.IsPublishAllowed(scope, name, mode))
{
SendNSFailed(streamConnection as RtmpConnection, "You are not allowed to publish the stream.", name, streamId);
return;
}
}
}
IBroadcastScope bsScope = GetBroadcastScope(scope, name);
if (bsScope != null && bsScope.GetProviders().Count > 0)
{
// Another stream with that name is already published.
StatusASO badName = new StatusASO(StatusASO.NS_PUBLISH_BADNAME);
badName.clientid = streamId;
badName.details = name;
badName.level = "error";
// FIXME: there should be a direct way to send the status
RtmpChannel channel = (streamConnection as RtmpConnection).GetChannel((byte)(4 + ((streamId - 1) * 5)));
channel.SendStatus(badName);
return;
}
IClientStream stream = streamConnection.GetStreamById(streamId);
if (stream != null && !(stream is IClientBroadcastStream))
return;
bool created = false;
if (stream == null)
{
stream = streamConnection.NewBroadcastStream(streamId);
created = true;
}
IClientBroadcastStream bs = stream as IClientBroadcastStream;
try
{
bs.PublishedName = name;
IScopeContext context = connection.Scope.Context;
//IProviderService providerService = (IProviderService)context.getBean(IProviderService.BEAN_NAME);
IProviderService providerService = ScopeUtils.GetScopeService(connection.Scope, typeof(IProviderService)) as IProviderService;
// TODO handle registration failure
if (providerService.RegisterBroadcastStream(connection.Scope, name, bs))
{
bsScope = GetBroadcastScope(connection.Scope, name);
bsScope.SetAttribute(Constants.BroadcastScopeStreamAttribute, bs);
if (connection is BaseConnection)
{
(connection as BaseConnection).RegisterBasicScope(bsScope);
}
}
if (Constants.ClientStreamModeRecord.Equals(mode))
{
bs.Start();
bs.SaveAs(name, false);
}
else if (Constants.ClientStreamModeAppend.Equals(mode))
{
bs.Start();
bs.SaveAs(name, true);
}
else if (Constants.ClientStreamModeLive.Equals(mode))
{
bs.Start();
}
bs.StartPublishing();
}
catch (System.IO.IOException ex)
{
StatusASO accessDenied = new StatusASO(StatusASO.NS_RECORD_NOACCESS);
accessDenied.clientid = streamId;
accessDenied.description = "The file could not be created/written to." + ex.Message;
accessDenied.details = name;
accessDenied.level = "error";
// FIXME: there should be a direct way to send the status
RtmpChannel channel = (streamConnection as RtmpConnection).GetChannel((byte)(4 + ((streamId - 1) * 5)));
channel.SendStatus(accessDenied);
bs.Close();
if (created)
streamConnection.DeleteStreamById(streamId);
}
catch (Exception ex)
{
log.Warn("Publish caught exception", ex);
}
}
public void publish(bool dontStop)
{
if (!dontStop)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
int streamId = GetCurrentStreamId();
IClientStream stream = streamConnection.GetStreamById(streamId);
if (!(stream is IBroadcastStream))
return;
IBroadcastStream bs = stream as IBroadcastStream;
if (bs.PublishedName == null)
return;
IBroadcastScope bsScope = GetBroadcastScope(connection.Scope, bs.PublishedName);
if (bsScope != null)
{
bsScope.Unsubscribe(bs.Provider);
if (connection is BaseConnection)
(connection as BaseConnection).UnregisterBasicScope(bsScope);
}
bs.Close();
streamConnection.DeleteStreamById(streamId);
}
}
public void seek(double position)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
int streamId = GetCurrentStreamId();
IClientStream stream = streamConnection.GetStreamById(streamId);
if (stream == null || !(stream is ISubscriberStream))
return;
ISubscriberStream subscriberStream = stream as ISubscriberStream;
try
{
subscriberStream.Seek((int)position);
}
catch (NotSupportedException ex)
{
StatusASO seekFailed = new StatusASO(StatusASO.NS_SEEK_FAILED);
seekFailed.clientid = streamId;
seekFailed.description = "The stream doesn't support seeking.";
seekFailed.level = "error";
seekFailed.details = ex.Message;
// FIXME: there should be a direct way to send the status
RtmpChannel channel = (streamConnection as RtmpConnection).GetChannel((byte)(4 + ((streamId - 1) * 5)));
channel.SendStatus(seekFailed);
}
}
public void pause(bool pausePlayback, double position)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
int streamId = GetCurrentStreamId();
IClientStream stream = streamConnection.GetStreamById(streamId);
if (stream == null || !(stream is ISubscriberStream))
return;
ISubscriberStream subscriberStream = stream as ISubscriberStream;
if (pausePlayback)
subscriberStream.Pause((int)position);
else
subscriberStream.Resume((int)position);
}
public void receiveVideo(bool receive)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
int streamId = GetCurrentStreamId();
IClientStream stream = streamConnection.GetStreamById(streamId);
if (stream == null || !(stream is ISubscriberStream))
return;
ISubscriberStream subscriberStream = stream as ISubscriberStream;
subscriberStream.ReceiveVideo(receive);
}
public void receiveAudio(bool receive)
{
IConnection connection = FluorineContext.Current.Connection;
if (!(connection is IStreamCapableConnection))
return;
IStreamCapableConnection streamConnection = connection as IStreamCapableConnection;
int streamId = GetCurrentStreamId();
IClientStream stream = streamConnection.GetStreamById(streamId);
if (stream == null || !(stream is ISubscriberStream))
return;
ISubscriberStream subscriberStream = stream as ISubscriberStream;
subscriberStream.ReceiveAudio(receive);
}
#endregion
private void SendNSFailed(RtmpConnection connection, string description, string name, int streamId)
{
StatusASO failed = new StatusASO(StatusASO.NS_FAILED);
failed.clientid = streamId;
failed.description = description;
failed.details = name;
failed.level = "error";
// FIXME: there should be a direct way to send the status
RtmpChannel channel = connection.GetChannel((byte)(4 + ((streamId - 1) * 5)));
channel.SendStatus(failed);
}
}
}
| |
// 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 gctv = Google.Cloud.Tasks.V2;
using sys = System;
namespace Google.Cloud.Tasks.V2
{
/// <summary>Resource name for the <c>Task</c> resource.</summary>
public sealed partial class TaskName : gax::IResourceName, sys::IEquatable<TaskName>
{
/// <summary>The possible contents of <see cref="TaskName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/queues/{queue}/tasks/{task}</c>.
/// </summary>
ProjectLocationQueueTask = 1,
}
private static gax::PathTemplate s_projectLocationQueueTask = new gax::PathTemplate("projects/{project}/locations/{location}/queues/{queue}/tasks/{task}");
/// <summary>Creates a <see cref="TaskName"/> 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="TaskName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static TaskName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TaskName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="TaskName"/> with the pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}/tasks/{task}</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="queueId">The <c>Queue</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="taskId">The <c>Task</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TaskName"/> constructed from the provided ids.</returns>
public static TaskName FromProjectLocationQueueTask(string projectId, string locationId, string queueId, string taskId) =>
new TaskName(ResourceNameType.ProjectLocationQueueTask, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), queueId: gax::GaxPreconditions.CheckNotNullOrEmpty(queueId, nameof(queueId)), taskId: gax::GaxPreconditions.CheckNotNullOrEmpty(taskId, nameof(taskId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TaskName"/> with pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}/tasks/{task}</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="queueId">The <c>Queue</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="taskId">The <c>Task</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TaskName"/> with pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}/tasks/{task}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string queueId, string taskId) =>
FormatProjectLocationQueueTask(projectId, locationId, queueId, taskId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TaskName"/> with pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}/tasks/{task}</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="queueId">The <c>Queue</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="taskId">The <c>Task</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TaskName"/> with pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}/tasks/{task}</c>.
/// </returns>
public static string FormatProjectLocationQueueTask(string projectId, string locationId, string queueId, string taskId) =>
s_projectLocationQueueTask.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(queueId, nameof(queueId)), gax::GaxPreconditions.CheckNotNullOrEmpty(taskId, nameof(taskId)));
/// <summary>Parses the given resource name string into a new <see cref="TaskName"/> 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}/queues/{queue}/tasks/{task}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="taskName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TaskName"/> if successful.</returns>
public static TaskName Parse(string taskName) => Parse(taskName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TaskName"/> 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}/queues/{queue}/tasks/{task}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="taskName">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="TaskName"/> if successful.</returns>
public static TaskName Parse(string taskName, bool allowUnparsed) =>
TryParse(taskName, allowUnparsed, out TaskName 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="TaskName"/> 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}/queues/{queue}/tasks/{task}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="taskName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TaskName"/>, 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 taskName, out TaskName result) => TryParse(taskName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TaskName"/> 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}/queues/{queue}/tasks/{task}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="taskName">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="TaskName"/>, 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 taskName, bool allowUnparsed, out TaskName result)
{
gax::GaxPreconditions.CheckNotNull(taskName, nameof(taskName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationQueueTask.TryParseName(taskName, out resourceName))
{
result = FromProjectLocationQueueTask(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(taskName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TaskName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string queueId = null, string taskId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
QueueId = queueId;
TaskId = taskId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TaskName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/queues/{queue}/tasks/{task}</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="queueId">The <c>Queue</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="taskId">The <c>Task</c> ID. Must not be <c>null</c> or empty.</param>
public TaskName(string projectId, string locationId, string queueId, string taskId) : this(ResourceNameType.ProjectLocationQueueTask, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), queueId: gax::GaxPreconditions.CheckNotNullOrEmpty(queueId, nameof(queueId)), taskId: gax::GaxPreconditions.CheckNotNullOrEmpty(taskId, nameof(taskId)))
{
}
/// <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>Queue</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string QueueId { get; }
/// <summary>
/// The <c>Task</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TaskId { 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.ProjectLocationQueueTask: return s_projectLocationQueueTask.Expand(ProjectId, LocationId, QueueId, TaskId);
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 TaskName);
/// <inheritdoc/>
public bool Equals(TaskName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TaskName a, TaskName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TaskName a, TaskName b) => !(a == b);
}
public partial class Task
{
/// <summary>
/// <see cref="gctv::TaskName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::TaskName TaskName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::TaskName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2015 FPT Software
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using ModernHttpClient;
using Cirrious.MvvmCross.ViewModels;
using FSoft.WordApp.Core.Services;
using FSoft.WordApp.Core.Models;
using System.Collections.ObjectModel;
using EShyMedia.MvvmCross.Plugins.DeviceInfo;
using Cirrious.CrossCore;
using Beezy.MvvmCross.Plugins.SecureStorage;
namespace FSoft.WordApp.Core.ViewModels
{
public class LoginViewModel: BaseViewModel
{
public LoginViewModel(IFNewsService service, IMvxDeviceInfo deviceInfoPlugin) : base(service, deviceInfoPlugin)
{
#if DEBUG
// Username = "admin";
// Password= "123456";
#endif
//IsLoading = false;
try {
LoadSavedData();
} catch (Exception e ){
}
}
private void LoadSavedData() {
var data = Mvx.Resolve<IMvxProtectedData>();
var _u = data.Unprotect (UsernamePropertyName);
var _p = data.Unprotect (PasswordPropertyName);
var _r = data.Unprotect (RememberPasswordPropertyName);
if (!string.IsNullOrEmpty (_u))
Username = _u;
if (!string.IsNullOrEmpty (_p))
Password = _p;
if (!string.IsNullOrEmpty (_r)) {
RememberPassword = _r.Equals ("1");
}
}
private void SaveData() {
var data = Mvx.Resolve<IMvxProtectedData>();
if (RememberPassword) {
data.Protect (UsernamePropertyName, Username);
data.Protect (PasswordPropertyName, Password);
data.Protect (RememberPasswordPropertyName, "1");
} else {
data.Protect (RememberPasswordPropertyName, "0");
data.Remove (UsernamePropertyName);
data.Remove (PasswordPropertyName);
}
}
public const string UsernamePropertyName = "Username";
private string username = string.Empty;
public string Username
{
get { return username; }
set { SetProperty(ref username, value, UsernamePropertyName); }
}
public const string PasswordPropertyName = "Password";
private string password = string.Empty;
public string Password
{
get { return password; }
set { SetProperty(ref password, value, PasswordPropertyName); }
}
public const string RememberPasswordPropertyName = "RememberPassword";
private bool _RememberPassword = false;
public bool RememberPassword
{
get { return _RememberPassword; }
set { SetProperty(ref _RememberPassword, value, RememberPasswordPropertyName); }
}
public const string ErrorPropertyName = "Error";
private string error = string.Empty;
public string Error {
get { return error; }
set {
SetProperty (ref error, value, ErrorPropertyName);
HasError = !string.IsNullOrEmpty (value);
if (HasError)
ShowErrorMessage (Error);
}
}
private bool _HasError;
public bool HasError {
get { return _HasError; }
set { SetProperty (ref _HasError, value, "HasError");}
}
private bool isLoading = false;
public new bool IsLoading {
get { return isLoading; }
set {
SetProperty (ref isLoading, value, IsLoadingPropertyName);
IsNotBusy = !(value);
ShowIntro = false;
}
}
private bool isNotBusy = true;
public bool IsNotBusy {
get { return isNotBusy;}
set { SetProperty (ref isNotBusy, value, "IsNotBusy"); }
}
private bool _IsSoftkeyHided;
public bool IsSoftkeyHided {
get { return _IsSoftkeyHided;}
set {
SetProperty (ref _IsSoftkeyHided, value, "IsSoftkeyHided");
ShowIntro = value;
if (IsLoading)
ShowIntro = false;
}
}
private bool _IsSoftkeyShowed;
public bool IsSoftkeyShowed {
get { return _IsSoftkeyShowed;}
set {
SetProperty (ref _IsSoftkeyShowed, value, "IsSoftkeyShowed");
//ShowIntro = value;//dont call here!!!!
}
}
private string _Info = string.Empty;
public string Info {
get { return _Info; }
set { SetProperty (ref _Info, value, "Info");}
}
private bool _showIntro;
public bool ShowIntro {
get { return _showIntro;}
set { SetProperty (ref _showIntro, value, "ShowIntro");}
}
private bool _useTreeMenu = true;
public bool UseTreeMenu {
get { return _useTreeMenu; }
set { SetProperty (ref _useTreeMenu, value, "UseTreeMenu"); }
}
private Cirrious.MvvmCross.ViewModels.MvxCommand _loginCommand;
public System.Windows.Input.ICommand LoginCommand
{
get
{
_loginCommand = _loginCommand ?? new Cirrious.MvvmCross.ViewModels.MvxCommand(DoLogin);
return _loginCommand;
}
}
public event EventHandler UpdateClientHandler;
public void showUpdateStore(){
ShowWebPage(Settings.UpdateInfo.Update_info.Link);
}
async private void DoLogin()
{
if (Status == NetworkStatus.NotReachable) {
Error = Settings.MSG_NETWORK_NOT_REACHABLE;
return;
}
SaveData ();
await ExecuteLoginCommand ();
if (Settings.UpdateInfo != null) {
if (UpdateClientHandler != null)
UpdateClientHandler (this, new UpdateClientEventArgs("Update",Settings.UpdateInfo.Update_info.Message,"OK"));
} else if (Settings.wpLoggedIn) {
Settings.Categories = null; //force to refresh
Close (this);
Settings.RootViewModel.RefreshData ();
//ShowViewModel<RootViewModel>();
}
}
protected async Task ExecuteLoginCommand()
{
Error = string.Empty;
if (Username.Equals(string.Empty) || Password.Equals(string.Empty)) {
Error = Settings.MSG_EMPTY_USERNAME_OR_PWD;
return;
}
if (isLoading)
return;
IsLoading = true;
Info = "We're processing...";
Settings.UseTreeMenu = UseTreeMenu;
try {
var content = new FormUrlEncodedContent (new[] {
new KeyValuePair<string, string> (Settings.WP_USERNAME_FIELD, Username),
new KeyValuePair<string, string> (Settings.WP_PWD_FIELD, Password)
});
NativeCookieHandler cookieHandler = Settings.mNativeCookieHandler;//new NativeCookieHandler ();
NativeMessageHandler handler = new NativeMessageHandler(true,true,cookieHandler){
UseCookies = true,
};
handler.AllowAutoRedirect = false;
HttpClient client = new HttpClient (handler);
HttpResponseMessage response = await client.PostAsync (Settings.LoginUrl, content);
if (response.StatusCode == HttpStatusCode.Redirect) {
Debug.WriteLine("Redirect: " + response.ToString());
Settings.wpLoggedIn = true;
Settings.wpUsername = Username;
Settings.wpPassword = Password;
} else {
string resultContent = await response.Content.ReadAsStringAsync ();
response.EnsureSuccessStatusCode ();
string responseUri = response.RequestMessage.RequestUri.ToString ();
Debug.WriteLine (responseUri);
Debug.WriteLine(resultContent);
if (Settings.LoginUrl.ToLower ().Equals (responseUri.ToLower ())) {
//login failed
Error = Settings.MSG_INVALID_USERNAME_OR_PWD;
} else {
Settings.wpLoggedIn = true;
Settings.wpUsername = Username;
Settings.wpPassword = Password;
}
}
if (Settings.wpLoggedIn) {
if (Settings.CHECK_UPDATE) {
var buildDetail = Mvx.Resolve<IBuildDetails>();
var respUpdate = await Service.GetUpdate(new RequestUpdate(buildDetail.OS, buildDetail.VersionCode));
if (respUpdate.Update_info != null) {
Settings.UpdateInfo = respUpdate;
IsLoading = false;
return;
}
System.Diagnostics.Debug.WriteLine("Build detail os={0} version_code={1}", buildDetail.OS, buildDetail.VersionCode);
}
//go to profile to get more cookies
response = await client.GetAsync(Settings.ProfileUrl);
//get user info and gen cookie for json api auth controller
var retAuth = await Service.GenrateAuthCookie();
if (retAuth != null) {
Settings.WP_AuthCookie = retAuth;
} else {
Settings.WP_AuthCookie = null;
}
}
} catch (Exception e ){
Error = Settings.MSG_NETWORK_COMMON;
#if DEBUG
System.Diagnostics.Debug.WriteLine("Login Error: " + e.Message);
Error += e.ToString();
#endif
}
Info = string.Empty;
IsLoading = false;
}
async private void LoadHomePosts() {
// //load home posts
var _GroupedPosts = new ObservableCollection<CatalogPostsGroup> ();
var cpbk = new CatalogPostsGroup ();
//cpbk.Category = new Category(-1, "Breaking Category");
_GroupedPosts.Add(cpbk);
var homePosts =await Service.GetHomePosts (new RequestHomePosts ());
foreach (HomePostGroup gr in homePosts.Home_posts) {
if (gr.Category.Breaking_news == 1) {
var post = gr.Posts.ToArray()[0];
var bk = new BreakingNews(post);
cpbk.Add(bk);
} else {
var cp = new CatalogPostsGroup ();
cp.Title = gr.Category.Title;
cp.ShortTitle = cp.Title;
cp.Category = gr.Category;
//ListPost.Clear ();
var pas = gr.Posts.ToArray ();
for (int i = 0; i < pas.Length; i++) {
cp.Add(pas[i]);
}
_GroupedPosts.Add (cp);
}
}
//
// foreach (Category cat in cats.Categories)
// if ((cat.Visible == 1 && cat.Parent == 0) || cat.Id == Settings.WP_SLIDEMAIN_ID)
// {
// var req = new RequestCategoryPosts ();
// req.Id = cat.Id;
// req.Page = 1;
// req.Count = 3;
//
// ResponseListPost resPosts = null;
// try{
// if (req.GetType () == typeof(RequestRecentPosts)) {
// resPosts = await Service.GetRecentPosts ((RequestRecentPosts)req);
// } else {
// resPosts = await Service.GetCategoryPosts ((RequestCategoryPosts)req);
// }
//
// if (cat.Id == Settings.WP_SLIDEMAIN_ID) {
// //News at index=0 of slide main catalog is breaking news
// var pas = resPosts.Posts.ToArray ();
// var bk = new BreakingNews(pas[0]);
// cpbk.Add(bk);
// } else {
// var cp = new CatalogPostsGroup ();
// cp.Title = cat.Title;
// cp.ShortTitle = cp.Title;
// cp.Category = cat;
// //ListPost.Clear ();
// var pas = resPosts.Posts.ToArray ();
// for (int i = 0; i < pas.Length; i++) {
// cp.Add(pas[i]);
// }
//
// _GroupedPosts.Add (cp);
// }
//
// System.Diagnostics.Debug.WriteLine("HomeViewModel loaded cat posts: " + cat.Title);
// } catch (Exception e){
//
// }
//
// }
Settings.GroupedPosts = _GroupedPosts;
}
}
public class UpdateClientEventArgs : EventArgs
{
public string Title { get; private set; }
public string Message { get; private set; }
public string CloseTitle { get; private set;}
public UpdateClientEventArgs(string title, string message, string closeTitle)
{
Title = title;
Message = message;
CloseTitle = closeTitle;
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections.Generic;
using log4net;
using OpenSim.Framework;
namespace OpenSim.Server.Base
{
public static class ServerUtils
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static string SLAssetTypeToContentType(int assetType)
{
switch (assetType)
{
case 0:
return "image/jp2";
case 1:
return "application/ogg";
case 2:
return "application/x-metaverse-callingcard";
case 3:
return "application/x-metaverse-landmark";
case 5:
return "application/x-metaverse-clothing";
case 6:
return "application/x-metaverse-primitive";
case 7:
return "application/x-metaverse-notecard";
case 8:
return "application/x-metaverse-folder";
case 10:
return "application/x-metaverse-lsl";
case 11:
return "application/x-metaverse-lso";
case 12:
return "image/tga";
case 13:
return "application/x-metaverse-bodypart";
case 17:
return "audio/x-wav";
case 19:
return "image/jpeg";
case 20:
return "application/x-metaverse-animation";
case 21:
return "application/x-metaverse-gesture";
case 22:
return "application/x-metaverse-simstate";
default:
return "application/octet-stream";
}
}
public static byte[] SerializeResult(XmlSerializer xs, object data)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8);
xw.Formatting = Formatting.Indented;
xs.Serialize(xw, data);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] ret = ms.GetBuffer();
Array.Resize(ref ret, (int)ms.Length);
return ret;
}
public static T LoadPlugin<T>(string dllName, Object[] args) where T:class
{
string[] parts = dllName.Split(new char[] {':'});
dllName = parts[0];
string className = String.Empty;
if (parts.Length > 1)
className = parts[1];
return LoadPlugin<T>(dllName, className, args);
}
public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
{
string interfaceName = typeof(T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (className != String.Empty &&
pluginType.ToString() !=
pluginType.Namespace + "." + className)
continue;
Type typeInterface =
pluginType.GetInterface(interfaceName, true);
if (typeInterface != null)
{
T plug = null;
try
{
plug = (T)Activator.CreateInstance(pluginType,
args);
}
catch (Exception e)
{
if (!(e is System.MissingMethodException))
m_log.ErrorFormat("Error loading plugin from {0}, exception {1}", dllName, e.InnerException);
return null;
}
return plug;
}
}
}
return null;
}
catch (Exception e)
{
m_log.ErrorFormat("Error loading plugin from {0}, exception {1}", dllName, e);
return null;
}
}
public static Dictionary<string, string> ParseQueryString(string query)
{
Dictionary<string, string> result = new Dictionary<string, string>();
string[] terms = query.Split(new char[] {'&'});
if (terms.Length == 0)
return result;
foreach (string t in terms)
{
string[] elems = t.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
result[name] = value;
}
return result;
}
public static string BuildQueryString(Dictionary<string, string> data)
{
string qstring = String.Empty;
foreach (KeyValuePair<string, string> kvp in data)
{
string part;
if (kvp.Value != String.Empty)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"=" + System.Web.HttpUtility.UrlEncode(kvp.Value);
}
else
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key);
}
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
return qstring;
}
public static string BuildXmlResponse(Dictionary<string, object> data)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
BuildXmlData(rootElement, data);
return doc.InnerXml;
}
private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
{
foreach (KeyValuePair<string, object> kvp in data)
{
XmlElement elem = parent.OwnerDocument.CreateElement("",
kvp.Key, "");
if (kvp.Value is Dictionary<string, object>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
}
else
{
elem.AppendChild(parent.OwnerDocument.CreateTextNode(
kvp.Value.ToString()));
}
parent.AppendChild(elem);
}
}
public static Dictionary<string, object> ParseXmlResponse(string data)
{
//m_log.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
if (rootL.Count != 1)
return ret;
XmlNode rootNode = rootL[0];
ret = ParseElement(rootNode);
return ret;
}
private static Dictionary<string, object> ParseElement(XmlNode element)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlNodeList partL = element.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List")
{
ret[part.Name] = part.InnerText;
}
else
{
ret[part.Name] = ParseElement(part);
}
}
return ret;
}
}
}
| |
// 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 ShiftRightLogicalUInt321()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalUInt321();
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 class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ImmUnaryOpTest__ShiftRightLogicalUInt321
{
private struct TestStruct
{
public Vector128<UInt32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalUInt321 testClass)
{
var result = Sse2.ShiftRightLogical(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalUInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public ImmUnaryOpTest__ShiftRightLogicalUInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftRightLogical(
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftRightLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalUInt321();
var result = Sse2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftRightLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((uint)(firstOp[0] >> 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((uint)(firstOp[i] >> 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<UInt32>(Vector128<UInt32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// FIXMEs:
// - some bad mappings:
// - C int -> C# int
// - C long -> C# int
// not sure what they should be.
// The sources are wrong. Those C code should not use int and long for each.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using PmDeviceID = System.Int32;
using PmTimestamp = System.Int32;
using PortMidiStream = System.IntPtr;
using PmMessage = System.Int32;
using PmError = Commons.Music.Midi.PortMidi.PortMidiErrorType;
namespace Commons.Music.Midi.PortMidi
{
public class PortMidiDeviceManager
{
static PortMidiDeviceManager ()
{
PortMidiMarshal.Pm_Initialize ();
#if !PORTABLE // FIXME: what to do for PCLs!?
AppDomain.CurrentDomain.DomainUnload += delegate (object o, EventArgs e) {
PortMidiMarshal.Pm_Terminate ();
};
#endif
}
public static int DeviceCount {
get { return PortMidiMarshal.Pm_CountDevices (); }
}
public static int DefaultInputDeviceID {
get { return PortMidiMarshal.Pm_GetDefaultInputDeviceID (); }
}
public static int DefaultOutputDeviceID {
get { return PortMidiMarshal.Pm_GetDefaultOutputDeviceID (); }
}
public static IEnumerable<PortMidiDeviceInfo> AllDevices {
get {
for (int i = 0; i < DeviceCount; i++)
yield return GetDeviceInfo (i);
}
}
public static PortMidiDeviceInfo GetDeviceInfo (PmDeviceID id)
{
return new PortMidiDeviceInfo (id, PortMidiMarshal.Pm_GetDeviceInfo (id));
}
public static PortMidiInputStream OpenInput (PmDeviceID inputDevice)
{
return OpenInput (inputDevice, default_buffer_size);
}
const int default_buffer_size = 1024;
public static PortMidiInputStream OpenInput (PmDeviceID inputDevice, int bufferSize)
{
IntPtr stream;
var e = PortMidiMarshal.Pm_OpenInput (out stream, inputDevice, IntPtr.Zero, bufferSize, null, IntPtr.Zero);
if (e != PmError.NoError)
throw new PortMidiException (e, String.Format ("Failed to open MIDI input device {0}", e));
return new PortMidiInputStream (stream, inputDevice);
}
public static PortMidiOutputStream OpenOutput (PmDeviceID outputDevice)
{
IntPtr stream;
var e = PortMidiMarshal.Pm_OpenOutput (out stream, outputDevice, IntPtr.Zero, 0, null, IntPtr.Zero, 0);
if (e != PmError.NoError)
throw new PortMidiException (e, String.Format ("Failed to open MIDI output device {0}", e));
return new PortMidiOutputStream (stream, outputDevice, 0);
}
}
public enum PortMidiErrorType
{
NoError = 0,
NoData = 0,
GotData = 1,
HostError = -10000,
InvalidDeviceId,
InsufficientMemory,
BufferTooSmall,
BufferOverflow,
BadPointer,
BadData,
InternalError,
BufferMaxSize,
}
public class PortMidiException : Exception
{
PmError error_type;
public PortMidiException (PmError errorType, string message)
: this (errorType, message, null)
{
}
public PortMidiException (PmError errorType, string message, Exception innerException)
: base (message, innerException)
{
error_type = errorType;
}
public PmError ErrorType {
get { return error_type; }
}
}
public struct PortMidiDeviceInfo
{
int id;
PmDeviceInfo info;
internal PortMidiDeviceInfo (int id, IntPtr ptr)
{
this.id = id;
this.info = (PmDeviceInfo) Marshal.PtrToStructure (ptr, typeof (PmDeviceInfo));
}
public int ID {
get { return id; }
set { id = value; }
}
public string Interface {
get { return Marshal.PtrToStringAnsi (info.Interface); }
}
public string Name {
get { return Marshal.PtrToStringAnsi (info.Name); }
}
public bool IsInput { get { return info.Input != 0; } }
public bool IsOutput { get { return info.Output != 0; } }
public bool IsOpened { get { return info.Opened != 0; } }
public override string ToString ()
{
return String.Format ("{0} - {1} ({2} {3})", Interface, Name, IsInput ? (IsOutput ? "I/O" : "Input") : (IsOutput ? "Output" : "N/A"), IsOpened ? "open" : String.Empty);
}
}
public abstract class PortMidiStream : IDisposable
{
public static IEnumerable<PortMidiEvent> Convert (byte [] bytes, int index, int size)
{
int i = index;
int end = index + size;
while (i < end) {
if (bytes [i] == 0xF0 || bytes [i] == 0xF7) {
var tmp = new byte [size];
Array.Copy (bytes, i, tmp, 0, tmp.Length);
yield return new PortMidiEvent () {Message = new PortMidiMessage (0xF0, 0, 0), Data = tmp};
i += size + 1;
} else {
if (end < i + 3)
throw new PortMidiException (PortMidiErrorType.NoError, string.Format ("Received data was incomplete to build MIDI status message for '{0:X}' status.", bytes [i]));
yield return new PortMidiEvent () {Message = new PortMidiMessage (bytes [i], bytes [i + 1], bytes [i + 2])};
i += 3;
}
}
}
internal IntPtr stream;
internal PmDeviceID device;
protected PortMidiStream (IntPtr stream, PmDeviceID deviceID)
{
this.stream = stream;
device = deviceID;
}
public void Abort ()
{
PortMidiMarshal.Pm_Abort (stream);
}
public void Close ()
{
Dispose ();
}
public void Dispose ()
{
PortMidiMarshal.Pm_Close (stream);
}
public void SetFilter (PortMidiFilter filters)
{
PortMidiMarshal.Pm_SetFilter (stream, filters);
}
public void SetChannelMask (int mask)
{
PortMidiMarshal.Pm_SetChannelMask (stream, mask);
}
}
public class PortMidiInputStream : PortMidiStream
{
public PortMidiInputStream (IntPtr stream, PmDeviceID inputDevice)
: base (stream, inputDevice)
{
}
public bool HasData {
get { return PortMidiMarshal.Pm_Poll (stream) == PortMidiErrorType.GotData; }
}
public int Read (byte [] buffer, int index, int length)
{
var gch = GCHandle.Alloc (buffer);
try {
var ptr = Marshal.UnsafeAddrOfPinnedArrayElement (buffer, index);
int size = PortMidiMarshal.Pm_Read (stream, ptr, length);
if (size < 0)
throw new PortMidiException ((PortMidiErrorType) size, PortMidiMarshal.Pm_GetErrorText ((PmError) size));
return size * 4;
} finally {
gch.Free ();
}
}
}
public class PortMidiOutputStream : PortMidiStream
{
public PortMidiOutputStream (IntPtr stream, PmDeviceID outputDevice, int latency)
: base (stream, outputDevice)
{
}
public void Write (PortMidiEvent mevent)
{
if (mevent.Data != null)
WriteSysEx (mevent.Timestamp, mevent.Data);
else
Write (mevent.Timestamp, mevent.Message);
}
public void Write (PmTimestamp when, PortMidiMessage msg)
{
var ret = PortMidiMarshal.Pm_WriteShort (stream, when, msg);
if (ret != PmError.NoError)
throw new PortMidiException (ret, String.Format ("Failed to write message {0} : {1}", msg.Value, PortMidiMarshal.Pm_GetErrorText ((PmError) ret)));
}
public void WriteSysEx (PmTimestamp when, byte [] sysex)
{
var ret = PortMidiMarshal.Pm_WriteSysEx (stream, when, sysex);
if (ret != PmError.NoError)
throw new PortMidiException (ret, String.Format ("Failed to write sysex message : {0}", PortMidiMarshal.Pm_GetErrorText ((PmError) ret)));
}
public void Write (PortMidiEvent [] buffer)
{
Write (buffer, 0, buffer.Length);
}
public void Write (PortMidiEvent [] buffer, int index, int length)
{
var gch = GCHandle.Alloc (buffer);
try {
var ptr = Marshal.UnsafeAddrOfPinnedArrayElement (buffer, index);
var ret = PortMidiMarshal.Pm_Write (stream, ptr, length);
if (ret != PmError.NoError)
throw new PortMidiException (ret, String.Format ("Failed to write messages : {0}", PortMidiMarshal.Pm_GetErrorText ((PmError) ret)));
} finally {
gch.Free ();
}
}
}
[StructLayout (LayoutKind.Sequential)]
public struct PortMidiEvent
{
PortMidiMessage msg;
PmTimestamp ts;
#if !PORTABLE // FIXME: wait, P/Invoke exists without [NonSerialized]!?
[NonSerialized]
#endif
byte [] data;
public PortMidiMessage Message {
get { return msg; }
set { msg = value; }
}
public PmTimestamp Timestamp {
get { return ts; }
set { ts = value; }
}
public byte [] Data {
get { return data; }
set { data = value; }
}
}
public struct PortMidiMessage
{
PmMessage v;
public PortMidiMessage (PmMessage value)
{
v = value;
}
public PortMidiMessage (int status, int data1, int data2)
{
v = ((((data2) << 16) & 0xFF0000) | (((data1) << 8) & 0xFF00) | ((status) & 0xFF));
}
public PmMessage Value {
get { return v; }
}
}
public delegate PmTimestamp MidiTimeProcDelegate (IntPtr timeInfo);
[Flags]
public enum PortMidiFilter : int
{
Active = 1 << 0x0E,
SysEx = 1 << 0x00,
Clock = 1 << 0x08,
Play = ((1 << 0x0A) | (1 << 0x0C) | (1 << 0x0B)),
Tick = (1 << 0x09),
FD = (1 << 0x0D),
Undefined = FD,
Reset = (1 << 0x0F),
RealTime = (Active | SysEx | Clock | Play | Undefined | Reset | Tick),
Note = ((1 << 0x19) | (1 << 0x18)),
CAF = (1 << 0x1D),
PAF = (1 << 0x1A),
AF = (CAF | PAF),
Program = (1 << 0x1C),
Control = (1 << 0x1B),
PitchBend = (1 << 0x1E),
MTC = (1 << 0x01),
SongPosition = (1 << 0x02),
SongSelect = (1 << 0x03),
Tune = (1 << 0x06),
SystemCommon = (MTC | SongPosition | SongSelect | Tune)
}
// Marshal types
class PortMidiMarshal
{
[DllImport ("portmidi")]
public static extern PmError Pm_Initialize ();
[DllImport ("portmidi")]
public static extern PmError Pm_Terminate ();
// TODO
[DllImport ("portmidi")]
public static extern int Pm_HasHostError (IntPtr stream);
// TODO
[DllImport ("portmidi")]
public static extern string Pm_GetErrorText (PmError errnum);
// TODO
[DllImport ("portmidi")]
public static extern void Pm_GetHostErrorText (IntPtr msg, uint len);
const int HDRLENGTH = 50;
const uint PM_HOST_ERROR_MSG_LEN = 256;
// Device enumeration
const PmDeviceID PmNoDevice = -1;
[DllImport ("portmidi")]
public static extern int Pm_CountDevices ();
[DllImport ("portmidi")]
public static extern PmDeviceID Pm_GetDefaultInputDeviceID ();
[DllImport ("portmidi")]
public static extern PmDeviceID Pm_GetDefaultOutputDeviceID ();
[DllImport ("portmidi")]
public static extern IntPtr Pm_GetDeviceInfo (PmDeviceID id);
[DllImport ("portmidi")]
public static extern PmError Pm_OpenInput (
out IntPtr stream,
PmDeviceID inputDevice,
IntPtr inputDriverInfo,
int bufferSize,
MidiTimeProcDelegate timeProc,
IntPtr timeInfo);
[DllImport ("portmidi")]
public static extern PmError Pm_OpenOutput (
out IntPtr stream,
PmDeviceID outputDevice,
IntPtr outputDriverInfo,
int bufferSize,
MidiTimeProcDelegate time_proc,
IntPtr time_info,
int latency);
[DllImport ("portmidi")]
public static extern PmError Pm_SetFilter (IntPtr stream, PortMidiFilter filters);
// TODO
public static int Pm_Channel (int channel) { return 1 << channel; }
[DllImport ("portmidi")]
public static extern PmError Pm_SetChannelMask (IntPtr stream, int mask);
[DllImport ("portmidi")]
public static extern PmError Pm_Abort (IntPtr stream);
[DllImport ("portmidi")]
public static extern PmError Pm_Close (IntPtr stream);
// TODO
public static int Pm_MessageStatus (int msg) { return ((msg) & 0xFF); }
// TODO
public static int Pm_MessageData1 (int msg) { return (((msg) >> 8) & 0xFF); }
// TODO
public static int Pm_MessageData2 (int msg) { return (((msg) >> 16) & 0xFF); }
[DllImport ("portmidi")]
public static extern int Pm_Read (IntPtr stream, IntPtr buffer, int length);
[DllImport ("portmidi")]
public static extern PmError Pm_Poll (IntPtr stream);
[DllImport ("portmidi")]
public static extern PmError Pm_Write (IntPtr stream, IntPtr buffer, int length);
[DllImport ("portmidi")]
public static extern PmError Pm_WriteShort (IntPtr stream, PmTimestamp when, PortMidiMessage msg);
[DllImport ("portmidi")]
public static extern PmError Pm_WriteSysEx (IntPtr stream, PmTimestamp when, byte [] msg);
}
[StructLayout (LayoutKind.Sequential)]
struct PmDeviceInfo
{
[MarshalAs (UnmanagedType.SysInt)]
public int StructVersion; // it is not actually used.
public IntPtr Interface; // char*
public IntPtr Name; // char*
[MarshalAs (UnmanagedType.SysInt)]
public int Input; // 1 or 0
[MarshalAs (UnmanagedType.SysInt)]
public int Output; // 1 or 0
[MarshalAs (UnmanagedType.SysInt)]
public int Opened;
public override string ToString ()
{
return String.Format ("{0},{1:X},{2:X},{3},{4},{5}", StructVersion, Interface, Name, Input, Output, Opened);
}
}
}
| |
using Newtonsoft.Json.Linq;
using System;
using System.Diagnostics;
using ReactNative.Bridge;
using Windows.Media;
using Windows.Media.Playback;
using Windows.Media.Core;
using TrackPlayer.Logic;
namespace TrackPlayer.Players
{
public class LocalPlayback : Playback
{
private MediaPlayer player;
private IPromise loadCallback;
private bool started = false;
private bool ended = false;
private double startPos = 0;
public LocalPlayback(MediaManager manager, JObject options) : base(manager)
{
player = new MediaPlayer();
player.AutoPlay = false;
player.AudioCategory = MediaPlayerAudioCategory.Media;
player.CommandManager.IsEnabled = false;
player.MediaOpened += OnLoad;
player.MediaFailed += OnError;
player.MediaEnded += OnEnd;
player.CurrentStateChanged += OnStateChange;
}
public override SystemMediaTransportControls GetTransportControls()
{
return player.SystemMediaTransportControls;
}
protected override void Load(Track track, IPromise promise)
{
started = false;
ended = false;
startPos = 0;
loadCallback = promise;
player.Source = MediaSource.CreateFromUri(track.Url);
}
public override void Play()
{
started = true;
ended = false;
player.Play();
}
public override void Pause()
{
started = false;
player.Pause();
}
public override void Stop()
{
started = false;
ended = true;
player.Pause();
player.PlaybackSession.Position = TimeSpan.FromSeconds(0);
}
public override void SetVolume(double volume)
{
player.Volume = volume;
}
public override double GetVolume()
{
return player.Volume;
}
public override void SetRate(double rate)
{
player.PlaybackSession.PlaybackRate = rate;
}
public override double GetRate()
{
return player.PlaybackSession.PlaybackRate;
}
public override void SeekTo(double seconds)
{
startPos = seconds;
player.PlaybackSession.Position = TimeSpan.FromSeconds(seconds);
}
public override double GetPosition()
{
return player.PlaybackSession.Position.TotalSeconds;
}
public override double GetBufferedPosition()
{
try
{
return player.PlaybackSession.BufferingProgress * GetDuration();
}
catch (Exception)
{
return 0;
}
}
public override double GetDuration()
{
double duration = player.PlaybackSession.NaturalDuration.TotalSeconds;
if (duration <= 0)
{
Track track = GetCurrentTrack();
duration = track != null && track.Duration > 0 ? track.Duration : 0;
}
return duration;
}
public override PlaybackState GetState()
{
MediaPlaybackState state = player.PlaybackSession.PlaybackState;
if (ended && (state == MediaPlaybackState.Paused || state == MediaPlaybackState.None))
return PlaybackState.Stopped;
else if (state == MediaPlaybackState.Opening || state == MediaPlaybackState.Buffering)
return PlaybackState.Buffering;
else if (state == MediaPlaybackState.None)
return PlaybackState.None;
else if (state == MediaPlaybackState.Paused)
return PlaybackState.Paused;
else if (state == MediaPlaybackState.Playing)
return PlaybackState.Playing;
return PlaybackState.None;
}
public override void Dispose()
{
player.Dispose();
}
private void OnStateChange(MediaPlayer sender, object args)
{
UpdateState(GetState());
}
private void OnEnd(MediaPlayer sender, object args)
{
if (HasNext())
{
UpdateCurrentTrack(currentTrack + 1, null);
Play();
}
else
{
manager.OnEnd(GetCurrentTrack(), GetPosition());
}
}
private void OnError(MediaPlayer sender, MediaPlayerFailedEventArgs args)
{
loadCallback?.Reject("error", args.ErrorMessage);
loadCallback = null;
Debug.WriteLine(args.Error);
Debug.WriteLine(args.ErrorMessage);
string code = "playback";
if (args.Error == MediaPlayerError.DecodingError || args.Error == MediaPlayerError.SourceNotSupported)
code = "playback-renderer";
else if (args.Error == MediaPlayerError.NetworkError)
code = "playback-source";
manager.OnError(code, args.ErrorMessage);
}
private void OnLoad(MediaPlayer sender, object args)
{
Debug.WriteLine("OnLoad");
if (startPos > 0)
{
player.PlaybackSession.Position = TimeSpan.FromSeconds(startPos);
startPos = 0;
}
if (started) Play();
loadCallback?.Resolve(null);
loadCallback = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Providers;
namespace Orleans.Streams
{
internal class PersistentStreamPullingManager : SystemTarget, IPersistentStreamPullingManager, IStreamQueueBalanceListener
{
private static readonly TimeSpan QUEUES_PRINT_PERIOD = TimeSpan.FromMinutes(5);
private readonly Dictionary<QueueId, PersistentStreamPullingAgent> queuesToAgentsMap;
private readonly string streamProviderName;
private readonly IStreamProviderRuntime providerRuntime;
private readonly IStreamPubSub pubSub;
private readonly PersistentStreamProviderConfig config;
private readonly IProviderConfiguration providerConfig;
private readonly AsyncSerialExecutor nonReentrancyGuarantor; // for non-reentrant execution of queue change notifications.
private readonly LoggerImpl logger;
private int latestRingNotificationSequenceNumber;
private int latestCommandNumber;
private IQueueAdapter queueAdapter;
private readonly IQueueAdapterCache queueAdapterCache;
private IStreamQueueBalancer queueBalancer;
private readonly IQueueAdapterFactory adapterFactory;
private PersistentStreamProviderState managerState;
private IDisposable queuePrintTimer;
private int NumberRunningAgents { get { return queuesToAgentsMap.Count; } }
internal PersistentStreamPullingManager(
GrainId id,
string strProviderName,
IStreamProviderRuntime runtime,
IStreamPubSub streamPubSub,
IQueueAdapterFactory adapterFactory,
IStreamQueueBalancer streamQueueBalancer,
PersistentStreamProviderConfig config,
IProviderConfiguration providerConfig)
: base(id, runtime.ExecutingSiloAddress)
{
if (string.IsNullOrWhiteSpace(strProviderName))
{
throw new ArgumentNullException("strProviderName");
}
if (runtime == null)
{
throw new ArgumentNullException("runtime", "IStreamProviderRuntime runtime reference should not be null");
}
if (streamPubSub == null)
{
throw new ArgumentNullException("streamPubSub", "StreamPubSub reference should not be null");
}
if (streamQueueBalancer == null)
{
throw new ArgumentNullException("streamQueueBalancer", "IStreamQueueBalancer streamQueueBalancer reference should not be null");
}
queuesToAgentsMap = new Dictionary<QueueId, PersistentStreamPullingAgent>();
streamProviderName = strProviderName;
providerRuntime = runtime;
pubSub = streamPubSub;
this.config = config;
this.providerConfig = providerConfig;
nonReentrancyGuarantor = new AsyncSerialExecutor();
latestRingNotificationSequenceNumber = 0;
latestCommandNumber = 0;
queueBalancer = streamQueueBalancer;
this.adapterFactory = adapterFactory;
queueAdapterCache = adapterFactory.GetQueueAdapterCache();
logger = LogManager.GetLogger(GetType().Name + "-" + streamProviderName, LoggerType.Provider);
Log(ErrorCode.PersistentStreamPullingManager_01, "Created {0} for Stream Provider {1}.", GetType().Name, streamProviderName);
IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_PULLING_AGENTS, strProviderName), () => queuesToAgentsMap.Count);
}
public async Task Initialize(Immutable<IQueueAdapter> qAdapter)
{
if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null");
Log(ErrorCode.PersistentStreamPullingManager_02, "Init.");
// Remove cast once we cleanup
queueAdapter = qAdapter.Value;
await this.queueBalancer.Initialize(this.streamProviderName, this.adapterFactory.GetStreamQueueMapper(), config.SiloMaturityPeriod, this.providerConfig);
queueBalancer.SubscribeToQueueDistributionChangeEvents(this);
List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList();
Log(ErrorCode.PersistentStreamPullingManager_03, String.Format("Initialize: I am now responsible for {0} queues: {1}.", myQueues.Count, PrintQueues(myQueues)));
queuePrintTimer = this.RegisterTimer(AsyncTimerCallback, null, QUEUES_PRINT_PERIOD, QUEUES_PRINT_PERIOD);
managerState = PersistentStreamProviderState.Initialized;
}
public async Task Stop()
{
await StopAgents();
if (queuePrintTimer != null)
{
queuePrintTimer.Dispose();
this.queuePrintTimer = null;
}
(this.queueBalancer as IDisposable)?.Dispose();
this.queueBalancer = null;
}
public async Task StartAgents()
{
managerState = PersistentStreamProviderState.AgentsStarted;
List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList();
Log(ErrorCode.PersistentStreamPullingManager_Starting, "Starting agents for {0} queues: {1}", myQueues.Count, PrintQueues(myQueues));
await AddNewQueues(myQueues, true);
Log(ErrorCode.PersistentStreamPullingManager_Started, "Started agents.");
}
public async Task StopAgents()
{
managerState = PersistentStreamProviderState.AgentsStopped;
List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.ToList();
Log(ErrorCode.PersistentStreamPullingManager_Stopping, "Stopping agents for {0} queues: {1}", queuesToRemove.Count, PrintQueues(queuesToRemove));
await RemoveQueues(queuesToRemove);
Log(ErrorCode.PersistentStreamPullingManager_Stopped, "Stopped agents.");
}
#region Management of queues
/// <summary>
/// Actions to take when the queue distribution changes due to a failure or a join.
/// Since this pulling manager is system target and queue distribution change notifications
/// are delivered to it as grain method calls, notifications are not reentrant. To simplify
/// notification handling we execute them serially, in a non-reentrant way. We also supress
/// and don't execute an older notification if a newer one was already delivered.
/// </summary>
public Task QueueDistributionChangeNotification()
{
return this.ScheduleTask(() => this.HandleQueueDistributionChangeNotification());
}
public Task HandleQueueDistributionChangeNotification()
{
latestRingNotificationSequenceNumber++;
int notificationSeqNumber = latestRingNotificationSequenceNumber;
Log(ErrorCode.PersistentStreamPullingManager_04,
"Got QueueChangeNotification number {0} from the queue balancer. managerState = {1}", notificationSeqNumber, managerState);
if (managerState == PersistentStreamProviderState.AgentsStopped)
{
return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them.
}
return nonReentrancyGuarantor.AddNext(() =>
{
// skip execution of an older/previous notification since already got a newer range update notification.
if (notificationSeqNumber < latestRingNotificationSequenceNumber)
{
Log(ErrorCode.PersistentStreamPullingManager_05,
"Skipping execution of QueueChangeNotification number {0} from the queue allocator since already received a later notification " +
"(already have notification number {1}).",
notificationSeqNumber, latestRingNotificationSequenceNumber);
return Task.CompletedTask;
}
if (managerState == PersistentStreamProviderState.AgentsStopped)
{
return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them.
}
return QueueDistributionChangeNotification(notificationSeqNumber);
});
}
private async Task QueueDistributionChangeNotification(int notificationSeqNumber)
{
HashSet<QueueId> currentQueues = queueBalancer.GetMyQueues().ToSet();
Log(ErrorCode.PersistentStreamPullingManager_06,
"Executing QueueChangeNotification number {0}. Queue balancer says I should now own {1} queues: {2}", notificationSeqNumber, currentQueues.Count, PrintQueues(currentQueues));
try
{
Task t1 = AddNewQueues(currentQueues, false);
List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.Where(queueId => !currentQueues.Contains(queueId)).ToList();
Task t2 = RemoveQueues(queuesToRemove);
await Task.WhenAll(t1, t2);
}
finally
{
Log(ErrorCode.PersistentStreamPullingManager_16,
"Done Executing QueueChangeNotification number {0}. I now own {1} queues: {2}", notificationSeqNumber, NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys));
}
}
/// <summary>
/// Take responsibility for a set of new queues that were assigned to me via a new range.
/// We first create one pulling agent for every new queue and store them in our internal data structure, then try to initialize the agents.
/// ERROR HANDLING:
/// The responsibility to handle initialization and shutdown failures is inside the Agents code.
/// The manager will call Initialize once and log an error. It will not call initialize again and will assume initialization has succeeded.
/// Same applies to shutdown.
/// </summary>
/// <param name="myQueues"></param>
/// <param name="failOnInit"></param>
/// <returns></returns>
private async Task AddNewQueues(IEnumerable<QueueId> myQueues, bool failOnInit)
{
// Create agents for queues in range that we don't yet have.
// First create them and store in local queuesToAgentsMap.
// Only after that Initialize them all.
var agents = new List<PersistentStreamPullingAgent>();
foreach (var queueId in myQueues.Where(queueId => !queuesToAgentsMap.ContainsKey(queueId)))
{
try
{
var agentId = GrainId.NewSystemTargetGrainIdByTypeCode(Constants.PULLING_AGENT_SYSTEM_TARGET_TYPE_CODE);
var agent = new PersistentStreamPullingAgent(agentId, streamProviderName, providerRuntime, pubSub, queueId, config);
providerRuntime.RegisterSystemTarget(agent);
queuesToAgentsMap.Add(queueId, agent);
agents.Add(agent);
}
catch (Exception exc)
{
logger.Error(ErrorCode.PersistentStreamPullingManager_07, "Exception while creating PersistentStreamPullingAgent.", exc);
// What should we do? This error is not recoverable and considered a bug. But we don't want to bring the silo down.
// If this is when silo is starting and agent is initializing, fail the silo startup. Otherwise, just swallow to limit impact on other receivers.
if (failOnInit) throw;
}
}
try
{
var initTasks = new List<Task>();
foreach (var agent in agents)
{
initTasks.Add(InitAgent(agent));
}
await Task.WhenAll(initTasks);
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Initialize. No need to log again.
}
if (agents.Count > 0)
{
Log(ErrorCode.PersistentStreamPullingManager_08, "Added {0} new queues: {1}. Now own total of {2} queues: {3}",
agents.Count,
Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()),
NumberRunningAgents,
PrintQueues(queuesToAgentsMap.Keys));
}
}
private async Task InitAgent(PersistentStreamPullingAgent agent)
{
// Init the agent only after it was registered locally.
var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>();
var queueAdapterCacheAsImmutable = queueAdapterCache != null ? queueAdapterCache.AsImmutable() : new Immutable<IQueueAdapterCache>(null);
IStreamFailureHandler deliveryFailureHandler = await adapterFactory.GetDeliveryFailureHandler(agent.QueueId);
// Need to call it as a grain reference.
var task = OrleansTaskExtentions.SafeExecute(() => agentGrainRef.Initialize(queueAdapter.AsImmutable(), queueAdapterCacheAsImmutable, deliveryFailureHandler.AsImmutable()));
await task.LogException(logger, ErrorCode.PersistentStreamPullingManager_09, String.Format("PersistentStreamPullingAgent {0} failed to Initialize.", agent.QueueId));
}
private async Task RemoveQueues(List<QueueId> queuesToRemove)
{
if (queuesToRemove.Count == 0)
{
return;
}
// Stop the agents that for queues that are not in my range anymore.
var agents = new List<PersistentStreamPullingAgent>(queuesToRemove.Count);
Log(ErrorCode.PersistentStreamPullingManager_10, "About to remove {0} agents from my responsibility: {1}", queuesToRemove.Count, Utils.EnumerableToString(queuesToRemove, q => q.ToString()));
var removeTasks = new List<Task>();
foreach (var queueId in queuesToRemove)
{
PersistentStreamPullingAgent agent;
if (!queuesToAgentsMap.TryGetValue(queueId, out agent)) continue;
agents.Add(agent);
queuesToAgentsMap.Remove(queueId);
var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>();
var task = OrleansTaskExtentions.SafeExecute(agentGrainRef.Shutdown);
task = task.LogException(logger, ErrorCode.PersistentStreamPullingManager_11,
String.Format("PersistentStreamPullingAgent {0} failed to Shutdown.", agent.QueueId));
removeTasks.Add(task);
}
try
{
await Task.WhenAll(removeTasks);
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Shutdown. No need to log again.
}
foreach (var agent in agents)
{
try
{
providerRuntime.UnregisterSystemTarget(agent);
}
catch (Exception exc)
{
Log(ErrorCode.PersistentStreamPullingManager_12,
"Exception while UnRegisterSystemTarget of PersistentStreamPullingAgent {0}. Ignoring. Exc.Message = {1}.", ((ISystemTargetBase)agent).GrainId, exc.Message);
}
}
if (agents.Count > 0)
{
Log(ErrorCode.PersistentStreamPullingManager_10, "Removed {0} queues: {1}. Now own total of {2} queues: {3}",
agents.Count,
Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()),
NumberRunningAgents,
PrintQueues(queuesToAgentsMap.Keys));
}
}
#endregion
public async Task<object> ExecuteCommand(PersistentStreamProviderCommand command, object arg)
{
latestCommandNumber++;
int commandSeqNumber = latestCommandNumber;
try
{
Log(ErrorCode.PersistentStreamPullingManager_13,
String.Format("Got command {0}{1}: commandSeqNumber = {2}, managerState = {3}.",
command, arg != null ? " with arg " + arg : String.Empty, commandSeqNumber, managerState));
switch (command)
{
case PersistentStreamProviderCommand.StartAgents:
case PersistentStreamProviderCommand.StopAgents:
await QueueCommandForExecution(command, commandSeqNumber);
return null;
case PersistentStreamProviderCommand.GetAgentsState:
return managerState;
case PersistentStreamProviderCommand.GetNumberRunningAgents:
return NumberRunningAgents;
default:
throw new OrleansException(String.Format("PullingAgentManager does not support command {0}.", command));
}
}
finally
{
Log(ErrorCode.PersistentStreamPullingManager_15,
String.Format("Done executing command {0}: commandSeqNumber = {1}, managerState = {2}, num running agents = {3}.",
command, commandSeqNumber, managerState, NumberRunningAgents));
}
}
// Start and Stop commands are composite commands that take multiple turns.
// Ee don't wnat them to interleave with other concurrent Start/Stop commands, as well as not with QueueDistributionChangeNotification.
// Therefore, we serialize them all via the same nonReentrancyGuarantor.
private Task QueueCommandForExecution(PersistentStreamProviderCommand command, int commandSeqNumber)
{
return nonReentrancyGuarantor.AddNext(() =>
{
// skip execution of an older/previous command since already got a newer command.
if (commandSeqNumber < latestCommandNumber)
{
Log(ErrorCode.PersistentStreamPullingManager_15,
"Skipping execution of command number {0} since already received a later command (already have command number {1}).",
commandSeqNumber, latestCommandNumber);
return Task.CompletedTask;
}
switch (command)
{
case PersistentStreamProviderCommand.StartAgents:
return StartAgents();
case PersistentStreamProviderCommand.StopAgents:
return StopAgents();
default:
throw new OrleansException(String.Format("PullingAgentManager got unsupported command {0}", command));
}
});
}
private static string PrintQueues(ICollection<QueueId> myQueues)
{
return Utils.EnumerableToString(myQueues, q => q.ToString());
}
// Just print our queue assignment periodicaly, for easy monitoring.
private Task AsyncTimerCallback(object state)
{
Log(ErrorCode.PersistentStreamPullingManager_PeriodicPrint,
"I am responsible for a total of {0} queues on stream provider {1}: {2}.",
NumberRunningAgents, streamProviderName, PrintQueues(queuesToAgentsMap.Keys));
return Task.CompletedTask;
}
private void Log(ErrorCode logCode, string format, params object[] args)
{
logger.LogWithoutBulkingAndTruncating(Severity.Info, logCode, format, args);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// PRMS Order Details Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KPRMSDataSet : EduHubDataSet<KPRMS>
{
/// <inheritdoc />
public override string Name { get { return "KPRMS"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KPRMSDataSet(EduHubContext Context)
: base(Context)
{
Index_TID = new Lazy<Dictionary<int, KPRMS>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KPRMS" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KPRMS" /> fields for each CSV column header</returns>
internal override Action<KPRMS, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KPRMS, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "PRMS_ORDERNO":
mapper[i] = (e, v) => e.PRMS_ORDERNO = v;
break;
case "TRDATE":
mapper[i] = (e, v) => e.TRDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "ORDER_LINENO":
mapper[i] = (e, v) => e.ORDER_LINENO = v == null ? (short?)null : short.Parse(v);
break;
case "ORDER_DESC":
mapper[i] = (e, v) => e.ORDER_DESC = v;
break;
case "GLCODE":
mapper[i] = (e, v) => e.GLCODE = v;
break;
case "GLPROGRAM":
mapper[i] = (e, v) => e.GLPROGRAM = v;
break;
case "GLSUBPROG":
mapper[i] = (e, v) => e.GLSUBPROG = v;
break;
case "GLINIT":
mapper[i] = (e, v) => e.GLINIT = v;
break;
case "TRQTY":
mapper[i] = (e, v) => e.TRQTY = v == null ? (double?)null : double.Parse(v);
break;
case "AMOUNT":
mapper[i] = (e, v) => e.AMOUNT = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CRKEY":
mapper[i] = (e, v) => e.CRKEY = v;
break;
case "GST_CODE":
mapper[i] = (e, v) => e.GST_CODE = v;
break;
case "GST_RATE":
mapper[i] = (e, v) => e.GST_RATE = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "ABN":
mapper[i] = (e, v) => e.ABN = v;
break;
case "SCHOOL_ID":
mapper[i] = (e, v) => e.SCHOOL_ID = v;
break;
case "DELETE_FLAG":
mapper[i] = (e, v) => e.DELETE_FLAG = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KPRMS" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KPRMS" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KPRMS" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KPRMS}"/> of entities</returns>
internal override IEnumerable<KPRMS> ApplyDeltaEntities(IEnumerable<KPRMS> Entities, List<KPRMS> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, KPRMS>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find KPRMS by TID field
/// </summary>
/// <param name="TID">TID value used to find KPRMS</param>
/// <returns>Related KPRMS entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KPRMS FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find KPRMS by TID field
/// </summary>
/// <param name="TID">TID value used to find KPRMS</param>
/// <param name="Value">Related KPRMS entity</param>
/// <returns>True if the related KPRMS entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out KPRMS Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find KPRMS by TID field
/// </summary>
/// <param name="TID">TID value used to find KPRMS</param>
/// <returns>Related KPRMS entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KPRMS TryFindByTID(int TID)
{
KPRMS value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KPRMS table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KPRMS]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KPRMS](
[TID] int IDENTITY NOT NULL,
[PRMS_ORDERNO] varchar(10) NULL,
[TRDATE] datetime NULL,
[ORDER_LINENO] smallint NULL,
[ORDER_DESC] varchar(30) NULL,
[GLCODE] varchar(10) NULL,
[GLPROGRAM] varchar(3) NULL,
[GLSUBPROG] varchar(4) NULL,
[GLINIT] varchar(3) NULL,
[TRQTY] float NULL,
[AMOUNT] money NULL,
[CRKEY] varchar(10) NULL,
[GST_CODE] varchar(4) NULL,
[GST_RATE] money NULL,
[ABN] varchar(15) NULL,
[SCHOOL_ID] varchar(4) NULL,
[DELETE_FLAG] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KPRMS_Index_TID] PRIMARY KEY CLUSTERED (
[TID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KPRMSDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KPRMSDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KPRMS"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KPRMS"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KPRMS> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[KPRMS] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KPRMS data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KPRMS data set</returns>
public override EduHubDataSetDataReader<KPRMS> GetDataSetDataReader()
{
return new KPRMSDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KPRMS data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KPRMS data set</returns>
public override EduHubDataSetDataReader<KPRMS> GetDataSetDataReader(List<KPRMS> Entities)
{
return new KPRMSDataReader(new EduHubDataSetLoadedReader<KPRMS>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KPRMSDataReader : EduHubDataSetDataReader<KPRMS>
{
public KPRMSDataReader(IEduHubDataSetReader<KPRMS> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 20; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // PRMS_ORDERNO
return Current.PRMS_ORDERNO;
case 2: // TRDATE
return Current.TRDATE;
case 3: // ORDER_LINENO
return Current.ORDER_LINENO;
case 4: // ORDER_DESC
return Current.ORDER_DESC;
case 5: // GLCODE
return Current.GLCODE;
case 6: // GLPROGRAM
return Current.GLPROGRAM;
case 7: // GLSUBPROG
return Current.GLSUBPROG;
case 8: // GLINIT
return Current.GLINIT;
case 9: // TRQTY
return Current.TRQTY;
case 10: // AMOUNT
return Current.AMOUNT;
case 11: // CRKEY
return Current.CRKEY;
case 12: // GST_CODE
return Current.GST_CODE;
case 13: // GST_RATE
return Current.GST_RATE;
case 14: // ABN
return Current.ABN;
case 15: // SCHOOL_ID
return Current.SCHOOL_ID;
case 16: // DELETE_FLAG
return Current.DELETE_FLAG;
case 17: // LW_DATE
return Current.LW_DATE;
case 18: // LW_TIME
return Current.LW_TIME;
case 19: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // PRMS_ORDERNO
return Current.PRMS_ORDERNO == null;
case 2: // TRDATE
return Current.TRDATE == null;
case 3: // ORDER_LINENO
return Current.ORDER_LINENO == null;
case 4: // ORDER_DESC
return Current.ORDER_DESC == null;
case 5: // GLCODE
return Current.GLCODE == null;
case 6: // GLPROGRAM
return Current.GLPROGRAM == null;
case 7: // GLSUBPROG
return Current.GLSUBPROG == null;
case 8: // GLINIT
return Current.GLINIT == null;
case 9: // TRQTY
return Current.TRQTY == null;
case 10: // AMOUNT
return Current.AMOUNT == null;
case 11: // CRKEY
return Current.CRKEY == null;
case 12: // GST_CODE
return Current.GST_CODE == null;
case 13: // GST_RATE
return Current.GST_RATE == null;
case 14: // ABN
return Current.ABN == null;
case 15: // SCHOOL_ID
return Current.SCHOOL_ID == null;
case 16: // DELETE_FLAG
return Current.DELETE_FLAG == null;
case 17: // LW_DATE
return Current.LW_DATE == null;
case 18: // LW_TIME
return Current.LW_TIME == null;
case 19: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // PRMS_ORDERNO
return "PRMS_ORDERNO";
case 2: // TRDATE
return "TRDATE";
case 3: // ORDER_LINENO
return "ORDER_LINENO";
case 4: // ORDER_DESC
return "ORDER_DESC";
case 5: // GLCODE
return "GLCODE";
case 6: // GLPROGRAM
return "GLPROGRAM";
case 7: // GLSUBPROG
return "GLSUBPROG";
case 8: // GLINIT
return "GLINIT";
case 9: // TRQTY
return "TRQTY";
case 10: // AMOUNT
return "AMOUNT";
case 11: // CRKEY
return "CRKEY";
case 12: // GST_CODE
return "GST_CODE";
case 13: // GST_RATE
return "GST_RATE";
case 14: // ABN
return "ABN";
case 15: // SCHOOL_ID
return "SCHOOL_ID";
case 16: // DELETE_FLAG
return "DELETE_FLAG";
case 17: // LW_DATE
return "LW_DATE";
case 18: // LW_TIME
return "LW_TIME";
case 19: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "PRMS_ORDERNO":
return 1;
case "TRDATE":
return 2;
case "ORDER_LINENO":
return 3;
case "ORDER_DESC":
return 4;
case "GLCODE":
return 5;
case "GLPROGRAM":
return 6;
case "GLSUBPROG":
return 7;
case "GLINIT":
return 8;
case "TRQTY":
return 9;
case "AMOUNT":
return 10;
case "CRKEY":
return 11;
case "GST_CODE":
return 12;
case "GST_RATE":
return 13;
case "ABN":
return 14;
case "SCHOOL_ID":
return 15;
case "DELETE_FLAG":
return 16;
case "LW_DATE":
return 17;
case "LW_TIME":
return 18;
case "LW_USER":
return 19;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// 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.Config
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Xml;
using NLog.Common;
using NLog.Filters;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.LayoutRenderers;
using NLog.Time;
#if SILVERLIGHT
// ReSharper disable once RedundantUsingDirective
using System.Windows;
#endif
/// <summary>
/// A class for configuring NLog through an XML configuration file
/// (App.config style or App.nlog style).
/// </summary>
public class XmlLoggingConfiguration : LoggingConfiguration
{
#region private fields
private readonly ConfigurationItemFactory configurationItemFactory = ConfigurationItemFactory.Default;
private readonly Dictionary<string, bool> visitedFile = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private string originalFileName;
#endregion
#region contructors
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
public XmlLoggingConfiguration(string fileName)
{
using (XmlReader reader = XmlReader.Create(fileName))
{
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(string fileName, bool ignoreErrors)
{
using (XmlReader reader = XmlReader.Create(fileName))
{
this.Initialize(reader, fileName, ignoreErrors);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName)
{
this.Initialize(reader, fileName, false);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors)
{
this.Initialize(reader, fileName, ignoreErrors);
}
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
/// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, ignoreErrors);
}
}
#endif
#endregion
#region public properties
#if !SILVERLIGHT
/// <summary>
/// Gets the default <see cref="LoggingConfiguration" /> object by parsing
/// the application configuration file (<c>app.exe.config</c>).
/// </summary>
public static LoggingConfiguration AppConfig
{
get
{
object o = System.Configuration.ConfigurationManager.GetSection("nlog");
return o as LoggingConfiguration;
}
}
#endif
/// <summary>
/// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet.
/// </summary>
public bool? InitializeSucceeded { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the configuration files
/// should be watched for changes and reloaded automatically when changed.
/// </summary>
public bool AutoReload { get; set; }
/// <summary>
/// Gets the collection of file names which should be watched for changes by NLog.
/// This is the list of configuration files processed.
/// If the <c>autoReload</c> attribute is not set it returns empty collection.
/// </summary>
public override IEnumerable<string> FileNamesToWatch
{
get
{
if (this.AutoReload)
{
return this.visitedFile.Keys;
}
return new string[0];
}
}
#endregion
#region public methods
/// <summary>
/// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object.
/// </summary>
/// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns>
public override LoggingConfiguration Reload()
{
return new XmlLoggingConfiguration(this.originalFileName);
}
#endregion
private static bool IsTargetElement(string name)
{
return name.Equals("target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetRefElement(string name)
{
return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Remove all spaces, also in between text.
/// </summary>
/// <param name="s">text</param>
/// <returns>text without spaces</returns>
/// <remarks>Tabs and other whitespace is not removed!</remarks>
private static string CleanSpaces(string s)
{
s = s.Replace(" ", string.Empty); // get rid of the whitespace
return s;
}
/// <summary>
/// Remove the namespace (before :)
/// </summary>
/// <example>
/// x:a, will be a
/// </example>
/// <param name="attributeValue"></param>
/// <returns></returns>
private static string StripOptionalNamespacePrefix(string attributeValue)
{
if (attributeValue == null)
{
return null;
}
int p = attributeValue.IndexOf(':');
if (p < 0)
{
return attributeValue;
}
return attributeValue.Substring(p + 1);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
private static Target WrapWithAsyncTargetWrapper(Target target)
{
var asyncTargetWrapper = new AsyncTargetWrapper();
asyncTargetWrapper.WrappedTarget = target;
asyncTargetWrapper.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name);
target = asyncTargetWrapper;
return target;
}
/// <summary>
/// Initializes the configuration.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
{
try
{
InitializeSucceeded = null;
reader.MoveToContent();
var content = new NLogXmlElement(reader);
if (fileName != null)
{
#if SILVERLIGHT
string key = fileName;
#else
string key = Path.GetFullPath(fileName);
#endif
this.visitedFile[key] = true;
this.originalFileName = fileName;
this.ParseTopLevel(content, Path.GetDirectoryName(fileName));
InternalLogger.Info("Configured from an XML element in {0}...", fileName);
}
else
{
this.ParseTopLevel(content, null);
}
InitializeSucceeded = true;
}
catch (Exception exception)
{
InitializeSucceeded = false;
if (exception.MustBeRethrown())
{
throw;
}
NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
if (!ignoreErrors)
{
if (LogManager.ThrowExceptions)
{
throw ConfigException;
}
else
{
InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
}
}
else
{
InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
}
}
}
private void ConfigureFromFile(string fileName)
{
#if SILVERLIGHT
// file names are relative to XAP
string key = fileName;
#else
string key = Path.GetFullPath(fileName);
#endif
if (this.visitedFile.ContainsKey(key))
{
return;
}
this.visitedFile[key] = true;
this.ParseTopLevel(new NLogXmlElement(fileName), Path.GetDirectoryName(fileName));
}
#region parse methods
/// <summary>
/// Parse the root
/// </summary>
/// <param name="content"></param>
/// <param name="baseDirectory">path to directory of config file.</param>
private void ParseTopLevel(NLogXmlElement content, string baseDirectory)
{
content.AssertName("nlog", "configuration");
switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "CONFIGURATION":
this.ParseConfigurationElement(content, baseDirectory);
break;
case "NLOG":
this.ParseNLogElement(content, baseDirectory);
break;
}
}
/// <summary>
/// Parse {configuration} xml element.
/// </summary>
/// <param name="configurationElement"></param>
/// <param name="baseDirectory">path to directory of config file.</param>
private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory)
{
InternalLogger.Trace("ParseConfigurationElement");
configurationElement.AssertName("configuration");
foreach (var el in configurationElement.Elements("nlog"))
{
this.ParseNLogElement(el, baseDirectory);
}
}
/// <summary>
/// Parse {NLog} xml element.
/// </summary>
/// <param name="nlogElement"></param>
/// <param name="baseDirectory">path to directory of config file.</param>
private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory)
{
InternalLogger.Trace("ParseNLogElement");
nlogElement.AssertName("nlog");
if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false))
{
this.DefaultCultureInfo = CultureInfo.InvariantCulture;
}
#pragma warning disable 618
this.ExceptionLoggingOldStyle = nlogElement.GetOptionalBooleanAttribute("exceptionLoggingOldStyle", false);
#pragma warning restore 618
this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false);
LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions);
InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);
InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));
LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name));
var children = nlogElement.Children;
//first load the extensions, as the can be used in other elements (targets etc)
var extensionsChilds = children.Where(child => child.LocalName.Equals("EXTENSIONS", StringComparison.InvariantCultureIgnoreCase));
foreach (var extensionsChild in extensionsChilds)
{
this.ParseExtensionsElement(extensionsChild, baseDirectory);
}
//parse all other direct elements
foreach (var child in children)
{
switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "EXTENSIONS":
//already parsed
break;
case "INCLUDE":
this.ParseIncludeElement(child, baseDirectory);
break;
case "APPENDERS":
case "TARGETS":
this.ParseTargetsElement(child);
break;
case "VARIABLE":
this.ParseVariableElement(child);
break;
case "RULES":
this.ParseRulesElement(child, this.LoggingRules);
break;
case "TIME":
this.ParseTimeElement(child);
break;
default:
InternalLogger.Warn("Skipping unknown node: {0}", child.LocalName);
break;
}
}
}
/// <summary>
/// Parse {Rules} xml element
/// </summary>
/// <param name="rulesElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection)
{
InternalLogger.Trace("ParseRulesElement");
rulesElement.AssertName("rules");
foreach (var loggerElement in rulesElement.Elements("logger"))
{
this.ParseLoggerElement(loggerElement, rulesCollection);
}
}
/// <summary>
/// Parse {Logger} xml element
/// </summary>
/// <param name="loggerElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection)
{
loggerElement.AssertName("logger");
var namePattern = loggerElement.GetOptionalAttribute("name", "*");
var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true);
if (!enabled)
{
InternalLogger.Debug("The logger named '{0}' are disabled");
return;
}
var rule = new LoggingRule();
string appendTo = loggerElement.GetOptionalAttribute("appendTo", null);
if (appendTo == null)
{
appendTo = loggerElement.GetOptionalAttribute("writeTo", null);
}
rule.LoggerNamePattern = namePattern;
if (appendTo != null)
{
foreach (string t in appendTo.Split(','))
{
string targetName = t.Trim();
Target target = FindTargetByName(targetName);
if (target != null)
{
rule.Targets.Add(target);
}
else
{
throw new NLogConfigurationException("Target " + targetName + " not found.");
}
}
}
rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false);
string levelString;
if (loggerElement.AttributeValues.TryGetValue("level", out levelString))
{
LogLevel level = LogLevel.FromString(levelString);
rule.EnableLoggingForLevel(level);
}
else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString))
{
levelString = CleanSpaces(levelString);
string[] tokens = levelString.Split(',');
foreach (string s in tokens)
{
if (!string.IsNullOrEmpty(s))
{
LogLevel level = LogLevel.FromString(s);
rule.EnableLoggingForLevel(level);
}
}
}
else
{
int minLevel = 0;
int maxLevel = LogLevel.MaxLevel.Ordinal;
string minLevelString;
string maxLevelString;
if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString))
{
minLevel = LogLevel.FromString(minLevelString).Ordinal;
}
if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString))
{
maxLevel = LogLevel.FromString(maxLevelString).Ordinal;
}
for (int i = minLevel; i <= maxLevel; ++i)
{
rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
foreach (var child in loggerElement.Children)
{
switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "FILTERS":
this.ParseFilters(rule, child);
break;
case "LOGGER":
this.ParseLoggerElement(child, rule.ChildRules);
break;
}
}
rulesCollection.Add(rule);
}
private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement)
{
filtersElement.AssertName("filters");
foreach (var filterElement in filtersElement.Children)
{
string name = filterElement.LocalName;
Filter filter = this.configurationItemFactory.Filters.CreateInstance(name);
this.ConfigureObjectFromAttributes(filter, filterElement, false);
rule.Filters.Add(filter);
}
}
private void ParseVariableElement(NLogXmlElement variableElement)
{
variableElement.AssertName("variable");
string name = variableElement.GetRequiredAttribute("name");
string value = this.ExpandSimpleVariables(variableElement.GetRequiredAttribute("value"));
this.Variables[name] = value;
}
private void ParseTargetsElement(NLogXmlElement targetsElement)
{
targetsElement.AssertName("targets", "appenders");
bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false);
NLogXmlElement defaultWrapperElement = null;
var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>();
foreach (var targetElement in targetsElement.Children)
{
string name = targetElement.LocalName;
string type = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null));
switch (name.ToUpper(CultureInfo.InvariantCulture))
{
case "DEFAULT-WRAPPER":
defaultWrapperElement = targetElement;
break;
case "DEFAULT-TARGET-PARAMETERS":
if (type == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
typeNameToDefaultTargetParameters[type] = targetElement;
break;
case "TARGET":
case "APPENDER":
case "WRAPPER":
case "WRAPPER-TARGET":
case "COMPOUND-TARGET":
if (type == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
NLogXmlElement defaults;
if (typeNameToDefaultTargetParameters.TryGetValue(type, out defaults))
{
this.ParseTargetElement(newTarget, defaults);
}
this.ParseTargetElement(newTarget, targetElement);
if (asyncWrap)
{
newTarget = WrapWithAsyncTargetWrapper(newTarget);
}
if (defaultWrapperElement != null)
{
newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
}
InternalLogger.Info("Adding target {0}", newTarget);
AddTarget(newTarget.Name, newTarget);
break;
}
}
}
private void ParseTargetElement(Target target, NLogXmlElement targetElement)
{
var compound = target as CompoundTargetBase;
var wrapper = target as WrapperTargetBase;
this.ConfigureObjectFromAttributes(target, targetElement, true);
foreach (var childElement in targetElement.Children)
{
string name = childElement.LocalName;
if (compound != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
compound.Targets.Add(newTarget);
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
compound.Targets.Add(newTarget);
}
continue;
}
}
if (wrapper != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
wrapper.WrappedTarget = newTarget;
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
if (wrapper.WrappedTarget != null)
{
throw new NLogConfigurationException("Wrapped target already defined.");
}
wrapper.WrappedTarget = newTarget;
}
continue;
}
}
this.SetPropertyFromElement(target, childElement);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")]
private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
{
extensionsElement.AssertName("extensions");
foreach (var addElement in extensionsElement.Elements("add"))
{
string prefix = addElement.GetOptionalAttribute("prefix", null);
if (prefix != null)
{
prefix = prefix + ".";
}
string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null));
if (type != null)
{
this.configurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
}
string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null);
if (assemblyFile != null)
{
try
{
#if SILVERLIGHT
var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
string fullFileName = Path.Combine(baseDirectory, assemblyFile);
InternalLogger.Info("Loading assembly file: {0}", fullFileName);
Assembly asm = Assembly.LoadFrom(fullFileName);
#endif
this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error loading extensions: {0}", exception);
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
}
}
continue;
}
string assemblyName = addElement.GetOptionalAttribute("assembly", null);
if (assemblyName != null)
{
try
{
InternalLogger.Info("Loading assembly name: {0}", assemblyName);
#if SILVERLIGHT
var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
Assembly asm = Assembly.Load(assemblyName);
#endif
this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error loading extensions: {0}", exception);
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
}
}
continue;
}
}
}
private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory)
{
includeElement.AssertName("include");
string newFileName = includeElement.GetRequiredAttribute("file");
try
{
newFileName = this.ExpandSimpleVariables(newFileName);
newFileName = SimpleLayout.Evaluate(newFileName);
if (baseDirectory != null)
{
newFileName = Path.Combine(baseDirectory, newFileName);
}
#if SILVERLIGHT
newFileName = newFileName.Replace("\\", "/");
if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null)
#else
if (File.Exists(newFileName))
#endif
{
InternalLogger.Debug("Including file '{0}'", newFileName);
this.ConfigureFromFile(newFileName);
}
else
{
throw new FileNotFoundException("Included file not found: " + newFileName);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception);
if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false))
{
return;
}
throw new NLogConfigurationException("Error when including: " + newFileName, exception);
}
}
private void ParseTimeElement(NLogXmlElement timeElement)
{
timeElement.AssertName("time");
string type = timeElement.GetRequiredAttribute("type");
TimeSource newTimeSource = this.configurationItemFactory.TimeSources.CreateInstance(type);
this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true);
InternalLogger.Info("Selecting time source {0}", newTimeSource);
TimeSource.Current = newTimeSource;
}
#endregion
private void SetPropertyFromElement(object o, NLogXmlElement element)
{
if (this.AddArrayItemFromElement(o, element))
{
return;
}
if (this.SetLayoutFromElement(o, element))
{
return;
}
PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandSimpleVariables(element.Value), this.configurationItemFactory);
}
private bool AddArrayItemFromElement(object o, NLogXmlElement element)
{
string name = element.LocalName;
PropertyInfo propInfo;
if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
{
return false;
}
Type elementType = PropertyHelper.GetArrayItemType(propInfo);
if (elementType != null)
{
IList propertyValue = (IList)propInfo.GetValue(o, null);
object arrayItem = FactoryHelper.CreateInstance(elementType);
this.ConfigureObjectFromAttributes(arrayItem, element, true);
this.ConfigureObjectFromElement(arrayItem, element);
propertyValue.Add(arrayItem);
return true;
}
return false;
}
private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType)
{
foreach (var kvp in element.AttributeValues)
{
string childName = kvp.Key;
string childValue = kvp.Value;
if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase))
{
continue;
}
PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandSimpleVariables(childValue), this.configurationItemFactory);
}
}
private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement)
{
PropertyInfo targetPropertyInfo;
string name = layoutElement.LocalName;
// if property exists
if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo))
{
// and is a Layout
if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType))
{
string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null));
// and 'type' attribute has been specified
if (layoutTypeName != null)
{
// configure it from current element
Layout layout = this.configurationItemFactory.Layouts.CreateInstance(this.ExpandSimpleVariables(layoutTypeName));
this.ConfigureObjectFromAttributes(layout, layoutElement, true);
this.ConfigureObjectFromElement(layout, layoutElement);
targetPropertyInfo.SetValue(o, layout, null);
return true;
}
}
}
return false;
}
private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element)
{
foreach (var child in element.Children)
{
this.SetPropertyFromElement(targetObject, child);
}
}
private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters)
{
string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type"));
Target wrapperTargetInstance = this.configurationItemFactory.Targets.CreateInstance(wrapperType);
WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
}
this.ParseTargetElement(wrapperTargetInstance, defaultParameters);
while (wtb.WrappedTarget != null)
{
wtb = wtb.WrappedTarget as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper.");
}
}
wtb.WrappedTarget = t;
wrapperTargetInstance.Name = t.Name;
t.Name = t.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name);
return wrapperTargetInstance;
}
/// <summary>
/// Replace a simple variable with a value. The orginal value is removed and thus we cannot redo this in a later stage.
///
/// Use for that: <see cref="VariableLayoutRenderer"/>
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private string ExpandSimpleVariables(string input)
{
string output = input;
// TODO - make this case-insensitive, will probably require a different approach
foreach (var kvp in this.Variables)
{
var layout = kvp.Value;
//this value is set from xml and that's a string. Because of that, we can use SimpleLayout here.
if (layout != null) output = output.Replace("${" + kvp.Key + "}", layout.OriginalText);
}
return output;
}
}
}
| |
using System.Collections;
using System.Globalization;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Iana;
using Org.BouncyCastle.Asn1.Kisa;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Ntt;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
namespace Org.BouncyCastle.Security
{
public sealed class GeneratorUtilities
{
private GeneratorUtilities()
{
}
private static readonly Hashtable kgAlgorithms = new Hashtable();
private static readonly Hashtable kpgAlgorithms = new Hashtable();
static GeneratorUtilities()
{
//
// key generators.
//
AddKgAlgorithm("AES",
"AESWRAP");
AddKgAlgorithm("AES128",
"2.16.840.1.101.3.4.2",
NistObjectIdentifiers.IdAes128Cbc,
NistObjectIdentifiers.IdAes128Cfb,
NistObjectIdentifiers.IdAes128Ecb,
NistObjectIdentifiers.IdAes128Ofb,
NistObjectIdentifiers.IdAes128Wrap);
AddKgAlgorithm("AES192",
"2.16.840.1.101.3.4.22",
NistObjectIdentifiers.IdAes192Cbc,
NistObjectIdentifiers.IdAes192Cfb,
NistObjectIdentifiers.IdAes192Ecb,
NistObjectIdentifiers.IdAes192Ofb,
NistObjectIdentifiers.IdAes192Wrap);
AddKgAlgorithm("AES256",
"2.16.840.1.101.3.4.42",
NistObjectIdentifiers.IdAes256Cbc,
NistObjectIdentifiers.IdAes256Cfb,
NistObjectIdentifiers.IdAes256Ecb,
NistObjectIdentifiers.IdAes256Ofb,
NistObjectIdentifiers.IdAes256Wrap);
AddKgAlgorithm("BLOWFISH",
"1.3.6.1.4.1.3029.1.2");
AddKgAlgorithm("CAMELLIA",
"CAMELLIAWRAP");
AddKgAlgorithm("CAMELLIA128",
NttObjectIdentifiers.IdCamellia128Cbc,
NttObjectIdentifiers.IdCamellia128Wrap);
AddKgAlgorithm("CAMELLIA192",
NttObjectIdentifiers.IdCamellia192Cbc,
NttObjectIdentifiers.IdCamellia192Wrap);
AddKgAlgorithm("CAMELLIA256",
NttObjectIdentifiers.IdCamellia256Cbc,
NttObjectIdentifiers.IdCamellia256Wrap);
AddKgAlgorithm("CAST5",
"1.2.840.113533.7.66.10");
AddKgAlgorithm("CAST6");
AddKgAlgorithm("DES",
OiwObjectIdentifiers.DesCbc,
OiwObjectIdentifiers.DesCfb,
OiwObjectIdentifiers.DesEcb,
OiwObjectIdentifiers.DesOfb);
AddKgAlgorithm("DESEDE",
"DESEDEWRAP",
OiwObjectIdentifiers.DesEde,
PkcsObjectIdentifiers.IdAlgCms3DesWrap);
AddKgAlgorithm("DESEDE3",
PkcsObjectIdentifiers.DesEde3Cbc);
AddKgAlgorithm("GOST28147",
"GOST",
"GOST-28147",
CryptoProObjectIdentifiers.GostR28147Cbc);
AddKgAlgorithm("HC128");
AddKgAlgorithm("HC256");
AddKgAlgorithm("IDEA",
"1.3.6.1.4.1.188.7.1.1.2");
AddKgAlgorithm("NOEKEON");
AddKgAlgorithm("RC2",
PkcsObjectIdentifiers.RC2Cbc,
PkcsObjectIdentifiers.IdAlgCmsRC2Wrap);
AddKgAlgorithm("RC4",
"ARC4",
"1.2.840.113549.3.4");
AddKgAlgorithm("RC5",
"RC5-32");
AddKgAlgorithm("RC5-64");
AddKgAlgorithm("RC6");
AddKgAlgorithm("RIJNDAEL");
AddKgAlgorithm("SALSA20");
AddKgAlgorithm("SEED",
KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap,
KisaObjectIdentifiers.IdSeedCbc);
AddKgAlgorithm("SERPENT");
AddKgAlgorithm("SKIPJACK");
AddKgAlgorithm("TEA");
AddKgAlgorithm("TWOFISH");
AddKgAlgorithm("VMPC");
AddKgAlgorithm("VMPC-KSA3");
AddKgAlgorithm("XTEA");
//
// HMac key generators
//
AddHMacKeyGenerator("MD2");
AddHMacKeyGenerator("MD4");
AddHMacKeyGenerator("MD5",
IanaObjectIdentifiers.HmacMD5);
AddHMacKeyGenerator("SHA1",
PkcsObjectIdentifiers.IdHmacWithSha1,
IanaObjectIdentifiers.HmacSha1);
AddHMacKeyGenerator("SHA224",
PkcsObjectIdentifiers.IdHmacWithSha224);
AddHMacKeyGenerator("SHA256",
PkcsObjectIdentifiers.IdHmacWithSha256);
AddHMacKeyGenerator("SHA384",
PkcsObjectIdentifiers.IdHmacWithSha384);
AddHMacKeyGenerator("SHA512",
PkcsObjectIdentifiers.IdHmacWithSha512);
AddHMacKeyGenerator("RIPEMD128");
AddHMacKeyGenerator("RIPEMD160",
IanaObjectIdentifiers.HmacRipeMD160);
AddHMacKeyGenerator("TIGER",
IanaObjectIdentifiers.HmacTiger);
//
// key pair generators.
//
AddKpgAlgorithm("DH",
"DIFFIEHELLMAN");
AddKpgAlgorithm("DSA");
AddKpgAlgorithm("EC");
AddKpgAlgorithm("ECDH",
"ECIES");
AddKpgAlgorithm("ECDHC");
AddKpgAlgorithm("ECDSA");
AddKpgAlgorithm("ECGOST3410",
"ECGOST-3410",
"GOST-3410-2001");
AddKpgAlgorithm("ELGAMAL");
AddKpgAlgorithm("GOST3410",
"GOST-3410",
"GOST-3410-94");
AddKpgAlgorithm("RSA",
"1.2.840.113549.1.1.1");
}
private static void AddKgAlgorithm(
string canonicalName,
params object[] aliases)
{
kgAlgorithms[canonicalName] = canonicalName;
foreach (object alias in aliases)
{
kgAlgorithms[alias.ToString()] = canonicalName;
}
}
private static void AddKpgAlgorithm(
string canonicalName,
params object[] aliases)
{
kpgAlgorithms[canonicalName] = canonicalName;
foreach (object alias in aliases)
{
kpgAlgorithms[alias.ToString()] = canonicalName;
}
}
private static void AddHMacKeyGenerator(
string algorithm,
params object[] aliases)
{
string mainName = "HMAC" + algorithm;
kgAlgorithms[mainName] = mainName;
kgAlgorithms["HMAC-" + algorithm] = mainName;
kgAlgorithms["HMAC/" + algorithm] = mainName;
foreach (object alias in aliases)
{
kgAlgorithms[alias.ToString()] = mainName;
}
}
// TODO Consider making this public
internal static string GetCanonicalKeyGeneratorAlgorithm(
string algorithm)
{
return (string) kgAlgorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];
}
// TODO Consider making this public
internal static string GetCanonicalKeyPairGeneratorAlgorithm(
string algorithm)
{
return (string) kpgAlgorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];
}
public static CipherKeyGenerator GetKeyGenerator(
DerObjectIdentifier oid)
{
return GetKeyGenerator(oid.Id);
}
public static CipherKeyGenerator GetKeyGenerator(
string algorithm)
{
string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm);
if (canonicalName == null)
throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised.");
int defaultKeySize = FindDefaultKeySize(canonicalName);
if (defaultKeySize == -1)
throw new SecurityUtilityException("KeyGenerator " + algorithm
+ " (" + canonicalName + ") not supported.");
switch (canonicalName)
{
case "DES":
return new DesKeyGenerator(defaultKeySize);
case "DESEDE":
case "DESEDE3":
return new DesEdeKeyGenerator(defaultKeySize);
default:
return new CipherKeyGenerator(defaultKeySize);
}
}
public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(
DerObjectIdentifier oid)
{
return GetKeyPairGenerator(oid.Id);
}
public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(
string algorithm)
{
string canonicalName = GetCanonicalKeyPairGeneratorAlgorithm(algorithm);
if (canonicalName == null)
throw new SecurityUtilityException("KeyPairGenerator " + algorithm + " not recognised.");
switch (canonicalName)
{
case "DH":
return new DHKeyPairGenerator();
case "DSA":
return new DsaKeyPairGenerator();
case "EC":
case "ECDH":
case "ECDHC":
case "ECDSA":
case "ECGOST3410":
return new ECKeyPairGenerator(canonicalName);
case "ELGAMAL":
return new ElGamalKeyPairGenerator();
case "GOST3410":
return new Gost3410KeyPairGenerator();
case "RSA":
return new RsaKeyPairGenerator();
default:
break;
}
throw new SecurityUtilityException("KeyPairGenerator " + algorithm
+ " (" + canonicalName + ") not supported.");
}
internal static int GetDefaultKeySize(
DerObjectIdentifier oid)
{
return GetDefaultKeySize(oid.Id);
}
internal static int GetDefaultKeySize(
string algorithm)
{
string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm);
if (canonicalName == null)
throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised.");
int defaultKeySize = FindDefaultKeySize(canonicalName);
if (defaultKeySize == -1)
throw new SecurityUtilityException("KeyGenerator " + algorithm
+ " (" + canonicalName + ") not supported.");
return defaultKeySize;
}
private static int FindDefaultKeySize(
string canonicalName)
{
switch (canonicalName)
{
case "DES":
return 64;
case "SKIPJACK":
return 80;
case "AES128":
case "BLOWFISH":
case "CAMELLIA128":
case "CAST5":
case "DESEDE":
case "HC128":
case "HMACMD2":
case "HMACMD4":
case "HMACMD5":
case "HMACRIPEMD128":
case "IDEA":
case "NOEKEON":
case "RC2":
case "RC4":
case "RC5":
case "SALSA20":
case "SEED":
case "TEA":
case "XTEA":
case "VMPC":
case "VMPC-KSA3":
return 128;
case "HMACRIPEMD160":
case "HMACSHA1":
return 160;
case "AES":
case "AES192":
case "CAMELLIA192":
case "DESEDE3":
case "HMACTIGER":
case "RIJNDAEL":
case "SERPENT":
return 192;
case "HMACSHA224":
return 224;
case "AES256":
case "CAMELLIA":
case "CAMELLIA256":
case "CAST6":
case "GOST28147":
case "HC256":
case "HMACSHA256":
case "RC5-64":
case "RC6":
case "TWOFISH":
return 256;
case "HMACSHA384":
return 384;
case "HMACSHA512":
return 512;
default:
return -1;
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// InputManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
#endregion
namespace RolePlaying
{
/// <summary>
/// This class handles all keyboard and gamepad actions in the game.
/// </summary>
public static class InputManager
{
#region Action Enumeration
/// <summary>
/// The actions that are possible within the game.
/// </summary>
public enum Action
{
MainMenu,
Ok,
Back,
CharacterManagement,
ExitGame,
TakeView,
DropUnEquip,
MoveCharacterUp,
MoveCharacterDown,
MoveCharacterLeft,
MoveCharacterRight,
CursorUp,
CursorDown,
DecreaseAmount,
IncreaseAmount,
PageLeft,
PageRight,
TargetUp,
TargetDown,
ActiveCharacterLeft,
ActiveCharacterRight,
TotalActionCount,
}
/// <summary>
/// Readable names of each action.
/// </summary>
private static readonly string[] actionNames =
{
"Main Menu",
"Ok",
"Back",
"Character Management",
"Exit Game",
"Take / View",
"Drop / Unequip",
"Move Character - Up",
"Move Character - Down",
"Move Character - Left",
"Move Character - Right",
"Move Cursor - Up",
"Move Cursor - Down",
"Decrease Amount",
"Increase Amount",
"Page Screen Left",
"Page Screen Right",
"Select Target -Up",
"Select Target - Down",
"Select Active Character - Left",
"Select Active Character - Right",
};
/// <summary>
/// Returns the readable name of the given action.
/// </summary>
public static string GetActionName(Action action)
{
int index = (int)action;
if ((index < 0) || (index > actionNames.Length))
{
throw new ArgumentException("action");
}
return actionNames[index];
}
#endregion
#region Support Types
/// <summary>
/// GamePad controls expressed as one type, unified with button semantics.
/// </summary>
public enum GamePadButtons
{
Start,
Back,
A,
B,
X,
Y,
Up,
Down,
Left,
Right,
LeftShoulder,
RightShoulder,
LeftTrigger,
RightTrigger,
}
/// <summary>
/// A combination of gamepad and keyboard keys mapped to a particular action.
/// </summary>
public class ActionMap
{
/// <summary>
/// List of GamePad controls to be mapped to a given action.
/// </summary>
public List<GamePadButtons> gamePadButtons = new List<GamePadButtons>();
/// <summary>
/// List of Keyboard controls to be mapped to a given action.
/// </summary>
public List<Keys> keyboardKeys = new List<Keys>();
}
#endregion
#region Constants
/// <summary>
/// The value of an analog control that reads as a "pressed button".
/// </summary>
const float analogLimit = 0.5f;
#endregion
#region Keyboard Data
/// <summary>
/// The state of the keyboard as of the last update.
/// </summary>
private static KeyboardState currentKeyboardState;
/// <summary>
/// The state of the keyboard as of the last update.
/// </summary>
public static KeyboardState CurrentKeyboardState
{
get { return currentKeyboardState; }
}
/// <summary>
/// The state of the keyboard as of the previous update.
/// </summary>
private static KeyboardState previousKeyboardState;
/// <summary>
/// Check if a key is pressed.
/// </summary>
public static bool IsKeyPressed(Keys key)
{
return currentKeyboardState.IsKeyDown(key);
}
/// <summary>
/// Check if a key was just pressed in the most recent update.
/// </summary>
public static bool IsKeyTriggered(Keys key)
{
return (currentKeyboardState.IsKeyDown(key)) &&
(!previousKeyboardState.IsKeyDown(key));
}
#endregion
#region GamePad Data
/// <summary>
/// The state of the gamepad as of the last update.
/// </summary>
private static GamePadState currentGamePadState;
/// <summary>
/// The state of the gamepad as of the last update.
/// </summary>
public static GamePadState CurrentGamePadState
{
get { return currentGamePadState; }
}
/// <summary>
/// The state of the gamepad as of the previous update.
/// </summary>
private static GamePadState previousGamePadState;
#region GamePadButton Pressed Queries
/// <summary>
/// Check if the gamepad's Start button is pressed.
/// </summary>
public static bool IsGamePadStartPressed()
{
return (currentGamePadState.Buttons.Start == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's Back button is pressed.
/// </summary>
public static bool IsGamePadBackPressed()
{
return (currentGamePadState.Buttons.Back == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's A button is pressed.
/// </summary>
public static bool IsGamePadAPressed()
{
return (currentGamePadState.Buttons.A == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's B button is pressed.
/// </summary>
public static bool IsGamePadBPressed()
{
return (currentGamePadState.Buttons.B == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's X button is pressed.
/// </summary>
public static bool IsGamePadXPressed()
{
return (currentGamePadState.Buttons.X == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's Y button is pressed.
/// </summary>
public static bool IsGamePadYPressed()
{
return (currentGamePadState.Buttons.Y == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's LeftShoulder button is pressed.
/// </summary>
public static bool IsGamePadLeftShoulderPressed()
{
return (currentGamePadState.Buttons.LeftShoulder == ButtonState.Pressed);
}
/// <summary>
/// <summary>
/// Check if the gamepad's RightShoulder button is pressed.
/// </summary>
public static bool IsGamePadRightShoulderPressed()
{
return (currentGamePadState.Buttons.RightShoulder == ButtonState.Pressed);
}
/// <summary>
/// Check if Up on the gamepad's directional pad is pressed.
/// </summary>
public static bool IsGamePadDPadUpPressed()
{
return (currentGamePadState.DPad.Up == ButtonState.Pressed);
}
/// <summary>
/// Check if Down on the gamepad's directional pad is pressed.
/// </summary>
public static bool IsGamePadDPadDownPressed()
{
return (currentGamePadState.DPad.Down == ButtonState.Pressed);
}
/// <summary>
/// Check if Left on the gamepad's directional pad is pressed.
/// </summary>
public static bool IsGamePadDPadLeftPressed()
{
return (currentGamePadState.DPad.Left == ButtonState.Pressed);
}
/// <summary>
/// Check if Right on the gamepad's directional pad is pressed.
/// </summary>
public static bool IsGamePadDPadRightPressed()
{
return (currentGamePadState.DPad.Right == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's left trigger is pressed.
/// </summary>
public static bool IsGamePadLeftTriggerPressed()
{
return (currentGamePadState.Triggers.Left > analogLimit);
}
/// <summary>
/// Check if the gamepad's right trigger is pressed.
/// </summary>
public static bool IsGamePadRightTriggerPressed()
{
return (currentGamePadState.Triggers.Right > analogLimit);
}
/// <summary>
/// Check if Up on the gamepad's left analog stick is pressed.
/// </summary>
public static bool IsGamePadLeftStickUpPressed()
{
return (currentGamePadState.ThumbSticks.Left.Y > analogLimit);
}
/// <summary>
/// Check if Down on the gamepad's left analog stick is pressed.
/// </summary>
public static bool IsGamePadLeftStickDownPressed()
{
return (-1f * currentGamePadState.ThumbSticks.Left.Y > analogLimit);
}
/// <summary>
/// Check if Left on the gamepad's left analog stick is pressed.
/// </summary>
public static bool IsGamePadLeftStickLeftPressed()
{
return (-1f * currentGamePadState.ThumbSticks.Left.X > analogLimit);
}
/// <summary>
/// Check if Right on the gamepad's left analog stick is pressed.
/// </summary>
public static bool IsGamePadLeftStickRightPressed()
{
return (currentGamePadState.ThumbSticks.Left.X > analogLimit);
}
/// <summary>
/// Check if the GamePadKey value specified is pressed.
/// </summary>
private static bool IsGamePadButtonPressed(GamePadButtons gamePadKey)
{
switch (gamePadKey)
{
case GamePadButtons.Start:
return IsGamePadStartPressed();
case GamePadButtons.Back:
return IsGamePadBackPressed();
case GamePadButtons.A:
return IsGamePadAPressed();
case GamePadButtons.B:
return IsGamePadBPressed();
case GamePadButtons.X:
return IsGamePadXPressed();
case GamePadButtons.Y:
return IsGamePadYPressed();
case GamePadButtons.LeftShoulder:
return IsGamePadLeftShoulderPressed();
case GamePadButtons.RightShoulder:
return IsGamePadRightShoulderPressed();
case GamePadButtons.LeftTrigger:
return IsGamePadLeftTriggerPressed();
case GamePadButtons.RightTrigger:
return IsGamePadRightTriggerPressed();
case GamePadButtons.Up:
return IsGamePadDPadUpPressed() ||
IsGamePadLeftStickUpPressed();
case GamePadButtons.Down:
return IsGamePadDPadDownPressed() ||
IsGamePadLeftStickDownPressed();
case GamePadButtons.Left:
return IsGamePadDPadLeftPressed() ||
IsGamePadLeftStickLeftPressed();
case GamePadButtons.Right:
return IsGamePadDPadRightPressed() ||
IsGamePadLeftStickRightPressed();
}
return false;
}
#endregion
#region GamePadButton Triggered Queries
/// <summary>
/// Check if the gamepad's Start button was just pressed.
/// </summary>
public static bool IsGamePadStartTriggered()
{
return ((currentGamePadState.Buttons.Start == ButtonState.Pressed) &&
(previousGamePadState.Buttons.Start == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's Back button was just pressed.
/// </summary>
public static bool IsGamePadBackTriggered()
{
return ((currentGamePadState.Buttons.Back == ButtonState.Pressed) &&
(previousGamePadState.Buttons.Back == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's A button was just pressed.
/// </summary>
public static bool IsGamePadATriggered()
{
return ((currentGamePadState.Buttons.A == ButtonState.Pressed) &&
(previousGamePadState.Buttons.A == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's B button was just pressed.
/// </summary>
public static bool IsGamePadBTriggered()
{
return ((currentGamePadState.Buttons.B == ButtonState.Pressed) &&
(previousGamePadState.Buttons.B == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's X button was just pressed.
/// </summary>
public static bool IsGamePadXTriggered()
{
return ((currentGamePadState.Buttons.X == ButtonState.Pressed) &&
(previousGamePadState.Buttons.X == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's Y button was just pressed.
/// </summary>
public static bool IsGamePadYTriggered()
{
return ((currentGamePadState.Buttons.Y == ButtonState.Pressed) &&
(previousGamePadState.Buttons.Y == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's LeftShoulder button was just pressed.
/// </summary>
public static bool IsGamePadLeftShoulderTriggered()
{
return (
(currentGamePadState.Buttons.LeftShoulder == ButtonState.Pressed) &&
(previousGamePadState.Buttons.LeftShoulder == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's RightShoulder button was just pressed.
/// </summary>
public static bool IsGamePadRightShoulderTriggered()
{
return (
(currentGamePadState.Buttons.RightShoulder == ButtonState.Pressed) &&
(previousGamePadState.Buttons.RightShoulder == ButtonState.Released));
}
/// <summary>
/// Check if Up on the gamepad's directional pad was just pressed.
/// </summary>
public static bool IsGamePadDPadUpTriggered()
{
return ((currentGamePadState.DPad.Up == ButtonState.Pressed) &&
(previousGamePadState.DPad.Up == ButtonState.Released));
}
/// <summary>
/// Check if Down on the gamepad's directional pad was just pressed.
/// </summary>
public static bool IsGamePadDPadDownTriggered()
{
return ((currentGamePadState.DPad.Down == ButtonState.Pressed) &&
(previousGamePadState.DPad.Down == ButtonState.Released));
}
/// <summary>
/// Check if Left on the gamepad's directional pad was just pressed.
/// </summary>
public static bool IsGamePadDPadLeftTriggered()
{
return ((currentGamePadState.DPad.Left == ButtonState.Pressed) &&
(previousGamePadState.DPad.Left == ButtonState.Released));
}
/// <summary>
/// Check if Right on the gamepad's directional pad was just pressed.
/// </summary>
public static bool IsGamePadDPadRightTriggered()
{
return ((currentGamePadState.DPad.Right == ButtonState.Pressed) &&
(previousGamePadState.DPad.Right == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's left trigger was just pressed.
/// </summary>
public static bool IsGamePadLeftTriggerTriggered()
{
return ((currentGamePadState.Triggers.Left > analogLimit) &&
(previousGamePadState.Triggers.Left < analogLimit));
}
/// <summary>
/// Check if the gamepad's right trigger was just pressed.
/// </summary>
public static bool IsGamePadRightTriggerTriggered()
{
return ((currentGamePadState.Triggers.Right > analogLimit) &&
(previousGamePadState.Triggers.Right < analogLimit));
}
/// <summary>
/// Check if Up on the gamepad's left analog stick was just pressed.
/// </summary>
public static bool IsGamePadLeftStickUpTriggered()
{
return ((currentGamePadState.ThumbSticks.Left.Y > analogLimit) &&
(previousGamePadState.ThumbSticks.Left.Y < analogLimit));
}
/// <summary>
/// Check if Down on the gamepad's left analog stick was just pressed.
/// </summary>
public static bool IsGamePadLeftStickDownTriggered()
{
return ((-1f * currentGamePadState.ThumbSticks.Left.Y > analogLimit) &&
(-1f * previousGamePadState.ThumbSticks.Left.Y < analogLimit));
}
/// <summary>
/// Check if Left on the gamepad's left analog stick was just pressed.
/// </summary>
public static bool IsGamePadLeftStickLeftTriggered()
{
return ((-1f * currentGamePadState.ThumbSticks.Left.X > analogLimit) &&
(-1f * previousGamePadState.ThumbSticks.Left.X < analogLimit));
}
/// <summary>
/// Check if Right on the gamepad's left analog stick was just pressed.
/// </summary>
public static bool IsGamePadLeftStickRightTriggered()
{
return ((currentGamePadState.ThumbSticks.Left.X > analogLimit) &&
(previousGamePadState.ThumbSticks.Left.X < analogLimit));
}
/// <summary>
/// Check if the GamePadKey value specified was pressed this frame.
/// </summary>
private static bool IsGamePadButtonTriggered(GamePadButtons gamePadKey)
{
switch (gamePadKey)
{
case GamePadButtons.Start:
return IsGamePadStartTriggered();
case GamePadButtons.Back:
return IsGamePadBackTriggered();
case GamePadButtons.A:
return IsGamePadATriggered();
case GamePadButtons.B:
return IsGamePadBTriggered();
case GamePadButtons.X:
return IsGamePadXTriggered();
case GamePadButtons.Y:
return IsGamePadYTriggered();
case GamePadButtons.LeftShoulder:
return IsGamePadLeftShoulderTriggered();
case GamePadButtons.RightShoulder:
return IsGamePadRightShoulderTriggered();
case GamePadButtons.LeftTrigger:
return IsGamePadLeftTriggerTriggered();
case GamePadButtons.RightTrigger:
return IsGamePadRightTriggerTriggered();
case GamePadButtons.Up:
return IsGamePadDPadUpTriggered() ||
IsGamePadLeftStickUpTriggered();
case GamePadButtons.Down:
return IsGamePadDPadDownTriggered() ||
IsGamePadLeftStickDownTriggered();
case GamePadButtons.Left:
return IsGamePadDPadLeftTriggered() ||
IsGamePadLeftStickLeftTriggered();
case GamePadButtons.Right:
return IsGamePadDPadRightTriggered() ||
IsGamePadLeftStickRightTriggered();
}
return false;
}
#endregion
#endregion
#region Action Mapping
/// <summary>
/// The action mappings for the game.
/// </summary>
private static ActionMap[] actionMaps;
public static ActionMap[] ActionMaps
{
get { return actionMaps; }
}
/// <summary>
/// Reset the action maps to their default values.
/// </summary>
private static void ResetActionMaps()
{
actionMaps = new ActionMap[(int)Action.TotalActionCount];
actionMaps[(int)Action.MainMenu] = new ActionMap();
actionMaps[(int)Action.MainMenu].keyboardKeys.Add(
Keys.Tab);
actionMaps[(int)Action.MainMenu].gamePadButtons.Add(
GamePadButtons.Start);
actionMaps[(int)Action.Ok] = new ActionMap();
actionMaps[(int)Action.Ok].keyboardKeys.Add(
Keys.Enter);
actionMaps[(int)Action.Ok].gamePadButtons.Add(
GamePadButtons.A);
actionMaps[(int)Action.Back] = new ActionMap();
actionMaps[(int)Action.Back].keyboardKeys.Add(
Keys.Escape);
actionMaps[(int)Action.Back].gamePadButtons.Add(
GamePadButtons.B);
actionMaps[(int)Action.CharacterManagement] = new ActionMap();
actionMaps[(int)Action.CharacterManagement].keyboardKeys.Add(
Keys.Space);
actionMaps[(int)Action.CharacterManagement].gamePadButtons.Add(
GamePadButtons.Y);
actionMaps[(int)Action.ExitGame] = new ActionMap();
actionMaps[(int)Action.ExitGame].keyboardKeys.Add(
Keys.Escape);
actionMaps[(int)Action.ExitGame].gamePadButtons.Add(
GamePadButtons.Back);
actionMaps[(int)Action.TakeView] = new ActionMap();
actionMaps[(int)Action.TakeView].keyboardKeys.Add(
Keys.LeftControl);
actionMaps[(int)Action.TakeView].gamePadButtons.Add(
GamePadButtons.Y);
actionMaps[(int)Action.DropUnEquip] = new ActionMap();
actionMaps[(int)Action.DropUnEquip].keyboardKeys.Add(
Keys.D);
actionMaps[(int)Action.DropUnEquip].gamePadButtons.Add(
GamePadButtons.X);
actionMaps[(int)Action.MoveCharacterUp] = new ActionMap();
actionMaps[(int)Action.MoveCharacterUp].keyboardKeys.Add(
Keys.Up);
actionMaps[(int)Action.MoveCharacterUp].gamePadButtons.Add(
GamePadButtons.Up);
actionMaps[(int)Action.MoveCharacterDown] = new ActionMap();
actionMaps[(int)Action.MoveCharacterDown].keyboardKeys.Add(
Keys.Down);
actionMaps[(int)Action.MoveCharacterDown].gamePadButtons.Add(
GamePadButtons.Down);
actionMaps[(int)Action.MoveCharacterLeft] = new ActionMap();
actionMaps[(int)Action.MoveCharacterLeft].keyboardKeys.Add(
Keys.Left);
actionMaps[(int)Action.MoveCharacterLeft].gamePadButtons.Add(
GamePadButtons.Left);
actionMaps[(int)Action.MoveCharacterRight] = new ActionMap();
actionMaps[(int)Action.MoveCharacterRight].keyboardKeys.Add(
Keys.Right);
actionMaps[(int)Action.MoveCharacterRight].gamePadButtons.Add(
GamePadButtons.Right);
actionMaps[(int)Action.CursorUp] = new ActionMap();
actionMaps[(int)Action.CursorUp].keyboardKeys.Add(
Keys.Up);
actionMaps[(int)Action.CursorUp].gamePadButtons.Add(
GamePadButtons.Up);
actionMaps[(int)Action.CursorDown] = new ActionMap();
actionMaps[(int)Action.CursorDown].keyboardKeys.Add(
Keys.Down);
actionMaps[(int)Action.CursorDown].gamePadButtons.Add(
GamePadButtons.Down);
actionMaps[(int)Action.DecreaseAmount] = new ActionMap();
actionMaps[(int)Action.DecreaseAmount].keyboardKeys.Add(
Keys.Left);
actionMaps[(int)Action.DecreaseAmount].gamePadButtons.Add(
GamePadButtons.Left);
actionMaps[(int)Action.IncreaseAmount] = new ActionMap();
actionMaps[(int)Action.IncreaseAmount].keyboardKeys.Add(
Keys.Right);
actionMaps[(int)Action.IncreaseAmount].gamePadButtons.Add(
GamePadButtons.Right);
actionMaps[(int)Action.PageLeft] = new ActionMap();
actionMaps[(int)Action.PageLeft].keyboardKeys.Add(
Keys.LeftShift);
actionMaps[(int)Action.PageLeft].gamePadButtons.Add(
GamePadButtons.LeftTrigger);
actionMaps[(int)Action.PageRight] = new ActionMap();
actionMaps[(int)Action.PageRight].keyboardKeys.Add(
Keys.RightShift);
actionMaps[(int)Action.PageRight].gamePadButtons.Add(
GamePadButtons.RightTrigger);
actionMaps[(int)Action.TargetUp] = new ActionMap();
actionMaps[(int)Action.TargetUp].keyboardKeys.Add(
Keys.Up);
actionMaps[(int)Action.TargetUp].gamePadButtons.Add(
GamePadButtons.Up);
actionMaps[(int)Action.TargetDown] = new ActionMap();
actionMaps[(int)Action.TargetDown].keyboardKeys.Add(
Keys.Down);
actionMaps[(int)Action.TargetDown].gamePadButtons.Add(
GamePadButtons.Down);
actionMaps[(int)Action.ActiveCharacterLeft] = new ActionMap();
actionMaps[(int)Action.ActiveCharacterLeft].keyboardKeys.Add(
Keys.Left);
actionMaps[(int)Action.ActiveCharacterLeft].gamePadButtons.Add(
GamePadButtons.Left);
actionMaps[(int)Action.ActiveCharacterRight] = new ActionMap();
actionMaps[(int)Action.ActiveCharacterRight].keyboardKeys.Add(
Keys.Right);
actionMaps[(int)Action.ActiveCharacterRight].gamePadButtons.Add(
GamePadButtons.Right);
}
/// <summary>
/// Check if an action has been pressed.
/// </summary>
public static bool IsActionPressed(Action action)
{
return IsActionMapPressed(actionMaps[(int)action]);
}
/// <summary>
/// Check if an action was just performed in the most recent update.
/// </summary>
public static bool IsActionTriggered(Action action)
{
return IsActionMapTriggered(actionMaps[(int)action]);
}
/// <summary>
/// Check if an action map has been pressed.
/// </summary>
private static bool IsActionMapPressed(ActionMap actionMap)
{
for (int i = 0; i < actionMap.keyboardKeys.Count; i++)
{
if (IsKeyPressed(actionMap.keyboardKeys[i]))
{
return true;
}
}
if (currentGamePadState.IsConnected)
{
for (int i = 0; i < actionMap.gamePadButtons.Count; i++)
{
if (IsGamePadButtonPressed(actionMap.gamePadButtons[i]))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Check if an action map has been triggered this frame.
/// </summary>
private static bool IsActionMapTriggered(ActionMap actionMap)
{
for (int i = 0; i < actionMap.keyboardKeys.Count; i++)
{
if (IsKeyTriggered(actionMap.keyboardKeys[i]))
{
return true;
}
}
if (currentGamePadState.IsConnected)
{
for (int i = 0; i < actionMap.gamePadButtons.Count; i++)
{
if (IsGamePadButtonTriggered(actionMap.gamePadButtons[i]))
{
return true;
}
}
}
return false;
}
#endregion
#region Initialization
/// <summary>
/// Initializes the default control keys for all actions.
/// </summary>
public static void Initialize()
{
ResetActionMaps();
}
#endregion
#region Updating
/// <summary>
/// Updates the keyboard and gamepad control states.
/// </summary>
public static void Update()
{
// update the keyboard state
previousKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
// update the gamepad state
previousGamePadState = currentGamePadState;
currentGamePadState = GamePad.GetState(PlayerIndex.One);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using gov.va.medora.mdo.dao;
using gov.va.medora.mdo.domain.ccr;
namespace gov.va.medora.mdo
{
public class Medication
{
const string DAO_NAME = "IPharmacyDao";
public class MedicationType
{
public static MedicationType OUTPATIENT = new MedicationType("OP");
public static MedicationType IV = new MedicationType("IV");
public static MedicationType NONVA = new MedicationType("NV");
public static MedicationType UNITDOSE = new MedicationType("UD");
public static MedicationType INFOROUT = new MedicationType("CP");
public static IEnumerable<MedicationType> Values
{
get
{
yield return OUTPATIENT;
yield return IV;
yield return NONVA;
yield return UNITDOSE;
yield return INFOROUT;
}
}
string code;
MedicationType(string code) { this.code = code; }
public string Code { get { return this.code; } }
public override string ToString() { return Code; }
public static MedicationType valueOf(string code)
{
foreach (MedicationType type in Values)
{
if (code.ToUpper().Equals(type.Code))
return type;
}
return null;
}
}
string id;
string name;
string rxNum;
string pharmId;
string quantity;
string expirationDate;
string issueDate;
string startDate;
string stopDate;
string orderId;
string status;
string refills;
bool outpatient;
bool inpatient;
bool IV;
bool unitDose;
bool nonVA;
bool imo;
string lastFillDate;
string remaining;
SiteId facility;
Author provider;
string cost;
string sig;
string type;
string additives;
string solution;
string rate;
string route;
string dose;
string instruction;
string comment;
string dateDocumented;
Author documentor;
string detail;
string schedule;
string daysSupply;
KeyValuePair<string, string> pharmacyOrderableItem;
KeyValuePair<string, string> drug;
KeyValuePair<string, string> hospital;
bool isSupply;
public Medication() { }
public bool IsSupply
{
get { return isSupply; }
set { isSupply = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string RxNumber
{
get { return rxNum; }
set { rxNum = value; }
}
public string PharmacyId
{
get { return pharmId; }
set { pharmId = value; }
}
public string Quantity
{
get { return quantity; }
set { quantity = value; }
}
public string ExpirationDate
{
get { return expirationDate; }
set { expirationDate = value; }
}
public string IssueDate
{
get { return issueDate; }
set { issueDate = value; }
}
public string OrderId
{
get { return orderId; }
set { orderId = value; }
}
public string Status
{
get { return status; }
set { status = value; }
}
public string Refills
{
get { return refills; }
set { refills = value; }
}
public bool IsOutpatient
{
get { return outpatient; }
set { outpatient = value; }
}
public bool IsInpatient
{
get { return inpatient; }
set { inpatient = value; }
}
public bool IsIV
{
get { return IV; }
set { IV = value; }
}
public bool IsUnitDose
{
get { return unitDose; }
set { unitDose = value; }
}
public bool IsNonVA
{
get { return nonVA; }
set { nonVA = value; }
}
public bool IsImo
{
get { return imo; }
set { imo = value; }
}
public string LastFillDate
{
get { return lastFillDate; }
set { lastFillDate = value; }
}
public string Remaining
{
get { return remaining; }
set { remaining = value; }
}
public SiteId Facility
{
get { return facility; }
set { facility = value; }
}
public Author Provider
{
get { return provider; }
set { provider = value; }
}
public string Cost
{
get { return cost; }
set { cost = value; }
}
public string Sig
{
get { return sig; }
set { sig = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public string Additives
{
get { return additives; }
set { additives = value; }
}
public string Solution
{
get { return solution; }
set { solution = value; }
}
public string Rate
{
get { return rate; }
set { rate = value; }
}
public string Route
{
get { return route; }
set { route = value; }
}
public string Dose
{
get { return dose; }
set { dose = value; }
}
public string Instruction
{
get { return instruction; }
set { instruction = value; }
}
public string Comment
{
get { return comment; }
set { comment = value; }
}
public string StartDate
{
get { return startDate; }
set { startDate = value; }
}
public string StopDate
{
get { return stopDate; }
set { stopDate = value; }
}
public string DateDocumented
{
get { return dateDocumented; }
set { dateDocumented = value; }
}
public Author Documentor
{
get { return documentor; }
set { documentor = value; }
}
public string Detail
{
get { return detail; }
set { detail = value; }
}
public string Schedule
{
get { return schedule; }
set { schedule = value; }
}
public string DaysSupply
{
get { return daysSupply; }
set { daysSupply = value; }
}
public KeyValuePair<string, string> PharmacyOrderableItem
{
get { return pharmacyOrderableItem; }
set { pharmacyOrderableItem = value; }
}
public KeyValuePair<string, string> Drug
{
get { return drug; }
set { drug = value; }
}
public KeyValuePair<string, string> Hospital
{
get { return hospital; }
set { hospital = value; }
}
/// <summary>
/// Create a string representation of the Medication object using a few of the unique properties
/// </summary>
/// <returns>String representation of Medication object</returns>
public override string ToString()
{
return "Medication" + Environment.NewLine +
"----------" + Environment.NewLine +
"ID: " + id + Environment.NewLine +
"Name: " + name + Environment.NewLine +
"RxNum: " + rxNum + Environment.NewLine +
"Pharmacy ID: " + pharmId + Environment.NewLine +
"Order ID: " + orderId + Environment.NewLine +
"Detail: " + detail + Environment.NewLine;
}
internal static IPharmacyDao getDao(AbstractConnection cxn)
{
AbstractDaoFactory f = AbstractDaoFactory.getDaoFactory(AbstractDaoFactory.getConstant(cxn.DataSource.Protocol));
return f.getPharmacyDao(cxn);
}
public static IndexedHashtable getOutpatientMeds(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getOutpatientMeds", new object[] { });
}
public static IndexedHashtable getIvMeds(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getIvMeds", new object[] { });
}
public static IndexedHashtable getUnitDoseMeds(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getUnitDoseMeds", new object[] { });
}
public static IndexedHashtable getOtherMeds(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getOtherMeds", new object[] { });
}
public static IndexedHashtable getAllMeds(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getAllMeds", new object[] { });
}
public static string getMedicationDetail(AbstractConnection cxn, string medId)
{
return getDao(cxn).getMedicationDetail(medId);
}
public static IndexedHashtable getOutpatientRxProfile(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getOutpatientRxProfile", new object[] { });
}
public static IndexedHashtable getMedsAdminHx(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getMedsAdminHx", new object[] { fromDate, toDate, nrpts });
}
public static IndexedHashtable getMedsAdminLog(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getMedsAdminLog", new object[] { fromDate, toDate, nrpts });
}
public static IndexedHashtable getImmunizations(ConnectionSet cxns, string fromDate, string toDate, int nrpts)
{
return cxns.query(DAO_NAME, "getImmunizations", new object[] { fromDate, toDate, nrpts });
}
public IndexedHashtable getDiscontinueReasons(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getDiscontinueReasons", new object[] { });
}
public static IndexedHashtable getImoMeds(ConnectionSet cxns)
{
return cxns.query(DAO_NAME, "getInpatientForOutpatientMeds", new object[] { });
}
/// <summary>
/// Convert a MDO Medication object to a CCR StructuredProductType. Since there is not a 1 to 1 mapping
/// between the two objects' properties, the additional arguments should be supplied
/// </summary>
/// <param name="med"></param>
/// <returns></returns>
public StructuredProductType toStructuredProductType(Medication med, string units, string form, string unitsPerDose)
{
StructuredProductType newMed = new CCRHelper().buildMedObject(med.Name, med.Id, med.PharmacyId, med.OrderId,
med.RxNumber, med.StartDate, med.StopDate, med.IssueDate, med.LastFillDate, med.ExpirationDate,
med.Sig, med.Dose, units, form, unitsPerDose, med.Schedule, med.Route, med.Refills, med.Remaining, med.Quantity,
med.Provider.Name, med.Provider.Id, med.Status, med.Type);
return newMed;
}
}
}
| |
//
// WorkspaceManager.cs
//
// Author:
// Jonathan Pobst <[email protected]>
//
// Copyright (c) 2010 Jonathan Pobst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Cairo;
namespace Pinta.Core
{
public class WorkspaceManager
{
private string filename;
private bool is_dirty;
private Point canvas_size;
public Point ImageSize { get; set; }
public Point CanvasSize {
get { return canvas_size; }
set {
if (canvas_size.X != value.X || canvas_size.Y != value.Y) {
canvas_size = value;
OnCanvasSizeChanged ();
}
}
}
public PointD Offset {
get { return new PointD ((PintaCore.Chrome.DrawingArea.Allocation.Width - canvas_size.X) / 2, (PintaCore.Chrome.DrawingArea.Allocation.Height - CanvasSize.Y) / 2); }
}
public WorkspaceManager ()
{
CanvasSize = new Point (800, 600);
ImageSize = new Point (800, 600);
}
public double Scale {
get { return (double)CanvasSize.X / (double)ImageSize.X; }
set {
if (Scale != value) {
int new_x = (int)(ImageSize.X * value);
int new_y = (int)((new_x * ImageSize.Y) / ImageSize.X);
CanvasSize = new Point (new_x, new_y);
Invalidate ();
}
}
}
public void Invalidate ()
{
OnCanvasInvalidated (new CanvasInvalidatedEventArgs ());
}
public void Invalidate (Gdk.Rectangle rect)
{
rect = new Gdk.Rectangle ((int)((rect.X) * Scale + Offset.X), (int)((rect.Y) * Scale + Offset.Y), (int)(rect.Width * Scale), (int)(rect.Height * Scale));
OnCanvasInvalidated (new CanvasInvalidatedEventArgs (rect));
}
public void ZoomIn ()
{
double zoom;
if (!double.TryParse (PintaCore.Actions.View.ZoomComboBox.ComboBox.ActiveText.Trim ('%'), out zoom))
zoom = Scale * 100;
zoom = Math.Min (zoom, 3600);
int i = 0;
foreach (object item in (PintaCore.Actions.View.ZoomComboBox.ComboBox.Model as Gtk.ListStore)) {
if (((object[])item)[0].ToString () == "Window" || int.Parse (((object[])item)[0].ToString ().Trim ('%')) <= zoom) {
PintaCore.Actions.View.ZoomComboBox.ComboBox.Active = i - 1;
return;
}
i++;
}
}
public void ZoomOut ()
{
double zoom;
if (!double.TryParse (PintaCore.Actions.View.ZoomComboBox.ComboBox.ActiveText.Trim ('%'), out zoom))
zoom = Scale * 100;
zoom = Math.Min (zoom, 3600);
int i = 0;
foreach (object item in (PintaCore.Actions.View.ZoomComboBox.ComboBox.Model as Gtk.ListStore)) {
if (((object[])item)[0].ToString () == "Window")
return;
if (int.Parse (((object[])item)[0].ToString ().Trim ('%')) < zoom) {
PintaCore.Actions.View.ZoomComboBox.ComboBox.Active = i;
return;
}
i++;
}
}
public void ZoomToRectangle (Rectangle rect)
{
double ratio;
if (ImageSize.X / rect.Width <= ImageSize.Y / rect.Height)
ratio = ImageSize.X / rect.Width;
else
ratio = ImageSize.Y / rect.Height;
(PintaCore.Actions.View.ZoomComboBox.ComboBox as Gtk.ComboBoxEntry).Entry.Text = String.Format ("{0:F}%", ratio * 100.0);
Gtk.Main.Iteration (); //Force update of scrollbar upper before recenter
RecenterView (rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
}
public void RecenterView (double x, double y)
{
Gtk.Viewport view = (Gtk.Viewport)PintaCore.Chrome.DrawingArea.Parent;
view.Hadjustment.Value = Utility.Clamp (x * Scale - view.Hadjustment.PageSize / 2 , view.Hadjustment.Lower, view.Hadjustment.Upper);
view.Vadjustment.Value = Utility.Clamp (y * Scale - view.Vadjustment.PageSize / 2 , view.Vadjustment.Lower, view.Vadjustment.Upper);
}
public void ResizeImage (int width, int height)
{
if (ImageSize.X == width && ImageSize.Y == height)
return;
PintaCore.Layers.FinishSelection ();
ResizeHistoryItem hist = new ResizeHistoryItem (ImageSize.X, ImageSize.Y);
hist.TakeSnapshotOfImage ();
ImageSize = new Point (width, height);
CanvasSize = new Point (width, height);
foreach (var layer in PintaCore.Layers)
layer.Resize (width, height);
PintaCore.History.PushNewItem (hist);
PintaCore.Layers.ResetSelectionPath ();
PintaCore.Workspace.Invalidate ();
}
public void ResizeCanvas (int width, int height, Anchor anchor)
{
if (ImageSize.X == width && ImageSize.Y == height)
return;
PintaCore.Layers.FinishSelection ();
ResizeHistoryItem hist = new ResizeHistoryItem (ImageSize.X, ImageSize.Y);
hist.Icon = "Menu.Image.CanvasSize.png";
hist.Text = "Resize Canvas";
hist.TakeSnapshotOfImage ();
ImageSize = new Point (width, height);
CanvasSize = new Point (width, height);
foreach (var layer in PintaCore.Layers)
layer.ResizeCanvas (width, height, anchor);
PintaCore.History.PushNewItem (hist);
PintaCore.Layers.ResetSelectionPath ();
PintaCore.Workspace.Invalidate ();
}
public Cairo.PointD WindowPointToCanvas (double x, double y)
{
return new Cairo.PointD ((x - Offset.X) / PintaCore.Workspace.Scale, (y - Offset.Y) / PintaCore.Workspace.Scale);
}
public bool PointInCanvas (Cairo.PointD point)
{
if (point.X < 0 || point.Y < 0)
return false;
if (point.X >= PintaCore.Workspace.ImageSize.X || point.Y >= PintaCore.Workspace.ImageSize.Y)
return false;
return true;
}
public Gdk.Rectangle ClampToImageSize (Gdk.Rectangle r)
{
int x = Utility.Clamp (r.X, 0, ImageSize.X);
int y = Utility.Clamp (r.Y, 0, ImageSize.Y);
int width = Math.Min (r.Width, ImageSize.X - x);
int height = Math.Min (r.Height, ImageSize.Y - y);
return new Gdk.Rectangle (x, y, width, height);
}
public string Filename {
get { return filename; }
set {
if (filename != value) {
filename = value;
ResetTitle ();
}
}
}
public bool IsDirty {
get { return is_dirty; }
set {
if (is_dirty != value) {
is_dirty = value;
ResetTitle ();
}
}
}
public bool CanvasFitsInWindow {
get {
Gtk.Viewport view = (Gtk.Viewport)PintaCore.Chrome.DrawingArea.Parent;
int window_x = view.Allocation.Width;
int window_y = view.Children[0].Allocation.Height;
if (CanvasSize.X <= window_x && CanvasSize.Y <= window_y)
return true;
return false;
}
}
public bool ImageFitsInWindow {
get {
Gtk.Viewport view = (Gtk.Viewport)PintaCore.Chrome.DrawingArea.Parent;
int window_x = view.Allocation.Width;
int window_y = view.Children[0].Allocation.Height;
if (ImageSize.X <= window_x && ImageSize.Y <= window_y)
return true;
return false;
}
}
public void ScrollCanvas (int dx, int dy)
{
Gtk.Viewport view = (Gtk.Viewport)PintaCore.Chrome.DrawingArea.Parent;
view.Hadjustment.Value = Utility.Clamp (dx + view.Hadjustment.Value, view.Hadjustment.Lower, view.Hadjustment.Upper - view.Hadjustment.PageSize);
view.Vadjustment.Value = Utility.Clamp (dy + view.Vadjustment.Value, view.Vadjustment.Lower, view.Vadjustment.Upper - view.Vadjustment.PageSize);
}
private void ResetTitle ()
{
PintaCore.Chrome.MainWindow.Title = string.Format ("{0}{1} - Pinta", filename, is_dirty ? "*" : "");
}
#region Protected Methods
protected void OnCanvasInvalidated (CanvasInvalidatedEventArgs e)
{
if (CanvasInvalidated != null)
CanvasInvalidated (this, e);
}
protected void OnCanvasSizeChanged ()
{
if (CanvasSizeChanged != null)
CanvasSizeChanged (this, EventArgs.Empty);
}
#endregion
#region Public Events
public event EventHandler<CanvasInvalidatedEventArgs> CanvasInvalidated;
public event EventHandler CanvasSizeChanged;
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="OLEDB_Enum.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.OleDb {
using System;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
internal enum DBStatus { // from 4214.0
S_OK = 0,
E_BADACCESSOR = 1,
E_CANTCONVERTVALUE = 2,
S_ISNULL = 3,
S_TRUNCATED = 4,
E_SIGNMISMATCH = 5,
E_DATAOVERFLOW = 6,
E_CANTCREATE = 7,
E_UNAVAILABLE = 8,
E_PERMISSIONDENIED = 9,
E_INTEGRITYVIOLATION = 10,
E_SCHEMAVIOLATION = 11,
E_BADSTATUS = 12,
S_DEFAULT = 13,
S_CELLEMPTY = 14, // 2.0
S_IGNORE = 15, // 2.0
E_DOESNOTEXIST = 16, // 2.1
E_INVALIDURL = 17, // 2.1
E_RESOURCELOCKED = 18, // 2.1
E_RESOURCEEXISTS = 19, // 2.1
E_CANNOTCOMPLETE = 20, // 2.1
E_VOLUMENOTFOUND = 21, // 2.1
E_OUTOFSPACE = 22, // 2.1
S_CANNOTDELETESOURCE = 23, // 2.1
E_READONLY = 24, // 2.1
E_RESOURCEOUTOFSCOPE = 25, // 2.1
S_ALREADYEXISTS = 26, // 2.1
E_CANCELED = 27, // 2.5
E_NOTCOLLECTION = 28, // 2.5
S_ROWSETCOLUMN = 29, // 2.6
}
sealed internal class NativeDBType { // from 4214.0
// Variant compatible
internal const short EMPTY = 0; //
internal const short NULL = 1; //
internal const short I2 = 2; //
internal const short I4 = 3; //
internal const short R4 = 4; //
internal const short R8 = 5; //
internal const short CY = 6; //
internal const short DATE = 7; //
internal const short BSTR = 8; //
internal const short IDISPATCH = 9; //
internal const short ERROR = 10; //
internal const short BOOL = 11; //
internal const short VARIANT = 12; //
internal const short IUNKNOWN = 13; //
internal const short DECIMAL = 14; //
internal const short I1 = 16; //
internal const short UI1 = 17; //
internal const short UI2 = 18; //
internal const short UI4 = 19; //
internal const short I8 = 20; //
internal const short UI8 = 21; //
internal const short FILETIME = 64; // 2.0
internal const short DBUTCDATETIME = 65; // 9.0
internal const short DBTIME_EX = 66; // 9.0
internal const short GUID = 72; //
internal const short BYTES = 128; //
internal const short STR = 129; //
internal const short WSTR = 130; //
internal const short NUMERIC = 131; // with potential overflow
internal const short UDT = 132; // should never be encountered
internal const short DBDATE = 133; //
internal const short DBTIME = 134; //
internal const short DBTIMESTAMP = 135; // granularity reduced from 1ns to 100ns (sql is 3.33 milli seconds)
internal const short HCHAPTER = 136; // 1.5
internal const short PROPVARIANT = 138; // 2.0 - as variant
internal const short VARNUMERIC = 139; // 2.0 - as string else ConversionException
internal const short XML = 141; // 9.0
internal const short VECTOR = unchecked((short)0x1000);
internal const short ARRAY = unchecked((short)0x2000);
internal const short BYREF = unchecked((short)0x4000); //
internal const short RESERVED = unchecked((short)0x8000); // SystemException
// high mask
internal const short HighMask = unchecked((short)0xf000);
static internal bool HasHighBit(short value) {
return (0 != (HighMask & value));
}
/*
static internal bool IsArray(short value) {
return (ARRAY == (HighMask & value));
}
static internal bool IsByRef(short value) {
return (BYREF == (HighMask & value));
}
static internal bool IsReserved(short value) {
return (RESERVED == (HighMask & value));
}
static internal bool IsVector(short value) {
return (VECTOR == (HighMask & value));
}
static internal int GetLowBits(short value) {
return (value & ~HighMask);
}
*/
private const string S_BINARY = "DBTYPE_BINARY"; // DBTYPE_BYTES
private const string S_BOOL = "DBTYPE_BOOL";
private const string S_BSTR = "DBTYPE_BSTR";
private const string S_CHAR = "DBTYPE_CHAR"; // DBTYPE_STR
private const string S_CY = "DBTYPE_CY";
private const string S_DATE = "DBTYPE_DATE";
private const string S_DBDATE = "DBTYPE_DBDATE";
private const string S_DBTIME = "DBTYPE_DBTIME";
private const string S_DBTIMESTAMP = "DBTYPE_DBTIMESTAMP";
private const string S_DECIMAL = "DBTYPE_DECIMAL";
private const string S_ERROR = "DBTYPE_ERROR";
private const string S_FILETIME = "DBTYPE_FILETIME";
private const string S_GUID = "DBTYPE_GUID";
private const string S_I1 = "DBTYPE_I1";
private const string S_I2 = "DBTYPE_I2";
private const string S_I4 = "DBTYPE_I4";
private const string S_I8 = "DBTYPE_I8";
private const string S_IDISPATCH = "DBTYPE_IDISPATCH";
private const string S_IUNKNOWN = "DBTYPE_IUNKNOWN";
private const string S_LONGVARBINARY = "DBTYPE_LONGVARBINARY"; // DBTYPE_BYTES
private const string S_LONGVARCHAR = "DBTYPE_LONGVARCHAR"; // DBTYPE_STR
private const string S_NUMERIC = "DBTYPE_NUMERIC";
private const string S_PROPVARIANT = "DBTYPE_PROPVARIANT";
private const string S_R4 = "DBTYPE_R4";
private const string S_R8 = "DBTYPE_R8";
private const string S_UDT = "DBTYPE_UDT";
private const string S_UI1 = "DBTYPE_UI1";
private const string S_UI2 = "DBTYPE_UI2";
private const string S_UI4 = "DBTYPE_UI4";
private const string S_UI8 = "DBTYPE_UI8";
private const string S_VARBINARY = "DBTYPE_VARBINARY"; // DBTYPE_BYTES
private const string S_VARCHAR = "DBTYPE_VARCHAR"; // DBTYPE_STR
private const string S_VARIANT = "DBTYPE_VARIANT";
private const string S_VARNUMERIC = "DBTYPE_VARNUMERIC";
private const string S_WCHAR = "DBTYPE_WCHAR"; // DBTYPE_WSTR
private const string S_WVARCHAR = "DBTYPE_WVARCHAR"; // DBTYPE_WSTR
private const string S_WLONGVARCHAR = "DBTYPE_WLONGVARCHAR"; // DBTYPE_WSTR
private const string S_XML = "DBTYPE_XML";
static private readonly NativeDBType D_Binary = new NativeDBType(0xff, -1, true, false, OleDbType.Binary, NativeDBType.BYTES, S_BINARY, typeof(System.Byte[]), NativeDBType.BYTES, DbType.Binary ); // 0
static private readonly NativeDBType D_Boolean = new NativeDBType(0xff, 2, true, false, OleDbType.Boolean, NativeDBType.BOOL, S_BOOL, typeof(System.Boolean), NativeDBType.BOOL, DbType.Boolean ); // 1 - integer2 (variant_bool)
static private readonly NativeDBType D_BSTR = new NativeDBType(0xff, ADP.PtrSize, false, false, OleDbType.BSTR, NativeDBType.BSTR, S_BSTR, typeof(System.String), NativeDBType.BSTR, DbType.String ); // 2 - integer4 (pointer)
static private readonly NativeDBType D_Char = new NativeDBType(0xff, -1, true, false, OleDbType.Char, NativeDBType.STR, S_CHAR, typeof(System.String), NativeDBType.WSTR/*STR*/, DbType.AnsiStringFixedLength); // 3 - (ansi pointer)
static private readonly NativeDBType D_Currency = new NativeDBType( 19, 8, true, false, OleDbType.Currency, NativeDBType.CY, S_CY, typeof(System.Decimal), NativeDBType.CY, DbType.Currency ); // 4 - integer8
static private readonly NativeDBType D_Date = new NativeDBType(0xff, 8, true, false, OleDbType.Date, NativeDBType.DATE, S_DATE, typeof(System.DateTime), NativeDBType.DATE, DbType.DateTime ); // 5 - double
static private readonly NativeDBType D_DBDate = new NativeDBType(0xff, 6, true, false, OleDbType.DBDate, NativeDBType.DBDATE, S_DBDATE, typeof(System.DateTime), NativeDBType.DBDATE, DbType.Date ); // 6 - (tagDBDate)
static private readonly NativeDBType D_DBTime = new NativeDBType(0xff, 6, true, false, OleDbType.DBTime, NativeDBType.DBTIME, S_DBTIME, typeof(System.TimeSpan), NativeDBType.DBTIME, DbType.Time ); // 7 - (tagDBTime)
static private readonly NativeDBType D_DBTimeStamp = new NativeDBType(0xff, 16, true, false, OleDbType.DBTimeStamp, NativeDBType.DBTIMESTAMP, S_DBTIMESTAMP, typeof(System.DateTime), NativeDBType.DBTIMESTAMP, DbType.DateTime ); // 8 - (tagDBTIMESTAMP)
static private readonly NativeDBType D_Decimal = new NativeDBType( 28, 16, true, false, OleDbType.Decimal, NativeDBType.DECIMAL, S_DECIMAL, typeof(System.Decimal), NativeDBType.DECIMAL, DbType.Decimal ); // 9 - (tagDec) // MDAC 68447
static private readonly NativeDBType D_Error = new NativeDBType(0xff, 4, true, false, OleDbType.Error, NativeDBType.ERROR, S_ERROR, typeof(System.Int32), NativeDBType.ERROR, DbType.Int32 ); // 10 - integer4
static private readonly NativeDBType D_Filetime = new NativeDBType(0xff, 8, true, false, OleDbType.Filetime, NativeDBType.FILETIME, S_FILETIME, typeof(System.DateTime), NativeDBType.FILETIME, DbType.DateTime ); // 11 - integer8 // MDAC 59504
static private readonly NativeDBType D_Guid = new NativeDBType(0xff, 16, true, false, OleDbType.Guid, NativeDBType.GUID, S_GUID, typeof(System.Guid), NativeDBType.GUID, DbType.Guid ); // 12 - ubyte[16]
static private readonly NativeDBType D_TinyInt = new NativeDBType( 3, 1, true, false, OleDbType.TinyInt, NativeDBType.I1, S_I1, typeof(System.Int16), NativeDBType.I1, DbType.SByte ); // 13 - integer1 // MDAC 59492
static private readonly NativeDBType D_SmallInt = new NativeDBType( 5, 2, true, false, OleDbType.SmallInt, NativeDBType.I2, S_I2, typeof(System.Int16), NativeDBType.I2, DbType.Int16 ); // 14 - integer2
static private readonly NativeDBType D_Integer = new NativeDBType( 10, 4, true, false, OleDbType.Integer, NativeDBType.I4, S_I4, typeof(System.Int32), NativeDBType.I4, DbType.Int32 ); // 15 - integer4
static private readonly NativeDBType D_BigInt = new NativeDBType( 19, 8, true, false, OleDbType.BigInt, NativeDBType.I8, S_I8, typeof(System.Int64), NativeDBType.I8, DbType.Int64 ); // 16 - integer8
static private readonly NativeDBType D_IDispatch = new NativeDBType(0xff, ADP.PtrSize, true, false, OleDbType.IDispatch, NativeDBType.IDISPATCH, S_IDISPATCH, typeof(System.Object), NativeDBType.IDISPATCH, DbType.Object ); // 17 - integer4 (pointer)
static private readonly NativeDBType D_IUnknown = new NativeDBType(0xff, ADP.PtrSize, true, false, OleDbType.IUnknown, NativeDBType.IUNKNOWN, S_IUNKNOWN, typeof(System.Object), NativeDBType.IUNKNOWN, DbType.Object ); // 18 - integer4 (pointer) // MDAC 64040
static private readonly NativeDBType D_LongVarBinary = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarBinary, NativeDBType.BYTES, S_LONGVARBINARY, typeof(System.Byte[]), NativeDBType.BYTES, DbType.Binary ); // 19
static private readonly NativeDBType D_LongVarChar = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarChar, NativeDBType.STR, S_LONGVARCHAR, typeof(System.String), NativeDBType.WSTR/*STR*/, DbType.AnsiString); // 20 - (ansi pointer)
static private readonly NativeDBType D_Numeric = new NativeDBType( 28, 19, true, false, OleDbType.Numeric, NativeDBType.NUMERIC, S_NUMERIC, typeof(System.Decimal), NativeDBType.NUMERIC, DbType.Decimal ); // 21 - (tagDB_Numeric)
static private readonly NativeDBType D_PropVariant = new NativeDBType(0xff, NativeOledbWrapper.SizeOfPROPVARIANT,
true, false, OleDbType.PropVariant, NativeDBType.PROPVARIANT, S_PROPVARIANT, typeof(System.Object), NativeDBType.VARIANT, DbType.Object ); // 22
static private readonly NativeDBType D_Single = new NativeDBType( 7, 4, true, false, OleDbType.Single, NativeDBType.R4, S_R4, typeof(System.Single), NativeDBType.R4, DbType.Single ); // 23 - single
static private readonly NativeDBType D_Double = new NativeDBType( 15, 8, true, false, OleDbType.Double, NativeDBType.R8, S_R8, typeof(System.Double), NativeDBType.R8, DbType.Double ); // 24 - double
static private readonly NativeDBType D_UnsignedTinyInt = new NativeDBType( 3, 1, true, false, OleDbType.UnsignedTinyInt, NativeDBType.UI1, S_UI1, typeof(System.Byte), NativeDBType.UI1, DbType.Byte ); // 25 - byte7
static private readonly NativeDBType D_UnsignedSmallInt = new NativeDBType( 5, 2, true, false, OleDbType.UnsignedSmallInt, NativeDBType.UI2, S_UI2, typeof(System.Int32), NativeDBType.UI2, DbType.UInt16 ); // 26 - unsigned integer2
static private readonly NativeDBType D_UnsignedInt = new NativeDBType( 10, 4, true, false, OleDbType.UnsignedInt, NativeDBType.UI4, S_UI4, typeof(System.Int64), NativeDBType.UI4, DbType.UInt32 ); // 27 - unsigned integer4
static private readonly NativeDBType D_UnsignedBigInt = new NativeDBType( 20, 8, true, false, OleDbType.UnsignedBigInt, NativeDBType.UI8, S_UI8, typeof(System.Decimal), NativeDBType.UI8, DbType.UInt64 ); // 28 - unsigned integer8
static private readonly NativeDBType D_VarBinary = new NativeDBType(0xff, -1, false, false, OleDbType.VarBinary, NativeDBType.BYTES, S_VARBINARY, typeof(System.Byte[]), NativeDBType.BYTES, DbType.Binary ); // 29
static private readonly NativeDBType D_VarChar = new NativeDBType(0xff, -1, false, false, OleDbType.VarChar, NativeDBType.STR, S_VARCHAR, typeof(System.String), NativeDBType.WSTR/*STR*/, DbType.AnsiString); // 30 - (ansi pointer)
static private readonly NativeDBType D_Variant = new NativeDBType(0xff, ODB.SizeOf_Variant, true, false, OleDbType.Variant, NativeDBType.VARIANT, S_VARIANT, typeof(System.Object), NativeDBType.VARIANT, DbType.Object ); // 31 - ubyte[16] (variant)
static private readonly NativeDBType D_VarNumeric = new NativeDBType( 255, 16, true, false, OleDbType.VarNumeric, NativeDBType.VARNUMERIC, S_VARNUMERIC, typeof(System.Decimal), NativeDBType.DECIMAL, DbType.VarNumeric); // 32 - (unicode pointer)
static private readonly NativeDBType D_WChar = new NativeDBType(0xff, -1, true, false, OleDbType.WChar, NativeDBType.WSTR, S_WCHAR, typeof(System.String), NativeDBType.WSTR, DbType.StringFixedLength); // 33 - (unicode pointer)
static private readonly NativeDBType D_VarWChar = new NativeDBType(0xff, -1, false, false, OleDbType.VarWChar, NativeDBType.WSTR, S_WVARCHAR, typeof(System.String), NativeDBType.WSTR, DbType.String ); // 34 - (unicode pointer)
static private readonly NativeDBType D_LongVarWChar = new NativeDBType(0xff, -1, false, true, OleDbType.LongVarWChar, NativeDBType.WSTR, S_WLONGVARCHAR, typeof(System.String), NativeDBType.WSTR, DbType.String ); // 35 - (unicode pointer)
static private readonly NativeDBType D_Chapter = new NativeDBType(0xff, ADP.PtrSize, false, false, OleDbType.Empty, NativeDBType.HCHAPTER, S_UDT, typeof(IDataReader), NativeDBType.HCHAPTER, DbType.Object ); // 36 - (hierarchical chaper)
static private readonly NativeDBType D_Empty = new NativeDBType(0xff, 0, false, false, OleDbType.Empty, NativeDBType.EMPTY, "", null, NativeDBType.EMPTY, DbType.Object ); // 37 - invalid param default
static private readonly NativeDBType D_Xml = new NativeDBType(0xff, -1, false, false, OleDbType.VarWChar, NativeDBType.XML, S_XML, typeof(System.String), NativeDBType.WSTR, DbType.String ); // 38 - (unicode pointer)
static private readonly NativeDBType D_Udt = new NativeDBType(0xff, -1, false, false, OleDbType.VarBinary, NativeDBType.UDT, S_BINARY, typeof(System.Byte[]), NativeDBType.BYTES, DbType.Binary ); // 39 - (unicode pointer)
static internal readonly NativeDBType Default = D_VarWChar; // MDAC 65324
static internal readonly Byte MaximumDecimalPrecision = D_Decimal.maxpre;
private const int FixedDbPart = /*DBPART_VALUE*/0x1 | /*DBPART_STATUS*/0x4;
private const int VarblDbPart = /*DBPART_VALUE*/0x1 | /*DBPART_LENGTH*/0x2 | /*DBPART_STATUS*/0x4;
internal readonly OleDbType enumOleDbType; // enum System.Data.OleDb.OleDbType
internal readonly DbType enumDbType; // enum System.Data.DbType
internal readonly short dbType; // OLE DB DBTYPE_
internal readonly short wType; // OLE DB DBTYPE_ we ask OleDB Provider to bind as
internal readonly Type dataType; // CLR Type
internal readonly int dbPart; // the DBPart w or w/out length
internal readonly bool isfixed; // IsFixedLength
internal readonly bool islong; // IsLongLength
internal readonly Byte maxpre; // maxium precision for numeric types // $
internal readonly int fixlen; // fixed length size in bytes (-1 for variable)
internal readonly String dataSourceType; // ICommandWithParameters.SetParameterInfo standard type name
internal readonly StringMemHandle dbString; // ptr to native allocated memory for dataSourceType string
private NativeDBType(Byte maxpre, int fixlen, bool isfixed, bool islong, OleDbType enumOleDbType, short dbType, string dbstring, Type dataType, short wType, DbType enumDbType) {
this.enumOleDbType = enumOleDbType;
this.dbType = dbType;
this.dbPart = (-1 == fixlen) ? VarblDbPart : FixedDbPart;
this.isfixed = isfixed;
this.islong = islong;
this.maxpre = maxpre;
this.fixlen = fixlen;
this.wType = wType;
this.dataSourceType = dbstring;
this.dbString = new StringMemHandle(dbstring);
this.dataType = dataType;
this.enumDbType = enumDbType;
}
internal bool IsVariableLength {
get {
return (-1 == fixlen);
}
}
#if DEBUG
override public string ToString() {
return enumOleDbType.ToString();
}
#endif
static internal NativeDBType FromDataType(OleDbType enumOleDbType) {
switch(enumOleDbType) { // @perfnote: Enum.IsDefined
case OleDbType.Empty: return D_Empty; // 0
case OleDbType.SmallInt: return D_SmallInt; // 2
case OleDbType.Integer: return D_Integer; // 3
case OleDbType.Single: return D_Single; // 4
case OleDbType.Double: return D_Double; // 5
case OleDbType.Currency: return D_Currency; // 6
case OleDbType.Date: return D_Date; // 7
case OleDbType.BSTR: return D_BSTR; // 8
case OleDbType.IDispatch: return D_IDispatch; // 9
case OleDbType.Error: return D_Error; // 10
case OleDbType.Boolean: return D_Boolean; // 11
case OleDbType.Variant: return D_Variant; // 12
case OleDbType.IUnknown: return D_IUnknown; // 13
case OleDbType.Decimal: return D_Decimal; // 14
case OleDbType.TinyInt: return D_TinyInt; // 16
case OleDbType.UnsignedTinyInt: return D_UnsignedTinyInt; // 17
case OleDbType.UnsignedSmallInt: return D_UnsignedSmallInt; // 18
case OleDbType.UnsignedInt: return D_UnsignedInt; // 19
case OleDbType.BigInt: return D_BigInt; // 20
case OleDbType.UnsignedBigInt: return D_UnsignedBigInt; // 21
case OleDbType.Filetime: return D_Filetime; // 64
case OleDbType.Guid: return D_Guid; // 72
case OleDbType.Binary: return D_Binary; // 128
case OleDbType.Char: return D_Char; // 129
case OleDbType.WChar: return D_WChar; // 130
case OleDbType.Numeric: return D_Numeric; // 131
case OleDbType.DBDate: return D_DBDate; // 133
case OleDbType.DBTime: return D_DBTime; // 134
case OleDbType.DBTimeStamp: return D_DBTimeStamp; // 135
case OleDbType.PropVariant: return D_PropVariant; // 138
case OleDbType.VarNumeric: return D_VarNumeric; // 139
case OleDbType.VarChar: return D_VarChar; // 200
case OleDbType.LongVarChar: return D_LongVarChar; // 201
case OleDbType.VarWChar: return D_VarWChar; // 202 // MDAC 64983: ORA-12704: character set mismatch
case OleDbType.LongVarWChar: return D_LongVarWChar; // 203
case OleDbType.VarBinary: return D_VarBinary; // 204
case OleDbType.LongVarBinary: return D_LongVarBinary; // 205
default:
throw ODB.InvalidOleDbType(enumOleDbType);
}
}
static internal NativeDBType FromSystemType(object value) {
IConvertible ic = (value as IConvertible);
if (null != ic) {
switch(ic.GetTypeCode()) {
case TypeCode.Empty: return NativeDBType.D_Empty;
case TypeCode.Object: return NativeDBType.D_Variant;
case TypeCode.DBNull: throw ADP.InvalidDataType(TypeCode.DBNull);
case TypeCode.Boolean: return NativeDBType.D_Boolean;
case TypeCode.Char: return NativeDBType.D_Char;
case TypeCode.SByte: return NativeDBType.D_TinyInt;
case TypeCode.Byte: return NativeDBType.D_UnsignedTinyInt;
case TypeCode.Int16: return NativeDBType.D_SmallInt;
case TypeCode.UInt16: return NativeDBType.D_UnsignedSmallInt;
case TypeCode.Int32: return NativeDBType.D_Integer;
case TypeCode.UInt32: return NativeDBType.D_UnsignedInt;
case TypeCode.Int64: return NativeDBType.D_BigInt;
case TypeCode.UInt64: return NativeDBType.D_UnsignedBigInt;
case TypeCode.Single: return NativeDBType.D_Single;
case TypeCode.Double: return NativeDBType.D_Double;
case TypeCode.Decimal: return NativeDBType.D_Decimal;
case TypeCode.DateTime: return NativeDBType.D_DBTimeStamp;
case TypeCode.String: return NativeDBType.D_VarWChar;
default: throw ADP.UnknownDataTypeCode(value.GetType(), ic.GetTypeCode());
}
}
else if (value is System.Byte[]) {
return NativeDBType.D_VarBinary;
}
else if (value is System.Guid) {
return NativeDBType.D_Guid;
}
else if (value is System.TimeSpan) {
return NativeDBType.D_DBTime;
}
else {
return NativeDBType.D_Variant;
}
//throw ADP.UnknownDataType(value.GetType());
}
static internal NativeDBType FromDbType(DbType dbType) {
switch(dbType) {
case DbType.AnsiString: return D_VarChar;
case DbType.AnsiStringFixedLength: return D_Char;
case DbType.Binary: return D_VarBinary;
case DbType.Byte: return D_UnsignedTinyInt;
case DbType.Boolean: return D_Boolean;
case DbType.Currency: return D_Currency;
case DbType.Date: return D_DBDate;
case DbType.DateTime: return D_DBTimeStamp;
case DbType.Decimal: return D_Decimal;
case DbType.Double: return D_Double;
case DbType.Guid: return D_Guid;
case DbType.Int16: return D_SmallInt;
case DbType.Int32: return D_Integer;
case DbType.Int64: return D_BigInt;
case DbType.Object: return D_Variant;
case DbType.SByte: return D_TinyInt;
case DbType.Single: return D_Single;
case DbType.String: return D_VarWChar;
case DbType.StringFixedLength: return D_WChar;
case DbType.Time: return D_DBTime;
case DbType.UInt16: return D_UnsignedSmallInt;
case DbType.UInt32: return D_UnsignedInt;
case DbType.UInt64: return D_UnsignedBigInt;
case DbType.VarNumeric: return D_VarNumeric;
case DbType.Xml: return D_Xml;
default:
throw ADP.DbTypeNotSupported(dbType, typeof(OleDbType)); // MDAC 66009
}
}
static internal NativeDBType FromDBType(short dbType, bool isLong, bool isFixed) {
switch(dbType) {
//case EMPTY:
//case NULL:
case I2: return D_SmallInt;
case I4: return D_Integer;
case R4: return D_Single;
case R8: return D_Double;
case CY: return D_Currency;
case DATE: return D_Date;
case BSTR: return D_BSTR;
case IDISPATCH: return D_IDispatch;
case ERROR: return D_Error;
case BOOL: return D_Boolean;
case VARIANT: return D_Variant;
case IUNKNOWN: return D_IUnknown;
case DECIMAL: return D_Decimal;
case I1: return D_TinyInt;
case UI1: return D_UnsignedTinyInt;
case UI2: return D_UnsignedSmallInt;
case UI4: return D_UnsignedInt;
case I8: return D_BigInt;
case UI8: return D_UnsignedBigInt;
case FILETIME: return D_Filetime;
case GUID: return D_Guid;
case BYTES: return (isLong) ? D_LongVarBinary : (isFixed) ? D_Binary : D_VarBinary;
case STR: return (isLong) ? D_LongVarChar : (isFixed) ? D_Char : D_VarChar;
case WSTR: return (isLong) ? D_LongVarWChar : (isFixed) ? D_WChar : D_VarWChar;
case NUMERIC: return D_Numeric;
//case UDT:
case DBDATE: return D_DBDate;
case DBTIME: return D_DBTime;
case DBTIMESTAMP: return D_DBTimeStamp;
case HCHAPTER: return D_Chapter;
case PROPVARIANT: return D_PropVariant;
case VARNUMERIC: return D_VarNumeric;
case XML: return D_Xml;
case UDT: return D_Udt;
//case VECTOR:
//case ARRAY:
//case BYREF:
//case RESERVED:
default:
if (0 != (NativeDBType.VECTOR & dbType)) {
throw ODB.DBBindingGetVector();
}
return D_Variant; // MDAC 72067
}
}
}
}
| |
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Collections.Generic;
using System;
namespace UMA.Editors
{
[CustomEditor(typeof(RaceData))]
public class RaceInspector : Editor
{
[MenuItem("Assets/Create/UMA/Core/RaceData")]
public static void CreateRaceMenuItem()
{
CustomAssetUtility.CreateAsset<RaceData>();
}
protected RaceData race;
protected bool _needsUpdate;
protected string _errorMessage;
//we dont really want to use delayedFields because if the user does not change focus from the field in the inspector but instead selects another asset in their projects their changes dont save
//Instead what we really want to do is set a short delay on saving so that the asset doesn't save while the user is typing in a field
private float lastActionTime = 0;
private bool doSave = false;
//pRaceInspector needs to get unpacked UMATextRecipes so we might need a virtual UMAContextBase
GameObject EditorUMAContextBase;
#region DCS variables
private ReorderableList wardrobeSlotList;
private bool wardrobeSlotListInitialized = false;
private int compatibleRacePickerID;
static bool[] _BCFoldouts = new bool[0];
List<SlotData> baseSlotsList = new List<SlotData>();
List<string> baseSlotsNamesList = new List<string>();
#endregion
public void OnEnable() {
race = target as RaceData;
EditorApplication.update += DoDelayedSave;
}
void OnDestroy()
{
EditorApplication.update -= DoDelayedSave;
if (EditorUMAContextBase != null)
DestroyEditorUMAContextBase();
}
void DoDelayedSave()
{
if (doSave && Time.realtimeSinceStartup > (lastActionTime + 0.5f))
{
doSave = false;
lastActionTime = Time.realtimeSinceStartup;
EditorUtility.SetDirty(race);
AssetDatabase.SaveAssets();
UMAUpdateProcessor.UpdateRace(race);
}
}
private void DestroyEditorUMAContextBase()
{
if (EditorUMAContextBase != null)
{
foreach (Transform child in EditorUMAContextBase.transform)
{
DestroyImmediate(child.gameObject);
}
DestroyImmediate(EditorUMAContextBase);
}
}
public override void OnInspectorGUI()
{
if (lastActionTime == 0)
lastActionTime = Time.realtimeSinceStartup;
race.raceName = EditorGUILayout.TextField("Race Name", race.raceName);
race.umaTarget = (UMA.RaceData.UMATarget)EditorGUILayout.EnumPopup(new GUIContent("UMA Target", "The Mecanim animation rig type."), race.umaTarget);
race.genericRootMotionTransformName = EditorGUILayout.TextField("Root Motion Transform", race.genericRootMotionTransformName);
race.TPose = EditorGUILayout.ObjectField(new GUIContent("T-Pose", "The UMA T-Pose asset can be created by selecting the race fbx and choosing the Extract T-Pose dropdown. Only needs to be done once per race."), race.TPose, typeof(UmaTPose), false) as UmaTPose;
race.expressionSet = EditorGUILayout.ObjectField(new GUIContent("Expression Set", "The Expression Set asset is used by the Expression player."), race.expressionSet, typeof(UMA.PoseTools.UMAExpressionSet), false) as UMA.PoseTools.UMAExpressionSet;
EditorGUILayout.HelpBox("Fixup Rotations should be true for Blender FBX slots", MessageType.Info);
race.FixupRotations = EditorGUILayout.Toggle("Fixup Rotations",race.FixupRotations);
EditorGUILayout.Space();
SerializedProperty dnaConverterListprop = serializedObject.FindProperty("_dnaConverterList");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(dnaConverterListprop, true);
if(EditorGUI.EndChangeCheck()) {
serializedObject.ApplyModifiedProperties();
}
SerializedProperty dnaRanges = serializedObject.FindProperty("dnaRanges");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(dnaRanges, true);
if(EditorGUI.EndChangeCheck()) {
serializedObject.ApplyModifiedProperties();
}
foreach (var field in race.GetType().GetFields())
{
foreach (var attribute in System.Attribute.GetCustomAttributes(field))
{
if (attribute is UMAAssetFieldVisible)
{
SerializedProperty serializedProp = serializedObject.FindProperty(field.Name);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serializedProp);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
break;
}
}
}
try {
PreInspectorGUI(ref _needsUpdate);
if(_needsUpdate == true){
DoUpdate();
}
}catch (UMAResourceNotFoundException e){
_errorMessage = e.Message;
}
if (GUI.changed)
{
doSave = true;
lastActionTime = Time.realtimeSinceStartup;
}
}
/// <summary>
/// Add to this method in extender editors if you need to do anything extra when updating the data.
/// </summary>
protected virtual void DoUpdate() { }
#region DCS functions
// Drop area for Backwards Compatible Races
private void CompatibleRacesDropArea(Rect dropArea, SerializedProperty crossCompatibilitySettingsData)
{
Event evt = Event.current;
//make the box clickable so that the user can select raceData assets from the asset selection window
if (evt.type == EventType.MouseUp)
{
if (dropArea.Contains(evt.mousePosition))
{
compatibleRacePickerID = EditorGUIUtility.GetControlID(new GUIContent("crfObjectPicker"), FocusType.Passive);
EditorGUIUtility.ShowObjectPicker<RaceData>(null, false, "", compatibleRacePickerID);
Event.current.Use();//stops the Mismatched LayoutGroup errors
return;
}
}
if (evt.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == compatibleRacePickerID)
{
RaceData tempRaceDataAsset = EditorGUIUtility.GetObjectPickerObject() as RaceData;
if (tempRaceDataAsset)
{
AddRaceDataAsset(tempRaceDataAsset, crossCompatibilitySettingsData);
}
if (Event.current.type != EventType.Layout)
Event.current.Use();//stops the Mismatched LayoutGroup errors
return;
}
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
for (int i = 0; i < draggedObjects.Length; i++)
{
if (draggedObjects[i])
{
RaceData tempRaceDataAsset = draggedObjects[i] as RaceData;
if (tempRaceDataAsset)
{
AddRaceDataAsset(tempRaceDataAsset, crossCompatibilitySettingsData);
continue;
}
var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForAssets(path, crossCompatibilitySettingsData);
}
}
}
}
}
}
private void RecursiveScanFoldersForAssets(string path, SerializedProperty crossCompatibilitySettingsData)
{
var assetFiles = System.IO.Directory.GetFiles(path, "*.asset");
foreach (var assetFile in assetFiles)
{
var tempRaceDataAsset = AssetDatabase.LoadAssetAtPath(assetFile, typeof(RaceData)) as RaceData;
if (tempRaceDataAsset)
{
AddRaceDataAsset(tempRaceDataAsset, crossCompatibilitySettingsData);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'), crossCompatibilitySettingsData);
}
}
private void AddRaceDataAsset(RaceData raceDataAsset, SerializedProperty crossCompatibilitySettingsData)
{
if (raceDataAsset.raceName == serializedObject.FindProperty("raceName").stringValue)
return;
bool found = false;
for (int i = 0; i < crossCompatibilitySettingsData.arraySize; i++)
{
var ccRaceName = crossCompatibilitySettingsData.GetArrayElementAtIndex(i).FindPropertyRelative("ccRace").stringValue;
if (ccRaceName == raceDataAsset.raceName)
found = true;
}
if (!found)
{
crossCompatibilitySettingsData.InsertArrayElementAtIndex(crossCompatibilitySettingsData.arraySize);
crossCompatibilitySettingsData.GetArrayElementAtIndex(crossCompatibilitySettingsData.arraySize - 1).FindPropertyRelative("ccRace").stringValue = raceDataAsset.raceName;
serializedObject.ApplyModifiedProperties();
}
//if (!compatibleRaces.Contains(raceDataAsset.raceName))
// compatibleRaces.Add(raceDataAsset.raceName);
}
/// <summary>
/// Add to PreInspectorGUI in any derived editors to allow editing of new properties added to races.
/// </summary>
//partial void PreInspectorGUI(ref bool result);
protected virtual void PreInspectorGUI(ref bool result)
{
if (!wardrobeSlotListInitialized)
{
InitWardrobeSlotList();
}
result = AddExtraStuff();
}
private void InitWardrobeSlotList()
{
var thisWardrobeSlotList = serializedObject.FindProperty("wardrobeSlots");
if (thisWardrobeSlotList.arraySize == 0)
{
race.ValidateWardrobeSlots(true);
thisWardrobeSlotList = serializedObject.FindProperty("wardrobeSlots");
}
wardrobeSlotList = new ReorderableList(serializedObject, thisWardrobeSlotList, true, true, true, true);
wardrobeSlotList.drawHeaderCallback = (Rect rect) => {
EditorGUI.LabelField(rect, "Wardrobe Slots");
};
wardrobeSlotList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
var element = wardrobeSlotList.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2;
element.stringValue = EditorGUI.TextField(new Rect(rect.x + 10, rect.y, rect.width - 10, EditorGUIUtility.singleLineHeight), element.stringValue);
};
wardrobeSlotListInitialized = true;
}
public bool AddExtraStuff()
{
SerializedProperty baseRaceRecipe = serializedObject.FindProperty("baseRaceRecipe");
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(baseRaceRecipe, true);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
if (wardrobeSlotList == null)
{
InitWardrobeSlotList();
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
wardrobeSlotList.DoLayoutList();
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
if (!race.ValidateWardrobeSlots())
{
EditorUtility.SetDirty(race);
}
}
//new CrossCompatibilitySettings
//To push any old settings in RaceData.backwardsCompatibleWith into the new crossCompatibilitySettings we have to call GetCrossCompatibleRaces() directly on the target
#pragma warning disable 618
if (race.backwardsCompatibleWith.Count > 0)
{
var cc = race.GetCrossCompatibleRaces();
if (cc.Count > 0)
serializedObject.Update();
}
#pragma warning restore 618
SerializedProperty _crossCompatibilitySettings = serializedObject.FindProperty("_crossCompatibilitySettings");
SerializedProperty _crossCompatibilitySettingsData = _crossCompatibilitySettings.FindPropertyRelative("settingsData");
//draw the new version of the crossCompatibility list that allows users to define what slots in this races base recipe equate to in the backwards compatible races base recipe
_crossCompatibilitySettings.isExpanded = EditorGUILayout.Foldout(_crossCompatibilitySettings.isExpanded, "Cross Compatibility Settings");
if (_crossCompatibilitySettings.isExpanded)
{
//draw an info foldout
EditorGUI.indentLevel++;
_crossCompatibilitySettingsData.isExpanded = EditorGUILayout.Foldout(_crossCompatibilitySettingsData.isExpanded, "Help");
if (_crossCompatibilitySettingsData.isExpanded)
{
var helpText = "CrossCompatibilitySettings allows this race to wear wardrobe slots from another race, if this race has a wardrobe slot that the recipe is set to.";
helpText += " You can further configure the compatibility settings for each compatible race to define 'equivalent' slotdatas in the races' base recipes.";
helpText += " For example you could define that this races 'highpolyMaleChest' slotdata in its base recipe is equivalent to HumanMales 'MaleChest' slot data in its base recipe.";
helpText += " This would mean that any recipes which hid or applied an overlay to 'MaleChest' would hide or apply an overlay to 'highPolyMaleChest' on this race.";
helpText += " If 'Overlays Match' is unchecked then overlays in a recipe wont be applied.";
EditorGUILayout.HelpBox(helpText, MessageType.Info);
}
EditorGUI.indentLevel--;
if (baseRaceRecipe.objectReferenceValue != null)
{
Rect dropArea = new Rect();
dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea, "Drag cross compatible Races here. Click to pick.");
CompatibleRacesDropArea(dropArea, _crossCompatibilitySettingsData);
EditorGUILayout.Space();
//update the foldouts list if the dropbox changes anything
if (_BCFoldouts.Length != _crossCompatibilitySettingsData.arraySize)
{
Array.Resize<bool>(ref _BCFoldouts, _crossCompatibilitySettingsData.arraySize);
}
//we need an uptodate list of the slots in THIS races base recipe
baseSlotsList.Clear();
baseSlotsNamesList.Clear();
//editing a race will require a context too because we need to get the base recipes and their slots
if (UMAContextBase.Instance == null)
{
EditorUMAContextBase = UMAContextBase.CreateEditorContext();
}
UMAData.UMARecipe thisBaseRecipe = (baseRaceRecipe.objectReferenceValue as UMARecipeBase).GetCachedRecipe(UMAContextBase.Instance);
SlotData[] thisBaseSlots = thisBaseRecipe.GetAllSlots();
foreach (SlotData slot in thisBaseSlots)
{
if (slot != null)
{
baseSlotsList.Add(slot);
baseSlotsNamesList.Add(slot.slotName);
}
}
List<int> crossCompatibleSettingsToDelete = new List<int>();
//draw a foldout area for each compatible race that will show an entry for each slot in this races base recipe
//with a picker to choose the slot from the compatible race's base recipe that it equates to
for (int i = 0; i < _crossCompatibilitySettingsData.arraySize; i++)
{
bool del = false;
var thisCCSettings = _crossCompatibilitySettingsData.GetArrayElementAtIndex(i).FindPropertyRelative("ccSettings");
var ccRaceName = _crossCompatibilitySettingsData.GetArrayElementAtIndex(i).FindPropertyRelative("ccRace").stringValue;
//this could be missing- we should show that
var label = ccRaceName;
if (GetCompatibleRaceData(ccRaceName) == null)
label += " (missing)";
GUIHelper.FoldoutBar(ref _BCFoldouts[i], label, out del);
if (del)
{
crossCompatibleSettingsToDelete.Add(i);
}
if (_BCFoldouts[i])
{
DrawCCUI(ccRaceName, baseRaceRecipe, thisCCSettings);
}
}
if (crossCompatibleSettingsToDelete.Count > 0)
{
foreach (int del in crossCompatibleSettingsToDelete)
{
_crossCompatibilitySettingsData.DeleteArrayElementAtIndex(del);
serializedObject.ApplyModifiedProperties();
}
}
}
else
{
EditorGUILayout.HelpBox("Please define this races baseRaceRecipe before trying to define its cross compatibility settings.", MessageType.Info);
}
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serializedObject.FindProperty("raceThumbnails"), true);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
return false;
}
private RaceData GetCompatibleRaceData(string raceName)
{
RaceData foundRace = null;
string[] foundRacesStrings = AssetDatabase.FindAssets("t:RaceData");
for (int i = 0; i < foundRacesStrings.Length; i++)
{
RaceData thisFoundRace = AssetDatabase.LoadAssetAtPath<RaceData>(AssetDatabase.GUIDToAssetPath(foundRacesStrings[i]));
if (thisFoundRace.raceName == raceName)
{
foundRace = thisFoundRace;
break;
}
}
return foundRace;
}
private void DrawCCUI(string ccRaceName, SerializedProperty baseRaceRecipe, SerializedProperty thisCCSettings)
{
GUIHelper.BeginVerticalPadded(5, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.LabelField("Equivalent Slots with " + ccRaceName, EditorStyles.centeredGreyMiniLabel);
if (baseRaceRecipe.objectReferenceValue == null)
{
EditorGUILayout.HelpBox("Please set this Races 'Base Race Recipe' before trying to set equivalent Slots.", MessageType.Warning);
}
else
{
//we need to get the base raceRecipeSlots for this compatible race
var ccRaceData = GetCompatibleRaceData(ccRaceName);
if (ccRaceData != null)
{
if (ccRaceData.baseRaceRecipe == null)
{
EditorGUILayout.HelpBox("Please set " + ccRaceData.raceName + " Races 'Base Race Recipe' before trying to set equivalent Slots.", MessageType.Warning);
}
else
{
var ccSlotsList = new List<SlotData>();
var ccSlotsNamesList = new List<string>();
UMAData.UMARecipe ccBaseRecipe = ccRaceData.baseRaceRecipe.GetCachedRecipe(UMAContextBase.Instance);
SlotData[] ccBaseSlots = ccBaseRecipe.GetAllSlots();
foreach (SlotData slot in ccBaseSlots)
{
if (slot != null)
{
ccSlotsList.Add(slot);
ccSlotsNamesList.Add(slot.slotName);
}
}
//if that worked we can draw the UI for any set values and a button to add new ones
GUIHelper.BeginVerticalPadded(2, new Color(1f, 1f, 1f, 0.5f));
var headerRect = GUILayoutUtility.GetRect(0.0f, (EditorGUIUtility.singleLineHeight * 2), GUILayout.ExpandWidth(true));
var slotLabelRect = headerRect;
var gapRect = headerRect;
var cSlotLabelRect = headerRect;
var overlaysMatchLabelRect = headerRect;
var deleteRect = headerRect;
slotLabelRect.width = (headerRect.width - 50f - 22f - 22f) / 2;
gapRect.xMin = slotLabelRect.xMax;
gapRect.width = 22f;
cSlotLabelRect.xMin = gapRect.xMax;
cSlotLabelRect.width = slotLabelRect.width;
overlaysMatchLabelRect.xMin = cSlotLabelRect.xMax;
overlaysMatchLabelRect.width = 50f;
deleteRect.xMin = overlaysMatchLabelRect.xMax;
deleteRect.width = 22f;
//move this up
var tableHeaderStyle = EditorStyles.wordWrappedMiniLabel;
tableHeaderStyle.alignment = TextAnchor.MiddleCenter;
//we need a gui style for this that wraps the text and vertically centers it in the space
EditorGUI.LabelField(slotLabelRect, "This Races Slot", tableHeaderStyle);
EditorGUI.LabelField(gapRect, "", tableHeaderStyle);
EditorGUI.LabelField(cSlotLabelRect, "Compatible Races Slot", tableHeaderStyle);
EditorGUI.LabelField(overlaysMatchLabelRect, "Overlays Match", tableHeaderStyle);
GUIHelper.EndVerticalPadded(2);
GUIHelper.BeginVerticalPadded(2, new Color(0.75f, 0.875f, 1f));
if (thisCCSettings.arraySize > 0)
{
for (int ccsd = 0; ccsd < thisCCSettings.arraySize; ccsd++)
{
if (DrawCCUISetting(ccsd, thisCCSettings, ccSlotsNamesList))
serializedObject.ApplyModifiedProperties();
}
}
else
{
EditorGUILayout.LabelField("No equivalent slots defined", EditorStyles.miniLabel);
}
GUIHelper.EndVerticalPadded(2);
var addButtonRect = GUILayoutUtility.GetRect(0.0f, EditorGUIUtility.singleLineHeight, GUILayout.ExpandWidth(true));
addButtonRect.xMin = addButtonRect.xMax - 70f;
addButtonRect.width = 70f;
if (GUI.Button(addButtonRect, "Add"))
{
thisCCSettings.InsertArrayElementAtIndex(thisCCSettings.arraySize);
serializedObject.ApplyModifiedProperties();
}
}
}
else
{
EditorGUILayout.HelpBox("The cross compatible race " + ccRaceName + " could not be found!", MessageType.Warning);
}
}
GUIHelper.EndVerticalPadded(5);
}
private bool DrawCCUISetting(int ccsd, SerializedProperty thisCCSettings, List<string> ccSlotsNamesList)
{
var changed = false;
var startingRect = GUILayoutUtility.GetRect(0.0f, EditorGUIUtility.singleLineHeight, GUILayout.ExpandWidth(true));
var thisSlot = thisCCSettings.GetArrayElementAtIndex(ccsd).FindPropertyRelative("raceSlot").stringValue;
var thisSlotIndex = baseSlotsNamesList.IndexOf(thisSlot);
var thisCompatibleSlot = thisCCSettings.GetArrayElementAtIndex(ccsd).FindPropertyRelative("compatibleRaceSlot").stringValue;
var thisCompatibleSlotIndex = ccSlotsNamesList.IndexOf(thisCompatibleSlot);
var thisOverlaysMatch = thisCCSettings.GetArrayElementAtIndex(ccsd).FindPropertyRelative("overlaysMatch").boolValue;
var thisSlotRect = startingRect;
var thisEqualsLabelRect = startingRect;
var thisCompatibleSlotRect = startingRect;
//var thisOverlaysLabelRect = startingRect;
var thisOverlaysMatchRect = startingRect;
var thisDeleteRect = startingRect;
thisSlotRect.width = (startingRect.width - 50f - 22f - 22f) / 2;
thisEqualsLabelRect.xMin = thisSlotRect.xMax;
thisEqualsLabelRect.width = 22f;
thisCompatibleSlotRect.xMin = thisEqualsLabelRect.xMax;
thisCompatibleSlotRect.width = thisSlotRect.width;
thisOverlaysMatchRect.xMin = thisCompatibleSlotRect.xMax + 22f;
thisOverlaysMatchRect.width = 50f - 22f;
thisDeleteRect.xMin = thisOverlaysMatchRect.xMax;
thisDeleteRect.width = 22f;
EditorGUI.BeginChangeCheck();
var newSlotIndex = EditorGUI.Popup(thisSlotRect, "", thisSlotIndex, baseSlotsNamesList.ToArray());
if (EditorGUI.EndChangeCheck())
{
if (newSlotIndex != thisSlotIndex)
{
thisCCSettings.GetArrayElementAtIndex(ccsd).FindPropertyRelative("raceSlot").stringValue = baseSlotsNamesList[newSlotIndex];
changed = true;
}
}
EditorGUI.LabelField(thisEqualsLabelRect, "==");
EditorGUI.BeginChangeCheck();
var newCompatibleSlotIndex = EditorGUI.Popup(thisCompatibleSlotRect, "", thisCompatibleSlotIndex, ccSlotsNamesList.ToArray());
if (EditorGUI.EndChangeCheck())
{
if (newCompatibleSlotIndex != thisCompatibleSlotIndex)
{
thisCCSettings.GetArrayElementAtIndex(ccsd).FindPropertyRelative("compatibleRaceSlot").stringValue = ccSlotsNamesList[newCompatibleSlotIndex];
/*var ccSlotsOverlays = ccSlotsList[newCompatibleSlotIndex].GetOverlayList();
thisCCSettings.GetArrayElementAtIndex(ccsd).FindPropertyRelative("compatibleRaceSlotOverlays").arraySize = ccSlotsOverlays.Count;
for (int ccai = 0; ccai < ccSlotsOverlays.Count; ccai++)
thisCCSettings.GetArrayElementAtIndex(ccsd).FindPropertyRelative("compatibleRaceSlotOverlays").GetArrayElementAtIndex(ccai).stringValue = ccSlotsOverlays[ccai].overlayName;*/
changed = true;
}
}
//we need a gui style for this that centers this horizontally
EditorGUI.BeginChangeCheck();
var newOverlaysMatch = EditorGUI.ToggleLeft(thisOverlaysMatchRect, " ", thisOverlaysMatch);
if (EditorGUI.EndChangeCheck())
{
if (newOverlaysMatch != thisOverlaysMatch)
{
thisCCSettings.GetArrayElementAtIndex(ccsd).FindPropertyRelative("overlaysMatch").boolValue = newOverlaysMatch;
changed = true;
}
}
if (GUI.Button(thisDeleteRect, "X", EditorStyles.miniButton))
{
thisCCSettings.DeleteArrayElementAtIndex(ccsd);
changed = true;
}
//******NEEDS TO BE IN THE RETURN***//
//if (changed)
// serializedObject.ApplyModifiedProperties();
//GUILayout.EndHorizontal();
GUILayout.Space(2f);
return changed;
}
#endregion
}
}
#endif
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService
{
public CSharpCodeGenerationService(HostLanguageServices languageServices)
: base(languageServices.GetService<ISymbolDeclarationService>(),
languageServices.WorkspaceServices.Workspace)
{
}
public override CodeGenerationDestination GetDestination(SyntaxNode node)
{
return CSharpCodeGenerationHelpers.GetDestination(node);
}
protected override IComparer<SyntaxNode> GetMemberComparer()
=> CSharpDeclarationComparer.WithoutNamesInstance;
protected override AbstractImportsAdder CreateImportsAdder(
Document document)
{
return new UsingDirectivesAdder(document);
}
protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken)
{
if (destination is TypeDeclarationSyntax)
{
return GetInsertionIndices((TypeDeclarationSyntax)destination, cancellationToken);
}
// TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or
// compilation unit, if it overlaps a hidden region. We can consider relaxing that
// restriction in the future.
return null;
}
private IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken)
{
return destination.GetInsertionIndices(cancellationToken);
}
public override async Task<Document> AddEventAsync(
Solution solution, INamedTypeSymbol destination, IEventSymbol @event,
CodeGenerationOptions options, CancellationToken cancellationToken)
{
var newDocument = await base.AddEventAsync(
solution, destination, @event, options, cancellationToken).ConfigureAwait(false);
var namedType = @event.Type as INamedTypeSymbol;
if (namedType?.AssociatedSymbol != null)
{
// This is a VB event that declares its own type. i.e. "Public Event E(x As Object)"
// We also have to generate "public void delegate EEventHandler(object x)"
var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var newDestinationSymbol = destination.GetSymbolKey().Resolve(compilation).Symbol;
if (newDestinationSymbol?.ContainingType != null)
{
return await this.AddNamedTypeAsync(
newDocument.Project.Solution, newDestinationSymbol.ContainingType,
namedType, options, cancellationToken).ConfigureAwait(false);
}
else if (newDestinationSymbol?.ContainingNamespace != null)
{
return await this.AddNamedTypeAsync(
newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace,
namedType, options, cancellationToken).ConfigureAwait(false);
}
}
return newDocument;
}
protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices)
{
CheckDeclarationNode<TypeDeclarationSyntax>(destination);
return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices));
}
protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices)
{
CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination);
if (destination is EnumDeclarationSyntax)
{
return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options));
}
else if (destination is TypeDeclarationSyntax)
{
return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices));
}
else
{
return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices));
}
}
protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices)
{
CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, NamespaceDeclarationSyntax>(destination);
// Synthesized methods for properties/events are not things we actually generate
// declarations for.
if (method.AssociatedSymbol is IEventSymbol)
{
return destination;
}
if (method.AssociatedSymbol is IPropertySymbol)
{
// we will ignore the method if the associated property can be generated.
var property = (IPropertySymbol)method.AssociatedSymbol;
if (PropertyGenerator.CanBeGenerated(property))
{
return destination;
}
}
var typeDeclaration = destination as TypeDeclarationSyntax;
if (typeDeclaration != null)
{
if (method.IsConstructor())
{
return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo(
typeDeclaration, method, Workspace, options, availableIndices));
}
if (method.IsDestructor())
{
return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices));
}
if (method.MethodKind == MethodKind.Conversion)
{
return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo(
typeDeclaration, method, Workspace, options, availableIndices));
}
if (method.MethodKind == MethodKind.UserDefinedOperator)
{
return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo(
typeDeclaration, method, Workspace, options, availableIndices));
}
return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo(
typeDeclaration, method, Workspace, options, availableIndices));
}
if (method.IsConstructor() ||
method.IsDestructor())
{
return destination;
}
var compilationUnit = destination as CompilationUnitSyntax;
if (compilationUnit != null)
{
return Cast<TDeclarationNode>(
MethodGenerator.AddMethodTo(compilationUnit, method, Workspace, options, availableIndices));
}
var ns = Cast<NamespaceDeclarationSyntax>(destination);
return Cast<TDeclarationNode>(
MethodGenerator.AddMethodTo(ns, method, Workspace, options, availableIndices));
}
protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices)
{
CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination);
// Can't generate a property with parameters. So generate the setter/getter individually.
if (!PropertyGenerator.CanBeGenerated(property))
{
var members = new List<ISymbol>();
if (property.GetMethod != null)
{
var getMethod = property.GetMethod;
if (property is CodeGenerationSymbol)
{
foreach (var annotation in ((CodeGenerationSymbol)property).GetAnnotations())
{
getMethod = annotation.AddAnnotationToSymbol(getMethod);
}
}
members.Add(getMethod);
}
if (property.SetMethod != null)
{
var setMethod = property.SetMethod;
if (property is CodeGenerationSymbol)
{
foreach (var annotation in ((CodeGenerationSymbol)property).GetAnnotations())
{
setMethod = annotation.AddAnnotationToSymbol(setMethod);
}
}
members.Add(setMethod);
}
if (members.Count > 1)
{
options = CreateOptionsForMultipleMembers(options);
}
return AddMembers(destination, members, availableIndices, options, CancellationToken.None);
}
if (destination is TypeDeclarationSyntax)
{
return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo(
Cast<TypeDeclarationSyntax>(destination), property, Workspace, options, availableIndices));
}
else
{
return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo(
Cast<CompilationUnitSyntax>(destination), property, Workspace, options, availableIndices));
}
}
protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken)
{
CheckDeclarationNode<TypeDeclarationSyntax, NamespaceDeclarationSyntax, CompilationUnitSyntax>(destination);
if (destination is TypeDeclarationSyntax)
{
return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<TypeDeclarationSyntax>(destination), namedType, options, availableIndices, cancellationToken));
}
else if (destination is NamespaceDeclarationSyntax)
{
return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<NamespaceDeclarationSyntax>(destination), namedType, options, availableIndices, cancellationToken));
}
else
{
return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken));
}
}
protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken)
{
CheckDeclarationNode<CompilationUnitSyntax, NamespaceDeclarationSyntax>(destination);
if (destination is CompilationUnitSyntax)
{
return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<CompilationUnitSyntax>(destination), @namespace, options, availableIndices, cancellationToken));
}
else
{
return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<NamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken));
}
}
public override TDeclarationNode AddParameters<TDeclarationNode>(
TDeclarationNode destinationMember,
IEnumerable<IParameterSymbol> parameters,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
var memberDeclaration = destinationMember as MemberDeclarationSyntax;
if (memberDeclaration == null)
{
return destinationMember;
}
var currentParameterList = memberDeclaration.GetParameterList();
if (currentParameterList == null)
{
return destinationMember;
}
int currentParamsCount = currentParameterList.Parameters.Count;
bool seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null;
bool isFirstParam = currentParamsCount == 0;
var parameterNodesAndTokens = currentParameterList.Parameters.GetWithSeparators().ToList();
foreach (var parameter in parameters)
{
if (parameterNodesAndTokens.Count > 0 && parameterNodesAndTokens.Last().Kind() != SyntaxKind.CommaToken)
{
parameterNodesAndTokens.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
}
var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional);
parameterNodesAndTokens.Add(parameterSyntax);
isFirstParam = false;
seenOptional = seenOptional || parameterSyntax.Default != null;
}
var finalParameterList = currentParameterList.WithParameters(SyntaxFactory.SeparatedList<ParameterSyntax>(parameterNodesAndTokens));
var finalMember = memberDeclaration.WithParameterList(finalParameterList);
return Cast<TDeclarationNode>(finalMember);
}
public override TDeclarationNode AddAttributes<TDeclarationNode>(
TDeclarationNode destination,
IEnumerable<AttributeData> attributes,
SyntaxToken? target,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
if (target.HasValue && !target.Value.IsValidAttributeTarget())
{
throw new ArgumentException("target");
}
var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray();
// Handle all members including types.
var member = destination as MemberDeclarationSyntax;
if (member != null)
{
return Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList));
}
// Handle accessors
var accessor = destination as AccessorDeclarationSyntax;
if (accessor != null)
{
return Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList));
}
// Handle global attributes
var compilationUnit = destination as CompilationUnitSyntax;
if (compilationUnit != null)
{
return Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList));
}
// Handle parameters
var parameter = destination as ParameterSyntax;
if (parameter != null)
{
return Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList));
}
var typeParameter = destination as TypeParameterSyntax;
if (typeParameter != null)
{
return Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList));
}
return destination;
}
protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members)
{
CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, NamespaceDeclarationSyntax, CompilationUnitSyntax>(destination);
if (destination is EnumDeclarationSyntax)
{
return Cast<TDeclarationNode>(Cast<EnumDeclarationSyntax>(destination)
.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray()));
}
else if (destination is TypeDeclarationSyntax)
{
return Cast<TDeclarationNode>(Cast<TypeDeclarationSyntax>(destination)
.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray()));
}
else if (destination is NamespaceDeclarationSyntax)
{
return Cast<TDeclarationNode>(Cast<NamespaceDeclarationSyntax>(destination)
.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray()));
}
else
{
return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination)
.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray()));
}
}
public override TDeclarationNode RemoveAttribute<TDeclarationNode>(
TDeclarationNode destination,
AttributeData attributeToRemove,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
if (attributeToRemove.ApplicationSyntaxReference == null)
{
throw new ArgumentException("attributeToRemove");
}
var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken);
return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken);
}
public override TDeclarationNode RemoveAttribute<TDeclarationNode>(
TDeclarationNode destination,
SyntaxNode attributeToRemove,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
if (attributeToRemove == null)
{
throw new ArgumentException("attributeToRemove");
}
// Removed node could be AttributeSyntax or AttributeListSyntax.
int positionOfRemovedNode;
SyntaxTriviaList triviaOfRemovedNode;
// Handle all members including types.
var member = destination as MemberDeclarationSyntax;
if (member != null)
{
var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode);
var newMember = member.WithAttributeLists(newAttributeLists);
return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode));
}
// Handle accessors
var accessor = destination as AccessorDeclarationSyntax;
if (accessor != null)
{
var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode);
var newAccessor = accessor.WithAttributeLists(newAttributeLists);
return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode));
}
// Handle global attributes
var compilationUnit = destination as CompilationUnitSyntax;
if (compilationUnit != null)
{
var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode);
var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists);
return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode));
}
// Handle parameters
var parameter = destination as ParameterSyntax;
if (parameter != null)
{
var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode);
var newParameter = parameter.WithAttributeLists(newAttributeLists);
return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode));
}
var typeParameter = destination as TypeParameterSyntax;
if (typeParameter != null)
{
var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, options, out positionOfRemovedNode, out triviaOfRemovedNode);
var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists);
return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode));
}
return destination;
}
private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxNode attributeToRemove,
CodeGenerationOptions options,
out int positionOfRemovedNode,
out SyntaxTriviaList triviaOfRemovedNode)
{
foreach (var attributeList in attributeLists)
{
var attributes = attributeList.Attributes;
if (attributes.Contains(attributeToRemove))
{
IEnumerable<SyntaxTrivia> trivia;
IEnumerable<AttributeListSyntax> newAttributeLists;
if (attributes.Count == 1)
{
// Remove the entire attribute list.
ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia);
newAttributeLists = attributeLists.Where(aList => aList != attributeList);
}
else
{
// Remove just the given attribute from the attribute list.
ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia);
var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove));
var newAttributeList = attributeList.WithAttributes(newAttributes);
newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList);
}
triviaOfRemovedNode = trivia.ToSyntaxTriviaList();
return newAttributeLists.ToSyntaxList();
}
}
throw new ArgumentException("attributeToRemove");
}
public override TDeclarationNode AddStatements<TDeclarationNode>(
TDeclarationNode destinationMember,
IEnumerable<SyntaxNode> statements,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
var memberDeclaration = destinationMember as MemberDeclarationSyntax;
if (memberDeclaration != null)
{
return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration);
}
else
{
return AddStatementsWorker(destinationMember, statements, options, cancellationToken);
}
}
private TDeclarationNode AddStatementsWorker<TDeclarationNode>(
TDeclarationNode destinationMember,
IEnumerable<SyntaxNode> statements,
CodeGenerationOptions options,
CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode
{
var location = options.BestLocation;
CheckLocation<TDeclarationNode>(destinationMember, location);
var token = location.FindToken(cancellationToken);
var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault();
if (block != null)
{
var blockStatements = block.Statements.ToSet();
var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains);
var index = block.Statements.IndexOf(containingStatement);
var newStatements = statements.OfType<StatementSyntax>().ToArray();
BlockSyntax newBlock;
if (options.BeforeThisLocation != null)
{
var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia);
newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia);
newBlock = block.ReplaceNode(containingStatement, newContainingStatement);
newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements));
}
else
{
newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements));
}
return destinationMember.ReplaceNode(block, newBlock);
}
throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to);
}
private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode
{
var body = memberDeclaration.GetBody();
if (body == null)
{
return destinationMember;
}
var statementNodes = body.Statements.ToList();
statementNodes.AddRange(StatementGenerator.GenerateStatements(statements));
var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes));
var finalMember = memberDeclaration.WithBody(finalBody);
return Cast<TDeclarationNode>(finalMember);
}
public override SyntaxNode CreateEventDeclaration(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
return EventGenerator.GenerateEventDeclaration(@event, destination, options);
}
public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options)
{
return destination == CodeGenerationDestination.EnumType
? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options)
: (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, destination, options);
}
public override SyntaxNode CreateMethodDeclaration(
IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options)
{
// Synthesized methods for properties/events are not things we actually generate
// declarations for.
if (method.AssociatedSymbol is IEventSymbol)
{
return null;
}
if (method.AssociatedSymbol is IPropertySymbol)
{
// we will ignore the method if the associated property can be generated.
var property = (IPropertySymbol)method.AssociatedSymbol;
if (PropertyGenerator.CanBeGenerated(property))
{
return null;
}
}
if (method.IsConstructor())
{
return ConstructorGenerator.GenerateConstructorDeclaration(
method, destination, Workspace, options, options.ParseOptions);
}
else if (method.IsDestructor())
{
return DestructorGenerator.GenerateDestructorDeclaration(method, destination, options);
}
else if (method.IsUserDefinedOperator())
{
return OperatorGenerator.GenerateOperatorDeclaration(
method, destination, Workspace, options, options.ParseOptions);
}
else if (method.IsConversion())
{
return ConversionGenerator.GenerateConversionDeclaration(
method, destination, Workspace, options, options.ParseOptions);
}
else
{
return MethodGenerator.GenerateMethodDeclaration(
method, destination, Workspace, options, options.ParseOptions);
}
}
public override SyntaxNode CreatePropertyDeclaration(
IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options)
{
return PropertyGenerator.GeneratePropertyOrIndexer(
property, destination, Workspace, options, options.ParseOptions);
}
public override SyntaxNode CreateNamedTypeDeclaration(
INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken);
}
public override SyntaxNode CreateNamespaceDeclaration(
INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken)
{
return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken);
}
private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList, CodeGenerationOptions options, CancellationToken cancellationToken)
{
// Handle type declarations.
var typeDeclaration = declaration as BaseTypeDeclarationSyntax;
if (typeDeclaration != null)
{
return Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers)));
}
// Handle field declarations.
var fieldDeclaration = declaration as BaseFieldDeclarationSyntax;
if (fieldDeclaration != null)
{
return Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers)));
}
// Handle method declarations.
var methodDeclaration = declaration as BaseMethodDeclarationSyntax;
if (methodDeclaration != null)
{
return Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers)));
}
// Handle properties.
var propertyDeclaration = declaration as BasePropertyDeclarationSyntax;
if (propertyDeclaration != null)
{
return Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers)));
}
return declaration;
}
public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken)
{
Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList = (SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList();
return UpdateDeclarationModifiers(declaration, computeNewModifiersList, options, cancellationToken);
}
public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken)
{
Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList = (SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options);
return UpdateDeclarationModifiers(declaration, computeNewModifiersList, options, cancellationToken);
}
private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options)
{
var newModifierTokens = new List<SyntaxToken>();
CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable);
if (newModifierTokens.Count == 0)
{
return modifiersList;
}
return GetUpdatedDeclarationAccessibilityModifiers(newModifierTokens, modifiersList, (SyntaxToken modifier) => SyntaxFacts.IsAccessibilityModifier(modifier.Kind()))
.ToSyntaxTokenList();
}
public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken)
{
var syntaxNode = declaration as CSharpSyntaxNode;
if (syntaxNode == null)
{
return declaration;
}
TypeSyntax newTypeSyntax;
switch (syntaxNode.Kind())
{
case SyntaxKind.DelegateDeclaration:
// Handle delegate declarations.
var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia())
.WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia());
return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax));
case SyntaxKind.MethodDeclaration:
// Handle method declarations.
var methodDeclarationSyntax = declaration as MethodDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia())
.WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia());
return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax));
case SyntaxKind.OperatorDeclaration:
// Handle operator declarations.
var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia())
.WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia());
return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax));
case SyntaxKind.ConversionOperatorDeclaration:
// Handle conversion operator declarations.
var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia())
.WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia());
return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax));
case SyntaxKind.PropertyDeclaration:
// Handle properties.
var propertyDeclaration = declaration as PropertyDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia())
.WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia());
return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax));
case SyntaxKind.EventDeclaration:
// Handle events.
var eventDeclarationSyntax = declaration as EventDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia())
.WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia());
return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax));
case SyntaxKind.IndexerDeclaration:
// Handle indexers.
var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia())
.WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia());
return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax));
case SyntaxKind.Parameter:
// Handle parameters.
var parameterSyntax = declaration as ParameterSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia())
.WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia());
return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax));
case SyntaxKind.IncompleteMember:
// Handle incomplete members.
var incompleteMemberSyntax = declaration as IncompleteMemberSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia())
.WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia());
return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax));
case SyntaxKind.ArrayType:
// Handle array type.
var arrayTypeSyntax = declaration as ArrayTypeSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia())
.WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia());
return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax));
case SyntaxKind.PointerType:
// Handle pointer type.
var pointerTypeSyntax = declaration as PointerTypeSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia())
.WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia());
return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax));
case SyntaxKind.VariableDeclaration:
// Handle variable declarations.
var variableDeclarationSyntax = declaration as VariableDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia())
.WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia());
return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax));
case SyntaxKind.CatchDeclaration:
// Handle catch declarations.
var catchDeclarationSyntax = declaration as CatchDeclarationSyntax;
newTypeSyntax = newType.GenerateTypeSyntax()
.WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia())
.WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia());
return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax));
default:
return declaration;
}
}
public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
{
var memberDeclaration = declaration as MemberDeclarationSyntax;
if (memberDeclaration != null)
{
return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken));
}
var syntaxNode = declaration as CSharpSyntaxNode;
if (syntaxNode != null)
{
switch (syntaxNode.Kind())
{
case SyntaxKind.CompilationUnit:
case SyntaxKind.NamespaceDeclaration:
return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken));
}
}
return declaration;
}
}
}
| |
/*
* 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 NUnit.Framework;
using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer;
using Lucene.Net.Documents;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using TermFreqVector = Lucene.Net.Index.TermFreqVector;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using English = Lucene.Net.Util.English;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
/// <summary> </summary>
/// <version> $rcs = ' $Id: TestMultiThreadTermVectors.java 759556 2009-03-28 19:10:55Z mikemccand $ ' ;
/// </version>
[TestFixture]
public class TestMultiThreadTermVectors:LuceneTestCase
{
private RAMDirectory directory = new RAMDirectory();
public int numDocs = 100;
public int numThreads = 3;
[SetUp]
public override void SetUp()
{
base.SetUp();
IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
//writer.setUseCompoundFile(false);
//writer.infoStream = System.out;
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
Fieldable fld = new Field("field", English.IntToEnglish(i), Field.Store.YES, Field.Index.NOT_ANALYZED, Field.TermVector.YES);
doc.Add(fld);
writer.AddDocument(doc);
}
writer.Close();
}
[Test]
public virtual void Test()
{
IndexReader reader = null;
try
{
reader = IndexReader.Open(directory);
for (int i = 1; i <= numThreads; i++)
TestTermPositionVectors(reader, i);
}
catch (System.IO.IOException ioe)
{
Assert.Fail(ioe.Message);
}
finally
{
if (reader != null)
{
try
{
/** close the opened reader */
reader.Close();
}
catch (System.IO.IOException ioe)
{
System.Console.Error.WriteLine(ioe.StackTrace);
}
}
}
}
public virtual void TestTermPositionVectors(IndexReader reader, int threadCount)
{
MultiThreadTermVectorsReader[] mtr = new MultiThreadTermVectorsReader[threadCount];
for (int i = 0; i < threadCount; i++)
{
mtr[i] = new MultiThreadTermVectorsReader();
mtr[i].Init(reader);
}
/** run until all threads finished */
int threadsAlive = mtr.Length;
while (threadsAlive > 0)
{
//System.out.println("Threads alive");
System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 10));
threadsAlive = mtr.Length;
for (int i = 0; i < mtr.Length; i++)
{
if (mtr[i].IsAlive() == true)
{
break;
}
threadsAlive--;
}
}
long totalTime = 0L;
for (int i = 0; i < mtr.Length; i++)
{
totalTime += mtr[i].timeElapsed;
mtr[i] = null;
}
//System.out.println("threadcount: " + mtr.length + " average term vector time: " + totalTime/mtr.length);
}
}
class MultiThreadTermVectorsReader : IThreadRunnable
{
private IndexReader reader = null;
private SupportClass.ThreadClass t = null;
private int runsToDo = 100;
internal long timeElapsed = 0;
public virtual void Init(IndexReader reader)
{
this.reader = reader;
timeElapsed = 0;
t = new SupportClass.ThreadClass(new System.Threading.ThreadStart(this.Run));
t.Start();
}
public virtual bool IsAlive()
{
if (t == null)
return false;
return t.IsAlive;
}
public virtual void Run()
{
try
{
// run the test 100 times
for (int i = 0; i < runsToDo; i++)
TestTermVectors();
}
catch (System.Exception e)
{
System.Console.Error.WriteLine(e.StackTrace);
}
return ;
}
private void TestTermVectors()
{
// check:
int numDocs = reader.NumDocs();
long start = 0L;
for (int docId = 0; docId < numDocs; docId++)
{
start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
TermFreqVector[] vectors = reader.GetTermFreqVectors(docId);
timeElapsed += (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - start;
// verify vectors result
VerifyVectors(vectors, docId);
start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
TermFreqVector vector = reader.GetTermFreqVector(docId, "field");
timeElapsed += (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - start;
vectors = new TermFreqVector[1];
vectors[0] = vector;
VerifyVectors(vectors, docId);
}
}
private void VerifyVectors(TermFreqVector[] vectors, int num)
{
System.Text.StringBuilder temp = new System.Text.StringBuilder();
System.String[] terms = null;
for (int i = 0; i < vectors.Length; i++)
{
terms = vectors[i].GetTerms();
for (int z = 0; z < terms.Length; z++)
{
temp.Append(terms[z]);
}
}
if (!English.IntToEnglish(num).Trim().Equals(temp.ToString().Trim()))
System.Console.Out.WriteLine("wrong term result");
}
}
}
| |
// 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.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
namespace System.Diagnostics.Tests
{
public class ProcessTests : ProcessTestBase
{
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestBasePriorityOnWindows()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestBasePriorityOnUnix()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
DateTime timeBeforeProcessStart = DateTime.UtcNow;
Process p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart, "TestExitTime is incorrect.");
}
[Fact]
public void TestId()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunner).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void TestMachineName()
{
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact, PlatformSpecific(~PlatformID.OSX)]
public void TestMainModuleOnNonOSX()
{
string fileName = "corerun";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
fileName = "CoreRun.exe";
Process p = Process.GetCurrentProcess();
Assert.True(p.Modules.Count > 0);
Assert.Equal(fileName, p.MainModule.ModuleName);
Assert.EndsWith(fileName, p.MainModule.FileName);
Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString());
}
[Fact]
public void TestMaxWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestMinWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotEqual(IntPtr.Zero, pModule.BaseAddress);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr addr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
public void TestNonpagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void TestPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void TestPagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void TestPeakPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void TestPeakVirtualMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void TestPeakWorkingSet64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void TestPrivateMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void TestVirtualMemorySize64()
{
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void TestWorkingSet64()
{
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void TestProcessorTime()
{
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact, ActiveIssue(3037)]
public void TestProcessStartTime()
{
DateTime timeBeforeCreatingProcess = DateTime.UtcNow;
Process p = CreateProcessLong();
Assert.Throws<InvalidOperationException>(() => p.StartTime);
try
{
p.Start();
// Time in unix, is measured in jiffies, which is incremented by one for every timer interrupt since the boot time.
// Thus, because there are HZ timer interrupts in a second, there are HZ jiffies in a second. Hence 1\HZ, will
// be the resolution of system timer. The lowest value of HZ on unix is 100, hence the timer resolution is 10 ms.
// On Windows, timer resolution is 15 ms from MSDN DateTime.Now. Hence, allowing error in 15ms [max(10,15)].
long intervalTicks = new TimeSpan(0, 0, 0, 0, 15).Ticks;
long beforeTicks = timeBeforeCreatingProcess.Ticks - intervalTicks;
try
{
// Ensure the process has started, p.id throws InvalidOperationException, if the process has not yet started.
Assert.Equal(p.Id, Process.GetProcessById(p.Id).Id);
long startTicks = p.StartTime.ToUniversalTime().Ticks;
long afterTicks = DateTime.UtcNow.Ticks + intervalTicks;
Assert.InRange(startTicks, beforeTicks, afterTicks);
}
catch (InvalidOperationException)
{
Assert.True(p.StartTime.ToUniversalTime().Ticks > beforeTicks);
}
}
finally
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
[Fact]
[PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestPriorityClassUnix()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestPriorityClassWindows()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact]
public void TestInvalidPriorityClass()
{
Process p = new Process();
Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; });
}
[Fact]
public void TestProcessName()
{
Assert.Equal(_process.ProcessName, HostRunner, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void TestSafeHandle()
{
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void TestSessionId()
{
uint sessionId;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
}
else
{
sessionId = (uint)Interop.getsid(_process.Id);
}
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
Interop.GetCurrentProcessId() :
Interop.getpid();
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
public void TestGetProcessById()
{
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void TestGetProcessesByName()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "TestGetProcessesByName001 failed");
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "TestGetProcessesByName001 failed");
}
public static IEnumerable<object[]> GetTestProcess()
{
Process currentProcess = Process.GetCurrentProcess();
yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") };
yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() };
}
[Theory, PlatformSpecific(PlatformID.Windows)]
[MemberData("GetTestProcess")]
public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess)
{
Assert.Equal(currentProcess.Id, remoteProcess.Id);
Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
[Fact, PlatformSpecific(PlatformID.AnyUnix)]
public void TestProcessOnRemoteMachineUnix()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1"));
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1"));
}
[Fact]
public void TestStartInfo()
{
{
Process process = CreateProcessLong();
process.Start();
Assert.Equal(HostRunner, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = CreateProcessLong();
process.Start();
Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo()));
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = new Process();
process.StartInfo = new ProcessStartInfo(TestConsoleApp);
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
{
Process process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
{
Process process = Process.GetCurrentProcess();
Assert.Throws<System.InvalidOperationException>(() => process.StartInfo);
}
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCPRPT
{
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// Implementation for MS_OXCPRPTAdapter for stream operations
/// </summary>
public partial class MS_OXCPRPTAdapter : ManagedAdapterBase, IMS_OXCPRPTAdapter
{
/// <summary>
/// This ROP opens a property for streaming access.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="openStreamResponse">The response of this ROP.</param>
/// <param name="tag">The propertyTag structure.</param>
/// <param name="openMode">8-bit flags structure. These flags control how the stream is opened.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The handle returned.</returns>
private uint RopOpenStream(uint objHandle, out RopOpenStreamResponse openStreamResponse, PropertyTag tag, byte openMode, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopOpenStreamRequest openStreamRequest;
openStreamRequest.RopId = (byte)RopId.RopOpenStream;
openStreamRequest.LogonId = LogonId;
openStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
openStreamRequest.OutputHandleIndex = (byte)HandleIndex.SecondIndex;
openStreamRequest.PropertyTag = tag;
openStreamRequest.OpenModeFlags = openMode;
this.responseSOHsValue = this.ProcessSingleRop(openStreamRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
openStreamResponse = (RopOpenStreamResponse)this.responseValue;
uint streamObjectHandle = this.responseSOHsValue[0][openStreamResponse.OutputHandleIndex];
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, openStreamResponse.ReturnValue, string.Format("RopOpenStream Failed! Error: 0x{0:X8}", openStreamResponse.ReturnValue));
}
return streamObjectHandle;
}
/// <summary>
/// This ROP reads bytes from a stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="byteCount">The maximum number of bytes to read if the value is not equal to 0xBABE.</param>
/// <param name="maximumByteCount">The maximum number of bytes to read if the value of the ByteCount field is equal to 0xBABE.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopReadStreamResponse RopReadStream(uint objHandle, ushort byteCount, uint maximumByteCount, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopReadStreamRequest readStreamRequest;
RopReadStreamResponse readStreamResponse;
readStreamRequest.RopId = (byte)RopId.RopReadStream;
readStreamRequest.LogonId = LogonId;
readStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
readStreamRequest.ByteCount = byteCount;
readStreamRequest.MaximumByteCount = maximumByteCount;
this.responseSOHsValue = this.ProcessSingleRop(readStreamRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
readStreamResponse = (RopReadStreamResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, readStreamResponse.ReturnValue, string.Format("RopReadStream failed! Error: 0x{0:X8}", readStreamResponse.ReturnValue));
}
return readStreamResponse;
}
/// <summary>
/// This ROP writes bytes to a stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="writeData">These values specify the data how to be written to the stream.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopWriteStreamResponse RopWriteStream(uint objHandle, string writeData, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopWriteStreamRequest writeStreamRequest;
RopWriteStreamResponse writeStreamResponse;
writeStreamRequest.RopId = (byte)RopId.RopWriteStream;
writeStreamRequest.LogonId = LogonId;
writeStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
byte[] data = Encoding.ASCII.GetBytes(writeData);
writeStreamRequest.DataSize = (ushort)data.Length;
writeStreamRequest.Data = data;
this.responseSOHsValue = this.ProcessSingleRop(writeStreamRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
writeStreamResponse = (RopWriteStreamResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, writeStreamResponse.ReturnValue, string.Format("RopWriteStream failed! Error: 0x{0:X8}", writeStreamResponse.ReturnValue));
}
return writeStreamResponse;
}
/// <summary>
/// This ROP writes bytes to a stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="writeData">These values specify the data how to be written to the stream.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopWriteStreamExtendedResponse RopWriteStreamExtended(uint objHandle, string writeData, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopWriteStreamExtendedRequest writeStreamExtendedRequest;
RopWriteStreamExtendedResponse writeStreamExtendedResponse;
writeStreamExtendedRequest.RopId = (byte)RopId.RopWriteStreamExtended;
writeStreamExtendedRequest.LogonId = LogonId;
writeStreamExtendedRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
byte[] data = Encoding.ASCII.GetBytes(writeData);
writeStreamExtendedRequest.DataSize = (ushort)data.Length;
writeStreamExtendedRequest.Data = data;
this.responseSOHsValue = this.ProcessSingleRop(writeStreamExtendedRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
writeStreamExtendedResponse = (RopWriteStreamExtendedResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, writeStreamExtendedResponse.ReturnValue, string.Format("RopWriteStream failed! Error: 0x{0:X8}", writeStreamExtendedResponse.ReturnValue));
}
return writeStreamExtendedResponse;
}
/// <summary>
/// This ROP commits stream operations.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopCommitStreamResponse RopCommitStream(uint objHandle, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopCommitStreamRequest commitStreamRequest;
RopCommitStreamResponse commitStreamResponse;
commitStreamRequest.RopId = (byte)RopId.RopCommitStream;
commitStreamRequest.LogonId = LogonId;
commitStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
this.responseSOHsValue = this.ProcessSingleRop(commitStreamRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
commitStreamResponse = (RopCommitStreamResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, commitStreamResponse.ReturnValue, string.Format("RopCommitStream failed! Error: 0x{0:X8}", commitStreamResponse.ReturnValue));
}
return commitStreamResponse;
}
/// <summary>
/// This ROP gets the size of a stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopGetStreamSizeResponse RopGetStreamSize(uint objHandle, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopGetStreamSizeRequest getStreamSizeRequest;
RopGetStreamSizeResponse getStreamSizeResponse;
getStreamSizeRequest.RopId = (byte)RopId.RopGetStreamSize;
getStreamSizeRequest.LogonId = LogonId;
getStreamSizeRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
this.responseSOHsValue = this.ProcessSingleRop(getStreamSizeRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
getStreamSizeResponse = (RopGetStreamSizeResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, getStreamSizeResponse.ReturnValue, string.Format("RopGetStreamSize failed! Error: 0x{0:X8}", getStreamSizeResponse.ReturnValue));
}
return getStreamSizeResponse;
}
/// <summary>
/// This ROP sets the size of a stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="streamSize">The size of the stream.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopSetStreamSizeResponse RopSetStreamSize(uint objHandle, ulong streamSize, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopSetStreamSizeRequest setStreamSizeRequest;
RopSetStreamSizeResponse setStreamSizeResponse;
setStreamSizeRequest.RopId = (byte)RopId.RopSetStreamSize;
setStreamSizeRequest.LogonId = LogonId;
setStreamSizeRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
setStreamSizeRequest.StreamSize = streamSize;
this.responseSOHsValue = this.ProcessSingleRop(setStreamSizeRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
setStreamSizeResponse = (RopSetStreamSizeResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, setStreamSizeResponse.ReturnValue, string.Format("RopSetStreamSize failed! Error: 0x{0:X8}", setStreamSizeResponse.ReturnValue));
}
return setStreamSizeResponse;
}
/// <summary>
/// This ROP seeks to a specific offset within a stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="origin">The origin location for the seek operation.</param>
/// <param name="offset">The seek offset for the seek operation.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopSeekStreamResponse RopSeekStream(uint objHandle, byte origin, long offset, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopSeekStreamRequest seekStreamRequest;
RopSeekStreamResponse seekStreamResponse;
seekStreamRequest.RopId = (byte)RopId.RopSeekStream;
seekStreamRequest.LogonId = LogonId;
seekStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
seekStreamRequest.Origin = origin;
seekStreamRequest.Offset = (ulong)offset;
this.responseSOHsValue = this.ProcessSingleRop(seekStreamRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
seekStreamResponse = (RopSeekStreamResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, seekStreamResponse.ReturnValue, string.Format("RopSeekStream failed! Error: 0x{0:X8}", seekStreamResponse.ReturnValue));
}
return seekStreamResponse;
}
/// <summary>
/// This ROP copies a number of bytes from a source stream to a destination stream.
/// </summary>
/// <param name="sourceHandle">The source handle to copy.</param>
/// <param name="destHandle">The destination handle to be copied.</param>
/// <param name="sourceHandleIndex">The source object stored location index in Server object handle table.</param>
/// <param name="destHandleIndex">This destination object stored location index in the Server object handle table.</param>
/// <param name="byteCount">The number of bytes to be copied.</param>
/// <returns>The response of this ROP.</returns>
private RopCopyToStreamResponse RopCopyToStream(uint sourceHandle, uint destHandle, byte sourceHandleIndex, byte destHandleIndex, ulong byteCount)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopCopyToStreamRequest copyToStreamRequest;
RopCopyToStreamResponse copyToStreamResponse;
copyToStreamRequest.RopId = (byte)RopId.RopCopyToStream;
copyToStreamRequest.LogonId = LogonId;
copyToStreamRequest.SourceHandleIndex = sourceHandleIndex;
copyToStreamRequest.DestHandleIndex = destHandleIndex;
copyToStreamRequest.ByteCount = byteCount;
List<uint> handleList = new List<uint>
{
sourceHandle, destHandle
};
this.responseSOHsValue = this.ProcessSingleRopWithMutipleServerObjects(copyToStreamRequest, handleList, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
copyToStreamResponse = (RopCopyToStreamResponse)this.responseValue;
return copyToStreamResponse;
}
/// <summary>
/// This ROP locks a specified range of bytes in a stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="regionOffset">The byte location in the stream where the region begins.</param>
/// <param name="regionSize">The size of the region, in bytes.</param>
/// <param name="lockFlags">The flags specified the behavior of the lock operation.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopLockRegionStreamResponse RopLockRegionStream(uint objHandle, ulong regionOffset, ulong regionSize, uint lockFlags, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopLockRegionStreamRequest lockRegionStreamRequest;
RopLockRegionStreamResponse lockRegionStreamResponse;
lockRegionStreamRequest.RopId = (byte)RopId.RopLockRegionStream;
lockRegionStreamRequest.LogonId = LogonId;
lockRegionStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
lockRegionStreamRequest.RegionOffset = regionOffset;
lockRegionStreamRequest.RegionSize = regionSize;
lockRegionStreamRequest.LockFlags = lockFlags;
this.responseSOHsValue = this.ProcessSingleRop(lockRegionStreamRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
lockRegionStreamResponse = (RopLockRegionStreamResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, lockRegionStreamResponse.ReturnValue, string.Format("RopLockRegionStream failed! Error: 0x{0:X8}", lockRegionStreamResponse.ReturnValue));
}
return lockRegionStreamResponse;
}
/// <summary>
/// This ROP unlocks a specified range of bytes in a stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="regionOffset">The byte location in the stream where the region begins.</param>
/// <param name="regionSize">The size of the region in bytes.</param>
/// <param name="lockFlags">The flag specified the behavior of the lock operation.</param>
/// <returns>The response of this ROP.</returns>
private RopUnlockRegionStreamResponse RopUnlockRegionStream(uint objHandle, ulong regionOffset, ulong regionSize, uint lockFlags)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopUnlockRegionStreamRequest unlockRegionStreamRequest;
RopUnlockRegionStreamResponse unlockRegionStreamResponse;
unlockRegionStreamRequest.RopId = (byte)RopId.RopUnlockRegionStream;
unlockRegionStreamRequest.LogonId = LogonId;
unlockRegionStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
unlockRegionStreamRequest.RegionOffset = regionOffset;
unlockRegionStreamRequest.RegionSize = regionSize;
unlockRegionStreamRequest.LockFlags = lockFlags;
this.responseSOHsValue = this.ProcessSingleRop(unlockRegionStreamRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
unlockRegionStreamResponse = (RopUnlockRegionStreamResponse)this.responseValue;
return unlockRegionStreamResponse;
}
/// <summary>
/// This ROP writes bytes to a stream and commits the stream.
/// </summary>
/// <param name="objHandle">The handle to operate.</param>
/// <param name="writeData">The data to be written to the stream.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopWriteStreamResponse RopWriteAndCommitStream(uint objHandle, string writeData, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopWriteAndCommitStreamRequest writeAndCommitStreamRequest;
RopWriteStreamResponse writeAndCommitStreamResponse;
writeAndCommitStreamRequest.RopId = (byte)RopId.RopWriteAndCommitStream;
writeAndCommitStreamRequest.LogonId = LogonId;
writeAndCommitStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
byte[] data = Encoding.ASCII.GetBytes(writeData);
writeAndCommitStreamRequest.DataSize = (ushort)data.Length;
writeAndCommitStreamRequest.Data = data;
this.responseSOHsValue = this.ProcessSingleRop(writeAndCommitStreamRequest, objHandle, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
writeAndCommitStreamResponse = (RopWriteStreamResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, writeAndCommitStreamResponse.ReturnValue, string.Format("RopWriteAndCommitStream failed! Error: 0x{0:X8}", writeAndCommitStreamResponse.ReturnValue));
}
return writeAndCommitStreamResponse;
}
/// <summary>
/// This ROP creates a new stream object based on the same data as another stream.
/// </summary>
/// <param name="sourceHandle">The source handle.</param>
/// <param name="destHandle">The destination handle.</param>
/// <param name="needVerify">Whether need to verify the response.</param>
/// <returns>The response of this ROP.</returns>
private RopCloneStreamResponse RopCloneStream(uint sourceHandle, uint destHandle, bool needVerify)
{
this.rawDataValue = null;
this.responseValue = null;
this.responseSOHsValue = null;
RopCloneStreamRequest cloneStreamRequest;
RopCloneStreamResponse cloneStreamResponse;
cloneStreamRequest.RopId = (byte)RopId.RopCloneStream;
cloneStreamRequest.LogonId = LogonId;
cloneStreamRequest.InputHandleIndex = (byte)HandleIndex.FirstIndex;
cloneStreamRequest.OutputHandleIndex = (byte)HandleIndex.SecondIndex;
List<uint> handleList = new List<uint>
{
sourceHandle, destHandle
};
this.responseSOHsValue = this.ProcessSingleRopWithMutipleServerObjects(cloneStreamRequest, handleList, ref this.responseValue, ref this.rawDataValue, RopResponseType.SuccessResponse);
cloneStreamResponse = (RopCloneStreamResponse)this.responseValue;
if (needVerify)
{
this.Site.Assert.AreEqual((uint)RopResponseType.SuccessResponse, cloneStreamResponse.ReturnValue, string.Format("RopCloneStream failed! Error: 0x{0:X8}", cloneStreamResponse.ReturnValue));
}
return cloneStreamResponse;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using IxMilia.BCad.Collections;
using IxMilia.BCad.Entities;
using IxMilia.BCad.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace IxMilia.BCad.FileHandlers
{
public partial class JsonFileHandler : IFileHandler
{
private JsonSerializerSettings Settings = new JsonSerializerSettings() { Converters = { new JsonEntityConverter() } };
public object GetFileSettingsFromDrawing(Drawing drawing)
{
return null;
}
public bool ReadDrawing(string fileName, Stream fileStream, out Drawing drawing, out ViewPort viewPort)
{
ReadOnlyTree<string, Layer> layers = null;
using (var reader = new StreamReader(fileStream, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
{
var json = reader.ReadToEnd();
var jsonDrawing = JsonConvert.DeserializeObject<JsonDrawing>(json, Settings);
var layerList = new List<Layer>();
foreach (var jsonLayer in jsonDrawing.Floorplan.Layers)
{
var layer = new Layer(jsonLayer.Name, color: CadColor.FromArgb(255, jsonLayer.R, jsonLayer.G, jsonLayer.B));
layerList.Add(layer);
}
layers = ReadOnlyTree<string, Layer>.FromEnumerable(layerList, l => l.Name);
void AddEntityToLayer(string layerName, Entity entity)
{
var layer = layers.GetValue(layerName);
layer = layer.Add(entity);
layers = layers.Insert(layerName, layer);
}
foreach (var block in jsonDrawing.Floorplan.Blocks)
{
switch (block.Name.ToUpperInvariant())
{
case "*MODEL_SPACE":
foreach (var jsonEntity in block.Entities)
{
switch (jsonEntity)
{
case JsonArc jsonArc:
var arc = new Arc(jsonArc.Center, jsonArc.Radius, jsonArc.StartAngle * MathHelper.RadiansToDegrees, jsonArc.EndAngle * MathHelper.RadiansToDegrees, Vector.ZAxis);
AddEntityToLayer(jsonEntity.Layer, arc);
break;
case JsonLine jsonLine:
for (int i = 0; i < jsonLine.Points.Count - 1; i++)
{
AddEntityToLayer(jsonEntity.Layer, new Line(jsonLine.Points[i], jsonLine.Points[i + 1]));
}
if (jsonLine.Points.Count > 2)
{
AddEntityToLayer(jsonEntity.Layer, new Line(jsonLine.Points.Last(), jsonLine.Points.First()));
}
break;
default:
break;
}
}
break;
// TODO: handle other blocks?
}
}
}
drawing = new Drawing().Update(layers: layers);
viewPort = null; // auto-generate later
return true;
}
public bool WriteDrawing(string fileName, Stream fileStream, Drawing drawing, ViewPort viewPort, object fileSettings)
{
var jsonDrawing = new JsonDrawing();
var modelSpace = new JsonBlock() { Name = "*Model_Space" };
jsonDrawing.Floorplan.Blocks.Add(modelSpace);
foreach (var layer in drawing.GetLayers())
{
var jsonLayer = new JsonLayer()
{
Name = layer.Name,
R = layer.Color?.R ?? 0,
G = layer.Color?.G ?? 0,
B = layer.Color?.B ?? 0,
};
jsonDrawing.Floorplan.Layers.Add(jsonLayer);
foreach (var entity in layer.GetEntities())
{
switch (entity.Kind)
{
case EntityKind.Arc:
var arc = (Arc)entity;
var jsonArc = new JsonArc()
{
Layer = layer.Name,
Center = arc.Center,
Radius = arc.Radius,
StartAngle = arc.StartAngle * MathHelper.DegreesToRadians,
EndAngle = arc.EndAngle * MathHelper.DegreesToRadians
};
modelSpace.Entities.Add(jsonArc);
break;
case EntityKind.Line:
var line = (Line)entity;
var jsonLine = new JsonLine() { Layer = layer.Name };
jsonLine.Points.Add(line.P1);
jsonLine.Points.Add(line.P2);
modelSpace.Entities.Add(jsonLine);
break;
}
}
foreach (var jsonEntity in modelSpace.Entities)
{
jsonEntity.BeforeWrite();
}
}
var json = JsonConvert.SerializeObject(jsonDrawing, Settings);
using (var writer = new StreamWriter(fileStream, encoding: Encoding.UTF8, bufferSize: 1024, leaveOpen: true))
{
writer.Write(json);
}
return true;
}
private class JsonEntityConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(JsonEntity);
}
public override bool CanWrite => true;
public override bool CanRead => true;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jo = JObject.Load(reader);
var typeString = (string)jo["t"];
JsonEntity entity;
switch (typeString)
{
case "A":
entity = jo.ToObject<JsonArc>(serializer);
break;
case "B":
// example:
// {
// "t": "B",
// "h": "7D84",
// "p": "1F",
// "l": "S-GRID-IDEN-EXST",
// "c": {
// "t": "L"
// },
// "b": "4216",
// "d": "4557.99999600003,2281.88345914876;96;96;0",
// "atts": [
// {}
// ]
// }
entity = null;
break;
case "C":
// example:
// {
// "t": "C",
// "h": "CDE7",
// "p": "1F",
// "l": "A-FURN-FREE-EXST",
// "c": {
// "t": "L"
// },
// "sents": [
// {
// "t": "P",
// "d": "5129.17346025466,2638.33635654058;5129.15750822654,2638.56059957781;0.00398172573236266"
// },
// {
// "t": "P",
// "d": "5129.15750822654,2638.56059957781;5129.11313297802,2638.77062202288;0.00355658289033234"
// },
// {
// "t": "P",
// "d": "5129.11313297802,2638.77062202288;5128.98882765085,2639.08644509474;0.00845993397036615"
// },
// {
// "t": "P",
// "d": "5128.98882765085,2639.08644509474;5128.7990407962,2639.38302813977;0.00831280783924693"
// },
// {
// "t": "P",
// "d": "5128.7990407962,2639.38302813977;5128.51404775427,2639.68132566635;0.0101618318638597"
// },
// {
// "t": "P",
// "d": "5128.51404775427,2639.68132566635;5128.12951303121,2639.95077986862;0.0115510842690671"
// },
// {
// "t": "P",
// "d": "5128.12951303121,2639.95077986862;5127.48432163509,2640.21199647146;0.0221325367753984"
// },
// {
// "t": "P",
// "d": "5127.48432163509,2640.21199647146;5126.70551727018,2640.31293966962;0.0255343910578292"
// },
// {
// "t": "P",
// "d": "5126.70551727018,2640.31293966962;5125.92673419451,2640.21183122829;0.0255344078661228"
// },
// {
// "t": "P",
// "d": "5125.92673419451,2640.21183122829;5125.28159800999,2639.95047749287;0.0221325749904388"
// },
// {
// "t": "P",
// "d": "5125.28159800999,2639.95047749287;5124.89712043488,2639.68094137149;0.0115511099028788"
// },
// {
// "t": "P",
// "d": "5124.89712043488,2639.68094137149;5124.61219085276,2639.38258301195;0.0101618546467232"
// },
// {
// "t": "P",
// "d": "5124.61219085276,2639.38258301195;5124.42246725259,2639.08595939151;0.00831282405976297"
// },
// {
// "t": "P",
// "d": "5124.42246725259,2639.08595939151;5124.2982360552,2638.7701333738;0.00845870127787784"
// },
// {
// "t": "P",
// "d": "5124.2982360552,2638.7701333738;5124.25389907874,2638.56007776809;0.00355739311568803"
// },
// {
// "t": "P",
// "d": "5124.25389907874,2638.56007776809;5124.23799502949,2638.33583635003;0.00398154844077303"
// }
// ]
// }
entity = null;
break;
case "F":
// example:
// {
// "t": "F",
// "h": "3AA4",
// "p": "3A9F",
// "l": "0",
// "c": {
// "t": "C",
// "r": "102",
// "g": "204",
// "b": "204"
// },
// "loops": [
// [
// {
// "t": "L",
// "d": "7.75000536403203,5.0000188823324|7.75000536403203,-4.99998107575811"
// },
// {
// "t": "L",
// "d": "7.75000536403203,0|18.5,0"
// }
// ]
// ]
// }
entity = null;
break;
case "L":
entity = jo.ToObject<JsonLine>(serializer);
break;
default:
entity = null;
break;
}
entity?.AfterParse();
return entity;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Text;
using Sandbox.ModAPI;
using VRage.Utils;
using VRage.Game;
using Sandbox.Definitions;
using Sandbox.Common.ObjectBuilders;
using VRage.ModAPI;
using Sandbox.Game.Entities;
using VRage.Game.ModAPI;
using VRageMath;
using NaniteConstructionSystem.Extensions;
using NaniteConstructionSystem.Settings;
namespace NaniteConstructionSystem.Entities
{
public class NaniteConstructionManagerSync
{
private bool m_init;
public NaniteConstructionManagerSync()
{
m_init = false;
}
public void Initialize()
{
if (!Sync.IsServer) // Client, why do I have to be so difficult
{
MyAPIGateway.Multiplayer.RegisterMessageHandler(8950, HandleUpdateState);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8951, HandleAddTarget);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8952, HandleCompleteTarget);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8953, HandleCancelTarget);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8954, HandleDetails);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8956, HandleSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8958, HandleStartParticle);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8959, HandleRemoveParticle);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8960, HandleTerminalSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8962, HandleAssemblerSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8966, HandleHammerTerminalSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8969, HandleVoxelRemoval);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8971, HandleBeaconTerminalSettings);
}
else
{
MyAPIGateway.Multiplayer.RegisterMessageHandler(8955, HandleLogin);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8961, HandleNeedTerminalSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8963, HandleNeedAssemblerSettings);
// Same function but server. I think SendMessageToOthers sends to self, which will stack overflow
MyAPIGateway.Multiplayer.RegisterMessageHandler(8964, HandleTerminalSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8965, HandleAssemblerSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8967, HandleHammerTerminalSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8968, HandleNeedHammerTerminalSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8972, HandleBeaconTerminalSettings);
MyAPIGateway.Multiplayer.RegisterMessageHandler(8973, HandleNeedBeaconTerminalSettings);
}
m_init = true;
}
public void Unload()
{
if (m_init)
{
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8950, HandleUpdateState);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8951, HandleAddTarget);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8952, HandleCompleteTarget);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8953, HandleCancelTarget);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8954, HandleDetails);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8956, HandleSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8958, HandleStartParticle);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8959, HandleRemoveParticle);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8960, HandleTerminalSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8962, HandleAssemblerSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8955, HandleLogin);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8961, HandleNeedTerminalSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8963, HandleNeedAssemblerSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8964, HandleTerminalSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8965, HandleAssemblerSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8967, HandleHammerTerminalSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8968, HandleNeedHammerTerminalSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8972, HandleBeaconTerminalSettings);
MyAPIGateway.Multiplayer.UnregisterMessageHandler(8973, HandleNeedBeaconTerminalSettings);
}
}
/// <summary>
/// Multiplayer packet handlers - Direct to the proper block handler
/// </summary>
/// <param name="data"></param>
private void HandleUpdateState(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
StateData state = MyAPIGateway.Utilities.SerializeFromXML<StateData>(ASCIIEncoding.ASCII.GetString(data));
//MyLog.Default.WriteLine(string.Format("UpdateState: {0}", state.State.ToString()));
if (NaniteConstructionManager.NaniteBlocks == null)
return;
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
if (item.Key == state.EntityId)
item.Value.SyncUpdateState(state);
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleUpdateState Error: {0}", ex.ToString()));
}
}
// HandleAddTarget
private void HandleAddTarget(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
if (NaniteConstructionManager.NaniteBlocks == null)
return;
TargetData target = MyAPIGateway.Utilities.SerializeFromXML<TargetData>(ASCIIEncoding.ASCII.GetString(data));
Logging.Instance.WriteLine(string.Format("HandleAddTarget: {0}", target.ToString()));
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
if (item.Key == target.EntityId)
item.Value.SyncAddTarget(target);
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleAddTarget Error: {0}", ex.ToString()));
}
}
// HandleCompleteTarget
private void HandleCompleteTarget(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
if (NaniteConstructionManager.NaniteBlocks == null)
return;
TargetData target = MyAPIGateway.Utilities.SerializeFromXML<TargetData>(ASCIIEncoding.ASCII.GetString(data));
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
if (item.Key == target.EntityId)
item.Value.SyncCompleteTarget(target);
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleCompleteTarget Error: {0}", ex.ToString()));
}
}
// HandleCancelTarget
private void HandleCancelTarget(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
if (NaniteConstructionManager.NaniteBlocks == null)
return;
TargetData target = MyAPIGateway.Utilities.SerializeFromXML<TargetData>(ASCIIEncoding.ASCII.GetString(data));
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
if (item.Key == target.EntityId)
item.Value.SyncCancelTarget(target);
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleCancelTarget Error: {0}", ex.ToString()));
}
}
private void HandleDetails(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
if (NaniteConstructionManager.NaniteBlocks == null)
return;
DetailData details = MyAPIGateway.Utilities.SerializeFromXML<DetailData>(ASCIIEncoding.ASCII.GetString(data));
//Logging.Instance.WriteLine(string.Format("HandleDetails: {0}", details.EntityId));
bool found = false;
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
if (item.Key == details.EntityId && item.Value.Initialized)
{
//Logging.Instance.WriteLine(string.Format("Details for Factory: {0}", details.EntityId));
item.Value.SyncDetails(details);
found = true;
break;
}
}
if(!found)
{
foreach(var item in NaniteConstructionManager.MiningList)
{
if(item.MiningBlock.EntityId == details.EntityId)
{
//Logging.Instance.WriteLine(string.Format("Details for Hammer: {0}", details.EntityId));
item.SyncDetails(details);
found = true;
break;
}
}
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleDetails() Error: {0}", ex.ToString()));
}
}
public void SendLogin()
{
LoginData data = new LoginData();
if (MyAPIGateway.Session.Player != null)
data.SteamId = MyAPIGateway.Session.Player.SteamUserId;
else
data.SteamId = 0;
MyAPIGateway.Multiplayer.SendMessageToServer(8955, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(data)));
}
private void HandleLogin(byte[] data)
{
if (!Sync.IsServer)
return;
try
{
LoginData loginData = MyAPIGateway.Utilities.SerializeFromXML<LoginData>(ASCIIEncoding.ASCII.GetString(data));
Logging.Instance.WriteLine(string.Format("Sending settings to: {0}", loginData.SteamId));
SendSettings(loginData.SteamId);
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleLogin() Error: {0}", ex.ToString()));
}
}
public void SendSettings(ulong steamId)
{
SettingsData data = new SettingsData();
data.Settings = NaniteConstructionManager.Settings;
MyAPIGateway.Multiplayer.SendMessageTo(8956, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(data)), steamId);
}
private void HandleSettings(byte[] data)
{
try
{
SettingsData settingsData = MyAPIGateway.Utilities.SerializeFromXML<SettingsData>(ASCIIEncoding.ASCII.GetString(data));
NaniteConstructionManager.Settings = settingsData.Settings;
Logging.Instance.WriteLine(string.Format("Received Settings Data - {0}x {1}x", NaniteConstructionManager.Settings.FactoryComponentMultiplier, NaniteConstructionManager.Settings.UpgradeComponentMultiplier));
foreach(var item in NaniteConstructionManager.NaniteBlocks)
{
IMySlimBlock slimBlock = ((MyCubeBlock)item.Value.ConstructionBlock).SlimBlock as IMySlimBlock;
Logging.Instance.WriteLine(string.Format("Here: {0} / {1}", slimBlock.BuildIntegrity, slimBlock.MaxIntegrity));
}
var def = MyDefinitionManager.Static.GetCubeBlockDefinition(new MyDefinitionId(typeof(MyObjectBuilder_OxygenFarm), "LargeNaniteFactory"));
foreach (var item in def.Components)
{
item.Count = (int)((float)item.Count * NaniteConstructionManager.Settings.FactoryComponentMultiplier);
if (item.Count < 1)
item.Count = 1;
}
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
IMySlimBlock slimBlock = ((MyCubeBlock)item.Value.ConstructionBlock).SlimBlock as IMySlimBlock;
Logging.Instance.WriteLine(string.Format("Here: {0} / {1}", slimBlock.BuildIntegrity, slimBlock.MaxIntegrity));
}
foreach (var item in MyDefinitionManager.Static.GetAllDefinitions())
{
if (item.Id.TypeId == typeof(MyObjectBuilder_UpgradeModule) && item.Id.SubtypeName.Contains("Nanite"))
{
MyCubeBlockDefinition cubeDef = (MyCubeBlockDefinition)item;
foreach (var component in cubeDef.Components)
{
component.Count = (int)((float)component.Count * NaniteConstructionManager.Settings.UpgradeComponentMultiplier);
if (component.Count < 1)
component.Count = 1;
}
}
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleSettings() Error: {0}", ex.ToString()));
}
}
private void HandleStartParticle(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
ParticleData target = MyAPIGateway.Utilities.SerializeFromXML<ParticleData>(ASCIIEncoding.ASCII.GetString(data));
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
if (item.Key == target.EntityId && item.Value.Initialized)
item.Value.SyncStartParticleEffect(target);
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleSettings() Error: {0}", ex.ToString()));
}
}
private void HandleRemoveParticle(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
ParticleData target = MyAPIGateway.Utilities.SerializeFromXML<ParticleData>(ASCIIEncoding.ASCII.GetString(data));
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
if (item.Key == target.EntityId && item.Value.Initialized)
item.Value.SyncRemoveParticleEffect(target);
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleSettings() Error: {0}", ex.ToString()));
}
}
public void SendTerminalSettings(IMyTerminalBlock block)
{
SendTerminalSettings(block.EntityId);
}
public void SendTerminalSettings(long blockId)
{
if (NaniteConstructionManager.NaniteBlocks == null)
return;
if (!NaniteConstructionManager.NaniteBlocks.ContainsKey(blockId))
return;
if (!NaniteConstructionManager.TerminalSettings.ContainsKey(blockId))
NaniteConstructionManager.TerminalSettings.Add(blockId, new NaniteTerminalSettings());
SerializableKeyValuePair<long, NaniteTerminalSettings> settings = new SerializableKeyValuePair<long, NaniteTerminalSettings>(blockId, NaniteConstructionManager.TerminalSettings[blockId]);
if (!Sync.IsServer)
{
//Logging.Instance.WriteLine("SendTerminalSettings -> Server");
MyAPIGateway.Multiplayer.SendMessageToServer(8964, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(settings)));
}
else
{
//Logging.Instance.WriteLine("SendTerminalSettings -> Others");
MyAPIGateway.Multiplayer.SendMessageToOthers(8960, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(settings)));
}
}
private void HandleTerminalSettings(byte[] data)
{
//Logging.Instance.WriteLine("HandleTerminalSettings");
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<SerializableKeyValuePair<long, NaniteTerminalSettings>>(ASCIIEncoding.ASCII.GetString(data));
if (!NaniteConstructionManager.TerminalSettings.ContainsKey(settings.Key))
NaniteConstructionManager.TerminalSettings.Add(settings.Key, settings.Value);
else
NaniteConstructionManager.TerminalSettings[settings.Key] = settings.Value;
if (Sync.IsServer)
{
SendTerminalSettings(settings.Key);
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleTerminalSettings() Error: {0}", ex.ToString()));
}
}
public void SendAssemblerSettings(IMyTerminalBlock block)
{
SendAssemblerSettings(block.EntityId);
}
public void SendAssemblerSettings(long blockId)
{
if (!NaniteConstructionManager.AssemblerSettings.ContainsKey(blockId))
NaniteConstructionManager.AssemblerSettings.Add(blockId, new NaniteAssemblerSettings());
SerializableKeyValuePair<long, NaniteAssemblerSettings> settings = new SerializableKeyValuePair<long, NaniteAssemblerSettings>(blockId, NaniteConstructionManager.AssemblerSettings[blockId]);
if (!Sync.IsServer)
{
//Logging.Instance.WriteLine("SendAssemblerSettings -> Server");
MyAPIGateway.Multiplayer.SendMessageToServer(8965, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(settings)));
}
else
{
//Logging.Instance.WriteLine("SendAssemblerSettings -> Others");
MyAPIGateway.Multiplayer.SendMessageToOthers(8962, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(settings)));
}
}
private void HandleAssemblerSettings(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<SerializableKeyValuePair<long, NaniteAssemblerSettings>>(ASCIIEncoding.ASCII.GetString(data));
if (!NaniteConstructionManager.AssemblerSettings.ContainsKey(settings.Key))
NaniteConstructionManager.AssemblerSettings.Add(settings.Key, settings.Value);
NaniteConstructionManager.AssemblerSettings[settings.Key] = settings.Value;
if (Sync.IsServer)
SendAssemblerSettings(settings.Key);
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleAssemblerSettings() Error: {0}", ex.ToString()));
}
}
private void HandleNeedTerminalSettings(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<long>(ASCIIEncoding.ASCII.GetString(data));
foreach (var item in NaniteConstructionManager.NaniteBlocks)
{
if (item.Key == settings)
{
SendTerminalSettings(settings);
break;
}
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleNeedTerminalSettings() Error: {0}", ex.ToString()));
}
}
public void SendNeedTerminalSettings(long blockId)
{
if (MyAPIGateway.Multiplayer == null)
return;
Logging.Instance.WriteLine(string.Format("Requesting Terminal Settings -> {0}", blockId));
MyAPIGateway.Multiplayer.SendMessageToServer(8961, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(blockId)));
}
private void HandleNeedAssemblerSettings(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<long>(ASCIIEncoding.ASCII.GetString(data));
foreach (var item in NaniteConstructionManager.AssemblerBlocks)
{
if (item == settings)
{
SendAssemblerSettings(settings);
break;
}
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleNeedAssemblerSettings() Error: {0}", ex.ToString()));
}
}
public void SendNeedAssemblerSettings(long blockId)
{
if (MyAPIGateway.Multiplayer == null)
return;
Logging.Instance.WriteLine(string.Format("Requesting Assembler Settings -> {0}", blockId));
MyAPIGateway.Multiplayer.SendMessageToServer(8963, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(blockId)));
}
public void SendHammerTerminalSettings(long blockId)
{
if (!NaniteConstructionManager.HammerTerminalSettings.ContainsKey(blockId))
NaniteConstructionManager.HammerTerminalSettings.Add(blockId, new NaniteHammerTerminalSettings());
SerializableKeyValuePair<long, NaniteHammerTerminalSettings> settings = new SerializableKeyValuePair<long, NaniteHammerTerminalSettings>(blockId, NaniteConstructionManager.HammerTerminalSettings[blockId]);
if (!Sync.IsServer)
{
Logging.Instance.WriteLine($"SendHammerTerminalSettings -> Server: {blockId}");
MyAPIGateway.Multiplayer.SendMessageToServer(8967, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(settings)));
}
else
{
Logging.Instance.WriteLine($"SendHammerTerminalSettings -> Others: {blockId}");
MyAPIGateway.Multiplayer.SendMessageToOthers(8966, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(settings)));
}
}
private void HandleHammerTerminalSettings(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<SerializableKeyValuePair<long, NaniteHammerTerminalSettings>>(ASCIIEncoding.ASCII.GetString(data));
if (!NaniteConstructionManager.HammerTerminalSettings.ContainsKey(settings.Key))
NaniteConstructionManager.HammerTerminalSettings.Add(settings.Key, settings.Value);
NaniteConstructionManager.HammerTerminalSettings[settings.Key] = settings.Value;
IMyEntity entity;
if(MyAPIGateway.Entities.TryGetEntityById(settings.Key, out entity))
{
var block = entity as IMyTerminalBlock;
block.RefreshCustomInfo();
}
if (Sync.IsServer)
SendHammerTerminalSettings(settings.Key);
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleHammerTerminalSettings() Error: {0}", ex.ToString()));
}
}
public void SendNeedHammerTerminalSettings(long blockId)
{
if (MyAPIGateway.Multiplayer == null)
return;
Logging.Instance.WriteLine(string.Format("Requesting Assembler Settings -> {0}", blockId));
MyAPIGateway.Multiplayer.SendMessageToServer(8968, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(blockId)));
}
private void HandleNeedHammerTerminalSettings(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<long>(ASCIIEncoding.ASCII.GetString(data));
foreach (var item in NaniteConstructionManager.HammerTerminalSettings)
{
if (item.Key == settings)
{
SendHammerTerminalSettings(item.Key);
break;
}
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleNeedHammerTerminalSettings() Error: {0}", ex.ToString()));
}
}
public void SendBeaconTerminalSettings(long blockId)
{
if (!NaniteConstructionManager.BeaconTerminalSettings.ContainsKey(blockId))
NaniteConstructionManager.BeaconTerminalSettings.Add(blockId, new NaniteBeaconTerminalSettings());
SerializableKeyValuePair<long, NaniteBeaconTerminalSettings> settings = new SerializableKeyValuePair<long, NaniteBeaconTerminalSettings>(blockId, NaniteConstructionManager.BeaconTerminalSettings[blockId]);
if (!Sync.IsServer)
{
//Logging.Instance.WriteLine("SendAssemblerSettings -> Server");
Logging.Instance.WriteLine($"SendBeaconTerminalSettings -> Server: {blockId}");
MyAPIGateway.Multiplayer.SendMessageToServer(8972, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(settings)));
}
else
{
//Logging.Instance.WriteLine("SendAssemblerSettings -> Others");
Logging.Instance.WriteLine($"SendBeaconTerminalSettings -> Client: {blockId}");
MyAPIGateway.Multiplayer.SendMessageToOthers(8971, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(settings)));
}
}
private void HandleBeaconTerminalSettings(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<SerializableKeyValuePair<long, NaniteBeaconTerminalSettings>>(ASCIIEncoding.ASCII.GetString(data));
if (!NaniteConstructionManager.BeaconTerminalSettings.ContainsKey(settings.Key))
NaniteConstructionManager.BeaconTerminalSettings.Add(settings.Key, settings.Value);
NaniteConstructionManager.BeaconTerminalSettings[settings.Key] = settings.Value;
Logging.Instance.WriteLine($"Receieved Beacon Terminal Settings Update: {settings.Key}");
if (Sync.IsServer)
SendBeaconTerminalSettings(settings.Key);
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleBeaconTerminalSettings() Error: {0}", ex.ToString()));
}
}
public void SendNeedBeaconTerminalSettings(long blockId)
{
if (MyAPIGateway.Multiplayer == null)
return;
Logging.Instance.WriteLine($"SendNeedBeaconTerminalSettings: {blockId}");
MyAPIGateway.Multiplayer.SendMessageToServer(8973, ASCIIEncoding.ASCII.GetBytes(MyAPIGateway.Utilities.SerializeToXML(blockId)));
}
private void HandleNeedBeaconTerminalSettings(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<long>(ASCIIEncoding.ASCII.GetString(data));
Logging.Instance.WriteLine($"HandleNeedBeaconTerminalSettings: {settings}");
foreach (var item in NaniteConstructionManager.BeaconTerminalSettings)
{
if (item.Key == settings)
{
Logging.Instance.WriteLine($"SendBeaconTerminalSettings: {settings}");
SendBeaconTerminalSettings(item.Key);
break;
}
}
}
catch (Exception ex)
{
MyLog.Default.WriteLine(string.Format("HandleNeedBeaconTerminalSettings() Error: {0}", ex.ToString()));
}
}
private void HandleVoxelRemoval(byte[] data)
{
try
{
if (MyAPIGateway.Session == null)
return;
var settings = MyAPIGateway.Utilities.SerializeFromXML<VoxelRemovalData>(ASCIIEncoding.ASCII.GetString(data));
byte materialRemoved = 0;
float amountOfMaterial = 0f;
Beacons.NaniteMining.RemoveVoxelContent(settings.VoxelID, settings.Position, out materialRemoved, out amountOfMaterial);
}
catch(Exception ex)
{
MyLog.Default.WriteLine($"HandleVoxelRemoval(): {ex.ToString()}");
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Resources;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Util;
using newtelligence.DasBlog.Util.Html;
using newtelligence.DasBlog.Web.Core;
using newtelligence.DasBlog.Web.TextEditors;
namespace newtelligence.DasBlog.Web
{
public partial class EditConfigBox : UserControl
{
const string defaultGravatarSize = "80";
const string passwordPlaceHolder = "########";
protected const string SPAM_OPTION_DELETE = "DELETE";
protected const string SPAM_OPTION_SAVE = "SAVE";
protected ResourceManager resmgr;
public PingServiceCollection PingServiceCollection
{
get
{
DataCache cache = CacheFactory.GetCache();
PingServiceCollection pingServices = (PingServiceCollection)cache["PingServices"];
if (pingServices == null)
{
pingServices = GetPingServiceInfo();
}
return pingServices;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (SiteSecurity.IsInRole("admin") == false)
{
Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
}
ID = "EditConfigBox";
SharedBasePage requestPage = Page as SharedBasePage;
SiteConfig siteConfig = requestPage.SiteConfig;
if (!IsPostBack)
{
textContact.Text = siteConfig.Contact;
textCopyright.Text = siteConfig.Copyright;
textPassword.Text = passwordPlaceHolder;
textConfirmPassword.Text = passwordPlaceHolder;
textFrontPageCategory.Text = siteConfig.FrontPageCategory;
textFrontPageDayCount.Text = siteConfig.FrontPageDayCount.ToString();
textFrontPageEntryCount.Text = siteConfig.FrontPageEntryCount.ToString();
textEntriesPerPage.Text = siteConfig.EntriesPerPage.ToString();
textContentLookaheadDays.Text = siteConfig.ContentLookaheadDays.ToString();
textMainMaxDaysInRss.Text = siteConfig.RssDayCount.ToString();
textMainMaxEntriesInRss.Text = siteConfig.RssMainEntryCount.ToString();
textOtherMaxEntriesInRss.Text = siteConfig.RssEntryCount.ToString();
checkAlwaysIncludeContentInRSS.Checked = siteConfig.AlwaysIncludeContentInRSS;
checkEnableRSSItemFooter.Checked = siteConfig.EnableRssItemFooters;
textRSSItemFooter.Text = siteConfig.RssItemFooter;
txtRSSEndPointRewrite.Text = siteConfig.RSSEndPointRewrite;
checkPop3Enabled.Checked = siteConfig.EnablePop3;
textPop3Interval.Text = siteConfig.Pop3Interval.ToString();
textPop3Server.Text = siteConfig.Pop3Server;
textPop3SubjectPrefix.Text = siteConfig.Pop3SubjectPrefix;
textPop3Username.Text = siteConfig.Pop3Username;
textPop3Password.Text = passwordPlaceHolder;
textPop3PasswordRepeat.Text = passwordPlaceHolder;
textRoot.Text = siteConfig.Root;
textSmtpServer.Text = siteConfig.SmtpServer;
textSmtpPort.Text = siteConfig.SmtpPort.ToString();
checkUseSSLForSMTP.Checked = siteConfig.UseSSLForSMTP;
textNotificationEmailAddress.Text = siteConfig.NotificationEMailAddress;
textSubtitle.Text = siteConfig.Subtitle;
textSmtpServer.Text = siteConfig.SmtpServer;
checkEnableCoComment.Checked = siteConfig.EnableCoComment;
checkComments.Checked = siteConfig.SendCommentsByEmail;
checkPingbacks.Checked = siteConfig.SendPingbacksByEmail;
checkReferrals.Checked = siteConfig.SendReferralsByEmail;
checkPosts.Checked = siteConfig.SendPostsByEmail;
checkTrackbacks.Checked = siteConfig.SendTrackbacksByEmail;
checkShowCommentCounters.Checked = siteConfig.ShowCommentCount;
checkEnableAutoPingback.Checked = siteConfig.EnableAutoPingback;
checkEnableBloggerApi.Checked = siteConfig.EnableBloggerApi;
checkEnableComments.Checked = siteConfig.EnableComments;
checkEnableCommentApi.Checked = siteConfig.EnableCommentApi;
checkShowCommentsWhenViewingEntry.Checked = siteConfig.ShowCommentsWhenViewingEntry;
checkEnableConfigEditService.Checked = siteConfig.EnableConfigEditService;
checkEnableEditService.Checked = siteConfig.EnableEditService;
checkEnableAutoSave.Checked = siteConfig.EnableAutoSave;
checkEnablePingbackService.Checked = siteConfig.EnablePingbackService;
checkEnableTrackbackService.Checked = siteConfig.EnableTrackbackService;
checkEnableClickThrough.Checked = siteConfig.EnableClickThrough;
checkEnableAggregatorBugging.Checked = siteConfig.EnableAggregatorBugging;
checkXssEnabled.Checked = siteConfig.EnableXSSUpstream;
textXssEndpoint.Text = siteConfig.XSSUpstreamEndpoint;
textXssInterval.Text = siteConfig.XSSUpstreamInterval.ToString();
textXssPassword.Text = passwordPlaceHolder;
textXssPasswordRepeat.Text = passwordPlaceHolder;
textXssUsername.Text = siteConfig.XSSUpstreamUsername;
textXssRssFilename.Text = siteConfig.XSSRSSFilename;
checkPop3InlineAttachedPictures.Checked = siteConfig.Pop3InlineAttachedPictures;
textPop3AttachedPicturesPictureThumbnailHeight.Text = siteConfig.Pop3InlinedAttachedPicturesThumbHeight.ToString();
mailDeletionAll.Checked = siteConfig.Pop3DeleteAllMessages;
mailDeletionProcessed.Checked = !siteConfig.Pop3DeleteAllMessages;
logIgnoredEmails.Checked = siteConfig.Pop3LogIgnoredEmails;
checkShowItemDescriptionInAggregatedViews.Checked = siteConfig.ShowItemDescriptionInAggregatedViews;
checkEnableStartPageCaching.Checked = siteConfig.EnableStartPageCaching;
checkEnableBlogrollDescription.Checked = siteConfig.EnableBlogrollDescription;
checkEntryTitleAsLink.Checked = siteConfig.EntryTitleAsLink;
checkEnableUrlRewriting.Checked = siteConfig.EnableUrlRewriting;
checkEnableCrosspost.Checked = siteConfig.EnableCrossposts;
checkCategoryAllEntries.Checked = siteConfig.CategoryAllEntries;
checkReferralUrlBlacklist.Checked = siteConfig.EnableReferralUrlBlackList;
textReferralBlacklist.Text = siteConfig.ReferralUrlBlackList;
checkCaptchaEnabled.Checked = siteConfig.EnableCaptcha;
checkReferralBlacklist404s.Checked = siteConfig.EnableReferralUrlBlackList404s;
textRSSChannelImage.Text = siteConfig.ChannelImageUrl;
checkEnableTitlePermaLink.Checked = siteConfig.EnableTitlePermaLink;
checkEnableTitlePermaLinkUnique.Checked = siteConfig.EnableTitlePermaLinkUnique;
checkEnableTitlePermaLinkSpaces.Checked = siteConfig.EnableTitlePermaLinkSpaces;
checkEnableEncryptLoginPassword.Checked = siteConfig.EncryptLoginPassword;
checkEnableSmtpAuthentication.Checked = siteConfig.EnableSmtpAuthentication;
textSmtpUsername.Text = siteConfig.SmtpUserName;
textSmtpPassword.Text = passwordPlaceHolder;
textRssLanguage.Text = siteConfig.RssLanguage;
checkEnableSearchHighlight.Checked = siteConfig.EnableSearchHighlight;
checkEnableEntryReferral.Checked = siteConfig.EnableEntryReferrals;
textFeedBurnerName.Text = siteConfig.FeedBurnerName;
checkUseFeedScheme.Checked = siteConfig.UseFeedSchemeForSyndication;
checkLogBlockedReferrals.Checked = siteConfig.LogBlockedReferrals;
//populate the title space replacement options
dropDownTitlePermalinkReplacementCharacter.Items.Clear();//in casee someone adds them in the ascx
foreach (string s in TitleMapperModule.TitlePermalinkSpaceReplacementOptions) dropDownTitlePermalinkReplacementCharacter.Items.Add(s);
dropDownTitlePermalinkReplacementCharacter.SelectedValue = siteConfig.TitlePermalinkSpaceReplacement;
checkSpamBlockingEnabled.Checked = siteConfig.EnableSpamBlockingService;
textSpamBlockingApiKey.Text = siteConfig.SpamBlockingServiceApiKey;
optionSpamHandling.SelectedValue = siteConfig.EnableSpamModeration ? SPAM_OPTION_SAVE : SPAM_OPTION_DELETE;
// setup the checkbox list to select which tags to allow
checkBoxListAllowedTags.DataSource = siteConfig.AllowedTags;
checkBoxListAllowedTags.DataTextField = "Name";
checkBoxListAllowedTags.DataValueField = "Name";
// enable comment moderation
checkCommentsRequireApproval.Checked = siteConfig.CommentsRequireApproval;
// allow html and comments
checkAllowHtml.Checked = siteConfig.CommentsAllowHtml;
// populate from config - Gravatar
GravatarPopulateForm();
// supress email address display
checkDisableEmailDisplay.Checked = siteConfig.SupressEmailAddressDisplay;
checkEnableCommentDays.Checked = siteConfig.EnableCommentDays;
checkAttemptToHtmlTidyContent.Checked = siteConfig.HtmlTidyContent;
checkResolveCommenterIP.Checked = siteConfig.ResolveCommenterIP;
//if ( siteConfig.EnableCommentDays )
//{
if (siteConfig.DaysCommentsAllowed > 0)
{
textDaysCommentsAllowed.Text = siteConfig.DaysCommentsAllowed.ToString();
}
//}
//else
//{
// textDaysCommentsAllowed.Text = null;
//}
// supress email address display
checkDisableEmailDisplay.Checked = siteConfig.SupressEmailAddressDisplay;
checkEnableCommentDays.Checked = siteConfig.EnableCommentDays;
//if ( siteConfig.EnableCommentDays )
//{
if (siteConfig.DaysCommentsAllowed > 0)
{
textDaysCommentsAllowed.Text = siteConfig.DaysCommentsAllowed.ToString();
}
//}
//else
//{
// textDaysCommentsAllowed.Text = null;
//}
// email daily report
checkDailyReport.Text = resmgr.GetString("text_daily_activity_report");
checkDailyReport.Checked = siteConfig.EnableDailyReportEmail;
WindowsTimeZoneCollection timeZones = WindowsTimeZone.TimeZones;
foreach (WindowsTimeZone tz in timeZones)
{
listTimeZones.Items.Add(new ListItem(tz.DisplayName, tz.ZoneIndex.ToString()));
}
listTimeZones.SelectedValue = siteConfig.DisplayTimeZoneIndex.ToString();
checkUseUTC.Checked = !siteConfig.AdjustDisplayTimeZone;
//FIX: hardcoded path
ThemeDictionary themes = BlogTheme.Load(SiteUtilities.MapPath("themes"));
foreach (BlogTheme theme in themes.Values)
{
// setting the selected item like this instead of
// using listThemes.SelectedValue = siteConfig.Theme;
// prevents the page from breaking.
ListItem item = new ListItem(theme.Title, theme.Name);
if (item.Value == siteConfig.Theme)
{
item.Selected = true;
}
listThemes.Items.Add(item);
}
textTitle.Text = siteConfig.Title;
checkBoxListPingServices.DataSource = PingServiceCollection;
checkBoxListPingServices.DataTextField = "Hyperlink";
checkBoxListPingServices.DataValueField = "Endpoint";
drpEntryEditControl.Items.Clear();
foreach (string potentialAssembly in Directory.GetFiles(HttpRuntime.BinDirectory, "*.dll"))
{
try
{
Assembly a = Assembly.LoadFrom(potentialAssembly);
foreach (Type potentialType in a.GetTypes())
{
if (potentialType.BaseType == typeof(EditControlAdapter))
{
drpEntryEditControl.Items.Add(new ListItem(potentialType.Name, potentialType.AssemblyQualifiedName));
}
}
}
catch (Exception)
{
//swallow
}
}
//Reasonable default
if (string.IsNullOrEmpty(siteConfig.EntryEditControl))
{
siteConfig.EntryEditControl = typeof(TinyMCEAdapter).AssemblyQualifiedName;
}
DataBind();
ListItem li = drpEntryEditControl.Items.FindByText(siteConfig.EntryEditControl);
if (li != null)
{
li.Selected = true;
}
else
{
drpEntryEditControl.SelectedIndex = 0;
}
foreach (PingService ps in siteConfig.PingServices)
{
checkBoxListPingServices.Items.FindByValue(ps.Endpoint).Selected = true;
}
foreach (ValidTag tag in siteConfig.AllowedTags)
{
checkBoxListAllowedTags.Items.FindByValue(tag.Name).Selected = tag.IsAllowed;
}
//check for Smtp permission
if (SecurityManager.IsGranted(new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort)))
{
phSmtpTrustWarning.Visible = false;
}
else
{
phSmtpTrustWarning.Visible = true;
}
//check for Socket permission
SocketPermission sp;
if (String.IsNullOrEmpty(textPop3Server.Text))
{
sp = new SocketPermission(PermissionState.Unrestricted);
}
else
{
sp = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, textPop3Server.Text, 110);
}
if (SecurityManager.IsGranted(sp))
{
phPop3TrustWarning.Visible = false;
}
else
{
phPop3TrustWarning.Visible = true;
}
// georss stuff
checkEnableGeoRss.Checked = siteConfig.EnableGeoRss;
textGoogleMapsApi.Text = siteConfig.GoogleMapsApiKey;
textDefaultLatitude.Text = siteConfig.DefaultLatitude.ToString(CultureInfo.InvariantCulture);
textDefaultLongitude.Text = siteConfig.DefaultLongitude.ToString(CultureInfo.InvariantCulture);
checkEnableGoogleMaps.Checked = siteConfig.EnableGoogleMaps;
checkEnableDefaultLatLongForNonGeoCodedPosts.Checked = siteConfig.EnableDefaultLatLongForNonGeoCodedPosts;
// OpenId
chkAllowOpenIdAdmin.Checked = siteConfig.AllowOpenIdAdmin;
chkAllowOpenIdCommenter.Checked = siteConfig.AllowOpenIdComments;
chkBypassSpamOpenIdCommenter.Checked = siteConfig.BypassSpamOpenIdComment;
SeoMetaTags smt = new SeoMetaTags().GetMetaTags();
txtMetaDescription.Text = smt.MetaDescription;
txtMetaKeywords.Text = smt.MetaKeywords;
txtTwitterCard.Text = smt.TwitterCard;
txtTwitterSite.Text = smt.TwitterSite;
txtTwitterCreator.Text = smt.TwitterCreator;
txtTwitterImage.Text = smt.TwitterImage;
txtFaceBookAdmins.Text = smt.FaceBookAdmins;
txtFaceBookAppID.Text = smt.FaceBookAppID;
checkAmpEnabled.Checked = siteConfig.AMPPagesEnabled;
} // end if !postback
//enable list controls that may have been enabled client-side
//in 2.0 if they are not enable we won't get there postback data
checkBoxListAllowedTags.Enabled = true;
dropGravatarRating.Enabled = true;
}
protected override void OnPreRender(EventArgs e)
{
CleanGravatar();
CleanAutoExpire();
CleanHtmlComments();
CleanGeoRss();
CreateClientScript();
}
static PingServiceCollection GetPingServiceInfo()
{
PingServiceCollection pingServiceCollection = new PingServiceCollection();
string fullPath = SiteConfig.GetConfigPathFromCurrentContext() + "PingServices.xml";
if (File.Exists(fullPath))
{
FileStream fileStream = FileUtils.OpenForRead(fullPath);
if (fileStream != null)
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(PingServiceCollection));
StreamReader reader = new StreamReader(fileStream);
pingServiceCollection = (PingServiceCollection)ser.Deserialize(reader);
// add to cache
DataCache cache = CacheFactory.GetCache();
cache.Insert("PingServices", pingServiceCollection, new CacheDependency(fullPath));
}
catch (Exception e)
{
ErrorTrace.Trace(TraceLevel.Error, e);
}
finally
{
fileStream.Close();
}
}
}
// add some defaults
if (pingServiceCollection.Count == 0)
{
pingServiceCollection = PingService.GetDefaultPingServices();
}
return pingServiceCollection;
}
protected void buttonSave_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
// There were validation errors, save client states.
CleanGravatar();
CleanAutoExpire();
CleanHtmlComments();
CleanGeoRss();
return;
}
SharedBasePage requestPage = Page as SharedBasePage;
SiteConfig siteConfig = requestPage.SiteConfig;
siteConfig.Contact = textContact.Text;
siteConfig.Copyright = textCopyright.Text;
siteConfig.FrontPageCategory = textFrontPageCategory.Text;
siteConfig.FrontPageDayCount = int.Parse(textFrontPageDayCount.Text);
siteConfig.FrontPageEntryCount = int.Parse(textFrontPageEntryCount.Text);
siteConfig.EntriesPerPage = int.Parse(textEntriesPerPage.Text);
try
{
siteConfig.ContentLookaheadDays = int.Parse(textContentLookaheadDays.Text);
}
catch (FormatException)
{
siteConfig.ContentLookaheadDays = 0;
}
siteConfig.RssDayCount = int.Parse(textMainMaxDaysInRss.Text);
siteConfig.RssMainEntryCount = int.Parse(textMainMaxEntriesInRss.Text);
siteConfig.RssEntryCount = int.Parse(textOtherMaxEntriesInRss.Text);
siteConfig.AlwaysIncludeContentInRSS = checkAlwaysIncludeContentInRSS.Checked;
siteConfig.EnableRssItemFooters = checkEnableRSSItemFooter.Checked;
siteConfig.RssItemFooter = textRSSItemFooter.Text;
siteConfig.RSSEndPointRewrite = txtRSSEndPointRewrite.Text;
siteConfig.EnablePop3 = checkPop3Enabled.Checked;
siteConfig.Pop3Interval = int.Parse(textPop3Interval.Text);
siteConfig.Pop3Server = textPop3Server.Text;
siteConfig.Pop3SubjectPrefix = textPop3SubjectPrefix.Text;
siteConfig.Pop3Username = textPop3Username.Text;
if (textPop3Password.Text.Length > 0 &&
textPop3Password.Text != passwordPlaceHolder)
{
siteConfig.Pop3Password = textPop3Password.Text;
}
siteConfig.Pop3DeleteAllMessages = mailDeletionAll.Checked;
siteConfig.Pop3LogIgnoredEmails = logIgnoredEmails.Checked;
siteConfig.EnableXSSUpstream = checkXssEnabled.Checked;
siteConfig.XSSUpstreamEndpoint = textXssEndpoint.Text;
siteConfig.XSSUpstreamInterval = int.Parse(textXssInterval.Text);
if (textXssPassword.Text.Length > 0 &&
textXssPassword.Text != passwordPlaceHolder)
{
siteConfig.XSSUpstreamPassword = textXssPassword.Text;
}
siteConfig.XSSUpstreamUsername = textXssUsername.Text;
siteConfig.XSSRSSFilename = textXssRssFilename.Text;
siteConfig.Root = textRoot.Text;
siteConfig.SmtpServer = textSmtpServer.Text;
siteConfig.SmtpPort = int.Parse(textSmtpPort.Text);
siteConfig.UseSSLForSMTP = checkUseSSLForSMTP.Checked;
siteConfig.NotificationEMailAddress = textNotificationEmailAddress.Text;
siteConfig.SendCommentsByEmail = checkComments.Checked;
siteConfig.EnableCoComment = checkEnableCoComment.Checked;
siteConfig.SendPingbacksByEmail = checkPingbacks.Checked;
siteConfig.SendReferralsByEmail = checkReferrals.Checked;
siteConfig.SendTrackbacksByEmail = checkTrackbacks.Checked;
siteConfig.SendPostsByEmail = checkPosts.Checked;
siteConfig.EnableAutoPingback = checkEnableAutoPingback.Checked;
siteConfig.EnableBloggerApi = checkEnableBloggerApi.Checked;
siteConfig.EnableComments = checkEnableComments.Checked;
siteConfig.EnableCommentApi = checkEnableCommentApi.Checked;
siteConfig.ShowCommentsWhenViewingEntry = checkShowCommentsWhenViewingEntry.Checked;
siteConfig.EnableConfigEditService = checkEnableConfigEditService.Checked;
siteConfig.EnableEditService = checkEnableEditService.Checked;
siteConfig.EnableAutoSave = checkEnableAutoSave.Checked;
siteConfig.EnableTrackbackService = checkEnableTrackbackService.Checked;
siteConfig.EnablePingbackService = checkEnablePingbackService.Checked;
siteConfig.EnableClickThrough = checkEnableClickThrough.Checked;
siteConfig.EnableAggregatorBugging = checkEnableAggregatorBugging.Checked;
siteConfig.Subtitle = textSubtitle.Text;
siteConfig.Title = textTitle.Text;
siteConfig.ShowCommentCount = checkShowCommentCounters.Checked;
siteConfig.Pop3InlineAttachedPictures = checkPop3InlineAttachedPictures.Checked;
siteConfig.Pop3InlinedAttachedPicturesThumbHeight = int.Parse(textPop3AttachedPicturesPictureThumbnailHeight.Text);
siteConfig.ShowItemDescriptionInAggregatedViews = checkShowItemDescriptionInAggregatedViews.Checked;
siteConfig.EnableStartPageCaching = checkEnableStartPageCaching.Checked;
siteConfig.EnableBlogrollDescription = checkEnableBlogrollDescription.Checked;
siteConfig.EnableUrlRewriting = checkEnableUrlRewriting.Checked;
siteConfig.DisplayTimeZoneIndex = Convert.ToInt32(listTimeZones.SelectedValue);
siteConfig.AdjustDisplayTimeZone = !checkUseUTC.Checked;
siteConfig.EntryTitleAsLink = checkEntryTitleAsLink.Checked;
siteConfig.EnableCrossposts = checkEnableCrosspost.Checked;
if (textPassword.Text.Length > 0 &&
textPassword.Text != passwordPlaceHolder)
{
SiteSecurity.SetPassword(requestPage.User.Identity.Name, textPassword.Text);
}
siteConfig.CategoryAllEntries = checkCategoryAllEntries.Checked;
requestPage.UserTheme = siteConfig.Theme = listThemes.SelectedValue;
siteConfig.ReferralUrlBlackList = textReferralBlacklist.Text.TrimEnd(';');
siteConfig.EnableReferralUrlBlackList = checkReferralUrlBlacklist.Checked;
siteConfig.EnableCaptcha = checkCaptchaEnabled.Checked;
siteConfig.EnableReferralUrlBlackList404s = checkReferralBlacklist404s.Checked;
siteConfig.ChannelImageUrl = textRSSChannelImage.Text;
siteConfig.EnableTitlePermaLink = checkEnableTitlePermaLink.Checked;
siteConfig.EnableTitlePermaLinkUnique = checkEnableTitlePermaLinkUnique.Checked;
siteConfig.EnableTitlePermaLinkSpaces = checkEnableTitlePermaLinkSpaces.Checked;
siteConfig.EncryptLoginPassword = checkEnableEncryptLoginPassword.Checked;
siteConfig.EnableSmtpAuthentication = checkEnableSmtpAuthentication.Checked;
siteConfig.SmtpUserName = textSmtpUsername.Text;
if (textSmtpPassword.Text.Length > 0 &&
textSmtpPassword.Text != passwordPlaceHolder)
{
siteConfig.SmtpPassword = textSmtpPassword.Text;
}
siteConfig.RssLanguage = textRssLanguage.Text;
siteConfig.EnableSearchHighlight = checkEnableSearchHighlight.Checked;
siteConfig.EnableEntryReferrals = checkEnableEntryReferral.Checked;
siteConfig.FeedBurnerName = textFeedBurnerName.Text.Trim();
siteConfig.UseFeedSchemeForSyndication = checkUseFeedScheme.Checked;
siteConfig.LogBlockedReferrals = checkLogBlockedReferrals.Checked;
siteConfig.EnableSpamBlockingService = checkSpamBlockingEnabled.Checked;
siteConfig.SpamBlockingServiceApiKey = textSpamBlockingApiKey.Text;
siteConfig.EnableSpamModeration = (optionSpamHandling.SelectedValue != SPAM_OPTION_DELETE);
siteConfig.EnableCommentDays = checkEnableCommentDays.Checked;
siteConfig.HtmlTidyContent = checkAttemptToHtmlTidyContent.Checked;
siteConfig.ResolveCommenterIP = checkResolveCommenterIP.Checked;
siteConfig.TitlePermalinkSpaceReplacement = dropDownTitlePermalinkReplacementCharacter.SelectedValue;
if (checkEnableCommentDays.Checked)
{
try
{
int days = Convert.ToInt32(textDaysCommentsAllowed.Text);
if (days > 0)
{
siteConfig.DaysCommentsAllowed = days;
}
}
catch (FormatException)
{
siteConfig.DaysCommentsAllowed = 60;
}
}
else
{
siteConfig.DaysCommentsAllowed = 60;
}
// comments approval
siteConfig.CommentsRequireApproval = checkCommentsRequireApproval.Checked;
// removed the ability to edit the html tags, which are allowed for now
foreach (ListItem li in checkBoxListAllowedTags.Items)
{
ValidTag tag = siteConfig.AllowedTags[li.Value];
if (tag != null)
{
tag.IsAllowed = li.Selected;
}
}
// comments allow html
siteConfig.CommentsAllowHtml = checkAllowHtml.Checked;
// comments allow Gravatar and alt path
GravatarPopulateConfig();
// supress email address display
siteConfig.SupressEmailAddressDisplay = checkDisableEmailDisplay.Checked;
// enable daily report email
siteConfig.EnableDailyReportEmail = checkDailyReport.Checked;
PingServiceCollection savePingServices = new PingServiceCollection();
foreach (PingService pingService in PingServiceCollection)
{
if (checkBoxListPingServices.Items.FindByValue(pingService.Endpoint).Selected)
{
savePingServices.Add(pingService);
}
}
siteConfig.PingServices = savePingServices;
siteConfig.EntryEditControl = drpEntryEditControl.SelectedValue;
// GeoRSS stuff.
siteConfig.EnableGeoRss = checkEnableGeoRss.Checked;
if (checkEnableGeoRss.Checked)
{
siteConfig.EnableDefaultLatLongForNonGeoCodedPosts = checkEnableDefaultLatLongForNonGeoCodedPosts.Checked;
if (checkEnableDefaultLatLongForNonGeoCodedPosts.Checked)
{
double latitude;
if (double.TryParse(textDefaultLatitude.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out latitude))
{
siteConfig.DefaultLatitude = latitude;
}
double longitude;
if (double.TryParse(textDefaultLongitude.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out longitude))
{
siteConfig.DefaultLongitude = longitude;
}
}
siteConfig.EnableGoogleMaps = checkEnableGoogleMaps.Checked;
if (checkEnableGoogleMaps.Checked)
{
siteConfig.GoogleMapsApiKey = textGoogleMapsApi.Text;
}
}
// open id stuff
siteConfig.AllowOpenIdAdmin = chkAllowOpenIdAdmin.Checked;
siteConfig.AllowOpenIdComments = chkAllowOpenIdCommenter.Checked;
siteConfig.BypassSpamOpenIdComment = chkBypassSpamOpenIdCommenter.Checked;
siteConfig.AMPPagesEnabled = checkAmpEnabled.Checked;
SiteConfig.Save(siteConfig);
SeoMetaTags smt = new SeoMetaTags().GetMetaTags();
smt.MetaDescription = txtMetaDescription.Text;
smt.MetaKeywords = txtMetaKeywords.Text ;
smt.TwitterCard = txtTwitterCard.Text;
smt.TwitterSite = txtTwitterSite.Text;
smt.TwitterCreator = txtTwitterCreator.Text;
smt.TwitterImage = txtTwitterImage.Text;
smt.FaceBookAdmins = txtFaceBookAdmins.Text;
smt.FaceBookAppID = txtFaceBookAppID.Text;
SeoMetaTags.Save(smt);
if (siteConfig.EnableReferralUrlBlackList && siteConfig.ReferralUrlBlackList.Length != 0)
{
ReferralBlackListFactory.AddBlacklist(new ReferralUrlBlacklist(), siteConfig.ReferralUrlBlackList);
}
else
{
ReferralBlackListFactory.RemoveBlacklist(typeof(ReferralUrlBlacklist));
}
requestPage.Redirect(Page.Request.Url.AbsoluteUri);
}
protected void EditConfigBox_Init(object sender, EventArgs e)
{
resmgr = ApplicationResourceTable.Get();
}
protected void buttonTestSMTP_Click(object sender, EventArgs e)
{
SharedBasePage requestPage = Page as SharedBasePage;
SiteConfig siteConfig = requestPage.SiteConfig;
if (textSmtpServer.Text != "" & textNotificationEmailAddress.Text != "")
{
MailMessage emailMessage = new MailMessage();
emailMessage.To.Add(textNotificationEmailAddress.Text);
emailMessage.Subject = String.Format("dasBlog test message");
emailMessage.Body =
String.Format("This is a test message from dasBlog. If you are reading this then everything is working properly.");
emailMessage.IsBodyHtml = false;
emailMessage.BodyEncoding = Encoding.UTF8;
emailMessage.From = new MailAddress(siteConfig.Contact);
SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, textSmtpServer.Text,
checkEnableSmtpAuthentication.Checked, checkUseSSLForSMTP.Checked,
textSmtpUsername.Text, textSmtpPassword.Text,
int.Parse(textSmtpPort.Text));
try
{
sendMailInfo.SendMyMessage();
}
catch (Exception ex)
{
//RyanG: Decode the real reason the error occured by looking at the inner exceptions
StringBuilder exceptionMessage = new StringBuilder();
Exception lastException = ex;
while (lastException != null)
{
if (exceptionMessage.Length > 0)
{
exceptionMessage.Append("; ");
}
exceptionMessage.Append(lastException.Message);
lastException = lastException.InnerException;
}
ILoggingDataService logService = requestPage.LoggingService;
logService.AddEvent(
new EventDataItem(EventCodes.SmtpError, "", exceptionMessage.ToString()));
Response.Redirect("FormatPage.aspx?path=SiteConfig/pageerror.format.html", true);
}
}
}
void CreateClientScript()
{
checkAllowHtml.Attributes.Add("onclick",
WebUtil.CreateEnableDisableScript(checkAllowHtml, checkBoxListAllowedTags));
checkEnableGeoRss.Attributes.Add("onclick",
WebUtil.CreateEnableDisableScript(checkEnableGeoRss,
checkEnableDefaultLatLongForNonGeoCodedPosts,
textDefaultLatitude,
textDefaultLongitude,
checkEnableGoogleMaps,
textGoogleMapsApi));
checkEnableGravatar.Attributes.Add("onclick", WebUtil.CreateEnableDisableScript(checkEnableGravatar,
textGravatarSize,
textNoGravatarPath,
textGravatarBorderColor,
dropGravatarRating));
checkEnableCommentDays.Attributes.Add("onclick",
String.Format(
"{0}if(document.getElementById('{1}').value == ''){{document.getElementById('{1}').value = '60';}}",
WebUtil.CreateEnableDisableScript(checkEnableCommentDays,
textDaysCommentsAllowed),
textDaysCommentsAllowed.ClientID));
}
#region Cleanup Routines
void CleanGeoRss()
{
checkEnableDefaultLatLongForNonGeoCodedPosts.Enabled = checkEnableGeoRss.Checked;
textDefaultLatitude.Enabled = checkEnableGeoRss.Checked;
textDefaultLongitude.Enabled = checkEnableGeoRss.Checked;
checkEnableGoogleMaps.Enabled = checkEnableGeoRss.Checked;
textGoogleMapsApi.Enabled = checkEnableGeoRss.Checked;
}
void CleanAutoExpire()
{
textDaysCommentsAllowed.Enabled = checkEnableCommentDays.Checked;
textDefaultLatitude.Enabled = checkEnableCommentDays.Checked;
textDefaultLongitude.Enabled = checkEnableCommentDays.Checked;
checkEnableGoogleMaps.Enabled = checkEnableCommentDays.Checked;
textGoogleMapsApi.Enabled = checkEnableCommentDays.Checked;
}
void CleanHtmlComments()
{
checkBoxListAllowedTags.Enabled = checkAllowHtml.Checked;
}
void CleanGravatar()
{
textGravatarSize.Enabled = checkEnableGravatar.Checked;
textNoGravatarPath.Enabled = checkEnableGravatar.Checked;
textGravatarBorderColor.Enabled = checkEnableGravatar.Checked;
dropGravatarRating.Enabled = checkEnableGravatar.Checked;
}
#endregion
#region Gravatar Support
void GravatarPopulateForm()
{
SharedBasePage requestPage = Page as SharedBasePage;
SiteConfig siteConfig = requestPage.SiteConfig;
checkEnableGravatar.Checked = siteConfig.CommentsAllowGravatar;
if (!String.IsNullOrEmpty(siteConfig.CommentsGravatarSize))
{
int gpix = Convert.ToInt32(siteConfig.CommentsGravatarSize);
if (gpix > 0)
{
textGravatarSize.Text = gpix.ToString();
}
else
{
textGravatarSize.Text = defaultGravatarSize;
}
}
if (siteConfig.CommentsGravatarNoImgPath != null)
{
textNoGravatarPath.Text = siteConfig.CommentsGravatarNoImgPath;
}
if (siteConfig.CommentsGravatarBorder != null)
{
textGravatarBorderColor.Text = siteConfig.CommentsGravatarBorder;
}
if (siteConfig.CommentsGravatarRating != null)
{
dropGravatarRating.SelectedValue = siteConfig.CommentsGravatarRating;
}
}
void GravatarPopulateConfig()
{
SharedBasePage requestPage = Page as SharedBasePage;
SiteConfig siteConfig = requestPage.SiteConfig;
siteConfig.CommentsAllowGravatar = checkEnableGravatar.Checked;
siteConfig.CommentsGravatarNoImgPath = textNoGravatarPath.Text.Trim();
siteConfig.CommentsGravatarBorder = textGravatarBorderColor.Text.Trim();
siteConfig.CommentsGravatarRating = dropGravatarRating.SelectedValue;
try
{
int gpix = Convert.ToInt32(textGravatarSize.Text.Trim());
if (gpix > 0 && gpix <= 80)
{
siteConfig.CommentsGravatarSize = gpix.ToString();
}
else
{
siteConfig.CommentsGravatarSize = defaultGravatarSize;
}
}
catch (FormatException)
{
siteConfig.CommentsGravatarSize = String.Empty;
}
}
#endregion
#region GeoRSS Validation
protected void cvDefaultLatitude_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
CheckBox chkEnableGeoRss = FindControl(checkEnableGeoRss.ID) as CheckBox;
CheckBox chkEnableDefaultLatLong = FindControl(checkEnableDefaultLatLongForNonGeoCodedPosts.ID) as CheckBox;
if (chkEnableGeoRss != null && chkEnableGeoRss.Checked &&
chkEnableDefaultLatLong != null && chkEnableDefaultLatLong.Checked)
{
double value;
if (double.TryParse(args.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
{
if (value >= -90d && value <= 90d)
{
args.IsValid = true;
}
}
}
else
{
args.IsValid = true;
}
}
protected void cvDefaultLongitude_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
CheckBox chkEnableGeoRss = FindControl(checkEnableGeoRss.ID) as CheckBox;
CheckBox chkEnableDefaultLatLong = FindControl(checkEnableDefaultLatLongForNonGeoCodedPosts.ID) as CheckBox;
if (chkEnableGeoRss != null && chkEnableGeoRss.Checked &&
chkEnableDefaultLatLong != null && chkEnableDefaultLatLong.Checked)
{
double value;
if (double.TryParse(args.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
{
if (value >= -180d && value <= 180d)
{
args.IsValid = true;
}
}
}
else
{
args.IsValid = true;
}
}
protected void cvGoogleMapsApi_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
CheckBox chkEnableGeoRss = FindControl(checkEnableGeoRss.ID) as CheckBox;
CheckBox chkGoogleMapsApi = FindControl(checkEnableGoogleMaps.ID) as CheckBox;
if (chkEnableGeoRss != null && chkEnableGeoRss.Checked &&
chkGoogleMapsApi != null && chkGoogleMapsApi.Checked)
{
args.IsValid = chkGoogleMapsApi.Checked && !String.IsNullOrEmpty(args.Value) ||
!chkGoogleMapsApi.Checked;
}
else
{
args.IsValid = true;
}
}
#endregion
#region Web Form Designer generated code
protected override void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
optionSpamHandling.Items.AddRange(new ListItem[]
{
new ListItem(resmgr.GetString("text_save_spam"), SPAM_OPTION_SAVE),
new ListItem(resmgr.GetString("text_delete_spam"), SPAM_OPTION_DELETE)
});
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent()
{
this.Init += new System.EventHandler(this.EditConfigBox_Init);
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.XWPF.Extractor
{
using System;
using NPOI.XWPF.Model;
using NPOI.XWPF.UserModel;
using NPOI.OpenXml4Net.OPC;
using System.Text;
using System.Collections.Generic;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.IO;
using System.Xml;
/**
* Helper class to extract text from an OOXML Word file
*/
public class XWPFWordExtractor : POIXMLTextExtractor
{
public static XWPFRelation[] SUPPORTED_TYPES = new XWPFRelation[] {
XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE,
XWPFRelation.MACRO_DOCUMENT,
XWPFRelation.MACRO_TEMPLATE_DOCUMENT
};
private XWPFDocument document;
private bool fetchHyperlinks = false;
public XWPFWordExtractor(OPCPackage Container)
: this(new XWPFDocument(Container))
{
}
public XWPFWordExtractor(XWPFDocument document)
: base(document)
{
this.document = document;
}
/**
* Should we also fetch the hyperlinks, when fetching
* the text content? Default is to only output the
* hyperlink label, and not the contents
*/
public void SetFetchHyperlinks(bool fetch)
{
fetchHyperlinks = fetch;
}
public override String Text
{
get
{
StringBuilder text = new StringBuilder();
XWPFHeaderFooterPolicy hfPolicy = document.GetHeaderFooterPolicy();
// Start out with all headers
ExtractHeaders(text, hfPolicy);
// body elements
foreach (IBodyElement e in document.BodyElements)
{
AppendBodyElementText(text, e);
text.Append('\n');
}
// Finish up with all the footers
ExtractFooters(text, hfPolicy);
return text.ToString();
}
}
public void AppendBodyElementText(StringBuilder text, IBodyElement e)
{
if (e is XWPFParagraph)
{
AppendParagraphText(text, (XWPFParagraph)e);
}
else if (e is XWPFTable)
{
AppendTableText(text, (XWPFTable)e);
}
else if (e is XWPFSDT)
{
text.Append(((XWPFSDT)e).Content.Text);
}
}
public void AppendParagraphText(StringBuilder text, XWPFParagraph paragraph)
{
try
{
CT_SectPr ctSectPr = null;
if (paragraph.GetCTP().pPr != null)
{
ctSectPr = paragraph.GetCTP().pPr.sectPr;
}
XWPFHeaderFooterPolicy headerFooterPolicy = null;
if (ctSectPr != null)
{
headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr);
ExtractHeaders(text, headerFooterPolicy);
}
foreach (IRunElement run in paragraph.Runs)
{
text.Append(run.ToString());
if (run is XWPFHyperlinkRun && fetchHyperlinks)
{
XWPFHyperlink link = ((XWPFHyperlinkRun)run).GetHyperlink(document);
if (link != null)
text.Append(" <" + link.URL + ">");
}
}
// Add comments
XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null);
String commentText = decorator.GetCommentText();
if (commentText.Length > 0)
{
text.Append(commentText).Append('\n');
}
// Do endnotes and footnotes
String footnameText = paragraph.FootnoteText;
if (footnameText != null && footnameText.Length > 0)
{
text.Append(footnameText + '\n');
}
if (ctSectPr != null)
{
ExtractFooters(text, headerFooterPolicy);
}
}
catch (IOException e)
{
throw new POIXMLException(e);
}
catch (XmlException e)
{
throw new POIXMLException(e);
}
}
private void AppendTableText(StringBuilder text, XWPFTable table)
{
//this works recursively to pull embedded tables from tables
foreach (XWPFTableRow row in table.Rows)
{
List<ICell> cells = row.GetTableICells();
for (int i = 0; i < cells.Count; i++)
{
ICell cell = cells[(i)];
if (cell is XWPFTableCell)
{
text.Append(((XWPFTableCell)cell).GetTextRecursively());
}
else if (cell is XWPFSDTCell)
{
text.Append(((XWPFSDTCell)cell).Content.Text);
}
if (i < cells.Count - 1)
{
text.Append("\t");
}
}
text.Append('\n');
}
}
private void ExtractFooters(StringBuilder text, XWPFHeaderFooterPolicy hfPolicy)
{
if (hfPolicy == null) return;
if (hfPolicy.GetFirstPageFooter() != null)
{
text.Append(hfPolicy.GetFirstPageFooter().Text);
}
if (hfPolicy.GetEvenPageFooter() != null)
{
text.Append(hfPolicy.GetEvenPageFooter().Text);
}
if (hfPolicy.GetDefaultFooter() != null)
{
text.Append(hfPolicy.GetDefaultFooter().Text);
}
}
private void ExtractHeaders(StringBuilder text, XWPFHeaderFooterPolicy hfPolicy)
{
if (hfPolicy == null) return;
if (hfPolicy.GetFirstPageHeader() != null)
{
text.Append(hfPolicy.GetFirstPageHeader().Text);
}
if (hfPolicy.GetEvenPageHeader() != null)
{
text.Append(hfPolicy.GetEvenPageHeader().Text);
}
if (hfPolicy.GetDefaultHeader() != null)
{
text.Append(hfPolicy.GetDefaultHeader().Text);
}
}
}
}
| |
//------------------------------------------
// WireBase.cs (c) 2007 by Charles Petzold
//
// The inspiration, concept, technique, and
// some of the code for this class came
// from the ScreenSpaceLines3D class
// in 3DTools at www.codeplex.com/3DTools.
//------------------------------------------
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using Petzold.Media2D; // for ArrowEnds enumeration
namespace Petzold.Media3D
{
/// <summary>
///
/// </summary>
public abstract class WireBase : ModelVisual3D
{
// Static fields for storing instances of WireBase.
static List<WireBaseAndUltimateParent> listWireBases = new List<WireBaseAndUltimateParent>();
static List<WireBaseAndUltimateParent> listRemove = new List<WireBaseAndUltimateParent>();
// Instance fields.
bool needRecalculation = true;
Matrix3D matxVisualToScreen = Matrix3D.Identity;
Matrix3D matxScreenToVisual;
RotateTransform rotate = new RotateTransform();
// Constructor
// -----------
public WireBase()
{
LineCollection = new Point3DCollection();
// Create MeshGeometry3D.
MeshGeometry3D mesh = new MeshGeometry3D();
// Create MaterialGroup.
MaterialGroup matgrp = new MaterialGroup();
matgrp.Children.Add(new DiffuseMaterial(Brushes.Black));
matgrp.Children.Add(new EmissiveMaterial(new SolidColorBrush(Color)));
// Create GeometryModel3D.
GeometryModel3D model = new GeometryModel3D(mesh, matgrp);
// Remove this later
model.BackMaterial = new DiffuseMaterial(Brushes.Red);
// Set the Content property to the GeometryModel3D.
Content = model;
// Add to collection.
listWireBases.Add(new WireBaseAndUltimateParent(this));
}
// Static constructor attaches Rendering handler for all instances.
static WireBase()
{
CompositionTarget.Rendering += new EventHandler(OnRendering);
}
private static readonly DependencyPropertyKey LineCollectionKey =
DependencyProperty.RegisterReadOnly("LineCollection",
typeof(Point3DCollection),
typeof(WireBase),
new PropertyMetadata(null, RecalcPropertyChanged));
/// <summary>
/// Identifies the BaseLines dependency property.
/// </summary>
public static readonly DependencyProperty LineCollectionProperty =
LineCollectionKey.DependencyProperty;
/// <summary>
///
/// </summary>
public Point3DCollection LineCollection
{
private set { SetValue(LineCollectionKey, value); }
get { return (Point3DCollection)GetValue(LineCollectionProperty); }
}
/// <summary>
/// Identifies the Color depencency property.
/// </summary>
public static readonly DependencyProperty ColorProperty =
DependencyProperty.Register("Color",
typeof(Color),
typeof(WireBase),
new PropertyMetadata(Colors.Black, ColorPropertyChanged));
/// <summary>
///
/// </summary>
public Color Color
{
set { SetValue(ColorProperty, value); }
get { return (Color)GetValue(ColorProperty); }
}
//
// This is the only property that does not require a recalculation
// of the MeshGeometry3D.
static void ColorPropertyChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
WireBase wirebase = obj as WireBase;
GeometryModel3D model = wirebase.Content as GeometryModel3D;
MaterialGroup matgrp = model.Material as MaterialGroup;
EmissiveMaterial mat = matgrp.Children[1] as EmissiveMaterial;
mat.Brush = new SolidColorBrush((Color)args.NewValue);
}
/// <summary>
/// Identifies the Thickness dependency property.
/// </summary>
public static readonly DependencyProperty ThicknessProperty =
DependencyProperty.Register("Thickness",
typeof(double),
typeof(WireBase),
new PropertyMetadata(1.0, RecalcPropertyChanged));
/// <summary>
///
/// </summary>
public double Thickness
{
set { SetValue(ThicknessProperty, value); }
get { return (double)GetValue(ThicknessProperty); }
}
// Rounding property -- CHECK FOR VALUES < ZERO
// -----------------
public static readonly DependencyProperty RoundingProperty =
DependencyProperty.Register("Rounding",
typeof(int),
typeof(WireBase),
new PropertyMetadata(0, RecalcPropertyChanged));
public int Rounding
{
set { SetValue(RoundingProperty, value); }
get { return (int)GetValue(RoundingProperty); }
}
/// <summary>
/// Identifies the ArrowAngle dependency property.
/// </summary>
public static readonly DependencyProperty ArrowAngleProperty =
DependencyProperty.Register("ArrowAngle",
typeof(double), typeof(WireBase),
new PropertyMetadata(45.0, RecalcPropertyChanged));
/// <summary>
/// Gets or sets the angle between the two sides of the arrowhead.
/// </summary>
public double ArrowAngle
{
set { SetValue(ArrowAngleProperty, value); }
get { return (double)GetValue(ArrowAngleProperty); }
}
/// <summary>
/// Identifies the ArrowLength dependency property.
/// </summary>
public static readonly DependencyProperty ArrowLengthProperty =
DependencyProperty.Register("ArrowLength",
typeof(double), typeof(WireBase),
new PropertyMetadata(12.0, RecalcPropertyChanged));
/// <summary>
/// Gets or sets the length of the two sides of the arrowhead.
/// </summary>
public double ArrowLength
{
set { SetValue(ArrowLengthProperty, value); }
get { return (double)GetValue(ArrowLengthProperty); }
}
/// <summary>
/// Identifies the ArrowEnds dependency property.
/// </summary>
public static readonly DependencyProperty ArrowEndsProperty =
DependencyProperty.Register("ArrowEnds",
typeof(ArrowEnds), typeof(WireBase),
new PropertyMetadata(ArrowEnds.None, RecalcPropertyChanged));
/// <summary>
/// Gets or sets the property that determines which ends of the
/// line have arrows.
/// </summary>
public ArrowEnds ArrowEnds
{
set { SetValue(ArrowEndsProperty, value); }
get { return (ArrowEnds)GetValue(ArrowEndsProperty); }
}
static void RecalcPropertyChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
WireBase linebase = obj as WireBase;
linebase.needRecalculation = true;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <param name="args"></param>
protected static void PropertyChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
(obj as WireBase).PropertyChanged(args);
}
protected void PropertyChanged(DependencyPropertyChangedEventArgs args)
{
Point3DCollection lines = LineCollection;
LineCollection = null;
Generate(args, lines);
LineCollection = lines;
}
/// <summary>
/// Sets the coordinates of all the individual lines in the visual.
/// </summary>
/// <param name="args">
/// The <c>DependencyPropertyChangedEventArgs</c> object associated
/// with the property-changed event that resulted in this method
/// being called.
/// </param>
/// <param name="lines">
/// The <c>Point3DCollection</c> to be filled.
/// </param>
/// <remarks>
/// <para>
/// Classes that derive from <c>WireBase</c> override this
/// method to fill the <c>lines</c> collection.
/// It is custmary for implementations of this method to clear
/// the <c>lines</c> collection first before filling it.
/// Each pair of successive members of the <c>lines</c>
/// collection indicate one straight line.
/// </para>
/// </remarks>
protected abstract void Generate(DependencyPropertyChangedEventArgs args,
Point3DCollection lines);
static void OnRendering(object sender, EventArgs args)
{
foreach (WireBaseAndUltimateParent wirebaseAndParent in listWireBases)
{
WireBase wirebase = wirebaseAndParent.wirebase;
DependencyObject obj = wirebase;
while (obj != null && !(obj is Window))
{
obj = VisualTreeHelper.GetParent(obj);
}
if (wirebaseAndParent.window == null)
{
if (obj != null)
{
wirebaseAndParent.window = obj as Window;
}
// Otherwise, the WireBase has no ultimate parent of type window,
// so there's no reason to try rendering it.
else
{
continue;
}
}
// A non-null 'window' field means the WireBase had an ultimate window
// parent at one time.
else
{
// But now there's no ultimate window parent, so it's likely that
// this WireBase has been disconnected from a valid visual tree.
if (obj == null)
{
listRemove.Add(wirebaseAndParent);
continue;
}
}
wirebase.OnRendering();
}
// Possibly remove objects from the rendering list.
if (listRemove.Count > 0)
{
foreach (WireBaseAndUltimateParent wirebaseAndParent in listRemove)
{
listWireBases.Remove(wirebaseAndParent);
}
listRemove.Clear();
}
}
void OnRendering()
{
if (LineCollection.Count == 0)
{
return;
}
Matrix3D matx = VisualInfo.GetTotalTransform(this);
if (matx == VisualInfo.ZeroMatrix)
{
return;
}
// How can this happen????
if (matx.IsIdentity)
{
return;
}
if (matx != matxVisualToScreen)
{
matxVisualToScreen = matx;
matxScreenToVisual = matx;
if (matxScreenToVisual.HasInverse)
{
matxScreenToVisual.Invert(); // might not be possible !!!!!!
needRecalculation = true;
}
else
throw new ApplicationException("Here's where the problem is");
}
if (needRecalculation)
{
Recalculate();
needRecalculation = false;
}
}
void Recalculate()
{
GeometryModel3D model = Content as GeometryModel3D;
MeshGeometry3D mesh = model.Geometry as MeshGeometry3D;
Point3DCollection points = mesh.Positions;
mesh.Positions = null;
points.Clear();
Int32Collection indices = mesh.TriangleIndices;
mesh.TriangleIndices = null;
indices.Clear();
int indicesBase = 0;
Point3DCollection lines = LineCollection;
for (int line = 0; line < lines.Count - 1; line += 2)
{
Point3D pt1 = lines[line + 0];
Point3D pt2 = lines[line + 1];
DoLine(pt1, pt2, points, indices, ref indicesBase);
if (line == 0 &&
(ArrowEnds & ArrowEnds.Start) == ArrowEnds.Start)
DoArrow(pt2, pt1, points, indices, ref indicesBase);
if (line > lines.Count - 4 &&
(ArrowEnds & ArrowEnds.End) == ArrowEnds.End)
DoArrow(pt1, pt2, points, indices, ref indicesBase);
}
mesh.TriangleIndices = indices;
mesh.Positions = points;
}
void DoArrow(Point3D pt1, Point3D pt2, Point3DCollection points,
Int32Collection indices, ref int indicesBase)
{
Point3D pt1Screen = pt1 * matxVisualToScreen;
Point3D pt2Screen = pt2 * matxVisualToScreen;
Vector vectArrow = new Vector(pt1Screen.X - pt2Screen.X,
pt1Screen.Y - pt2Screen.Y);
vectArrow.Normalize();
vectArrow *= ArrowLength;
Matrix matx = new Matrix();
matx.Rotate(ArrowAngle / 2);
Point3D ptArrow1 = Widen(pt2, vectArrow * matx);
matx.Rotate(-ArrowAngle);
Point3D ptArrow2 = Widen(pt2, vectArrow * matx);
DoLine(pt2, ptArrow1, points, indices, ref indicesBase);
DoLine(pt2, ptArrow2, points, indices, ref indicesBase);
}
void DoLine(Point3D pt1, Point3D pt2, Point3DCollection points,
Int32Collection indices, ref int indicesBase)
{
Point3D pt1Screen = pt1 * matxVisualToScreen;
Point3D pt2Screen = pt2 * matxVisualToScreen;
Vector3D vectLine = pt2Screen - pt1Screen;
vectLine.Z = 0;
vectLine.Normalize();
Vector delta = (Thickness / 2) * new Vector(-vectLine.Y, vectLine.X);
points.Add(Widen(pt1, delta));
points.Add(Widen(pt1, -delta));
points.Add(Widen(pt2, delta));
points.Add(Widen(pt2, -delta));
indices.Add(indicesBase);
indices.Add(indicesBase + 2);
indices.Add(indicesBase + 1);
indices.Add(indicesBase + 1);
indices.Add(indicesBase + 2);
indices.Add(indicesBase + 3);
indicesBase += 4;
if (Rounding > 0)
{
AddRounding(pt1, delta, points, indices, ref indicesBase);
AddRounding(pt2, -delta, points, indices, ref indicesBase);
}
}
Point3D Widen(Point3D pointIn, Vector delta)
{
Point4D pt4In = (Point4D)pointIn;
Point4D pt4Out = pt4In * matxVisualToScreen;
pt4Out.X += delta.X * pt4Out.W;
pt4Out.Y += delta.Y * pt4Out.W;
pt4Out *= matxScreenToVisual;
Point3D ptOut = new Point3D(pt4Out.X / pt4Out.W,
pt4Out.Y / pt4Out.W,
pt4Out.Z / pt4Out.W);
return ptOut;
}
void AddRounding(Point3D ptIn, Vector delta, Point3DCollection points,
Int32Collection indices, ref int indicesCount)
{
points.Add(CalculatePoint(ptIn, new Vector(0, 0), 0));
for (int i = 0; i <= Rounding; i++)
points.Add(CalculatePoint(ptIn, delta, 180 * i / Rounding));
for (int i = 0; i < Rounding; i++)
{
indices.Add(indicesCount);
indices.Add(indicesCount + i + 2);
indices.Add(indicesCount + i + 1);
}
indicesCount += Rounding + 2;
}
Point3D CalculatePoint(Point3D ptIn, Vector delta, double angle)
{
Point4D pt4In = (Point4D)ptIn;
Point4D pt4Out = pt4In * matxVisualToScreen;
rotate.Angle = angle;
delta = (Vector)rotate.Transform((Point)delta);
pt4Out.X += delta.X * pt4Out.W;
pt4Out.Y += delta.Y * pt4Out.W;
pt4Out *= matxScreenToVisual;
Point3D ptOut = new Point3D(pt4Out.X / pt4Out.W,
pt4Out.Y / pt4Out.W,
pt4Out.Z / pt4Out.W);
return ptOut;
}
}
}
| |
using System;
namespace Thinktecture.Adapters
{
/// <summary>
/// Adapter for <see cref="Math"/>.
/// </summary>
public class MathAdapter : IMath
{
/// <inheritdoc />
public double PI => Math.PI;
/// <inheritdoc />
public double E => Math.E;
#if NET5_0
/// <inheritdoc />
public double Tau => Math.Tau;
#endif
/// <inheritdoc />
public byte Clamp(byte value, byte min, byte max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public decimal Clamp(decimal value, decimal min, decimal max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public double Clamp(double value, double min, double max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public float Clamp(float value, float min, float max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public int Clamp(int value, int min, int max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public long Clamp(long value, long min, long max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public sbyte Clamp(sbyte value, sbyte min, sbyte max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public short Clamp(short value, short min, short max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public uint Clamp(uint value, uint min, uint max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public ulong Clamp(ulong value, ulong min, ulong max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public ushort Clamp(ushort value, ushort min, ushort max)
{
return Math.Clamp(value, min, max);
}
/// <inheritdoc />
public double Acosh(double value)
{
return Math.Acosh(value);
}
/// <inheritdoc />
public double Asinh(double value)
{
return Math.Asinh(value);
}
/// <inheritdoc />
public double Atanh(double value)
{
return Math.Atanh(value);
}
/// <inheritdoc />
public double Cbrt(double value)
{
return Math.Cbrt(value);
}
/// <inheritdoc />
public decimal Abs(decimal value)
{
return Math.Abs(value);
}
/// <inheritdoc />
public double Abs(double value)
{
return Math.Abs(value);
}
/// <inheritdoc />
public short Abs(short value)
{
return Math.Abs(value);
}
/// <inheritdoc />
public int Abs(int value)
{
return Math.Abs(value);
}
/// <inheritdoc />
public long Abs(long value)
{
return Math.Abs(value);
}
/// <inheritdoc />
public sbyte Abs(sbyte value)
{
return Math.Abs(value);
}
/// <inheritdoc />
public float Abs(float value)
{
return Math.Abs(value);
}
/// <inheritdoc />
public double Acos(double d)
{
return Math.Acos(d);
}
/// <inheritdoc />
public double Asin(double d)
{
return Math.Asin(d);
}
/// <inheritdoc />
public double Atan(double d)
{
return Math.Atan(d);
}
/// <inheritdoc />
public double Atan2(double y, double x)
{
return Math.Atan2(y, x);
}
/// <inheritdoc />
public decimal Ceiling(decimal d)
{
return Math.Ceiling(d);
}
/// <inheritdoc />
public double Ceiling(double a)
{
return Math.Ceiling(a);
}
/// <inheritdoc />
public double Cos(double d)
{
return Math.Cos(d);
}
/// <inheritdoc />
public double Cosh(double value)
{
return Math.Cosh(value);
}
/// <inheritdoc />
public double Exp(double d)
{
return Math.Exp(d);
}
/// <inheritdoc />
public decimal Floor(decimal d)
{
return Math.Floor(d);
}
/// <inheritdoc />
public double Floor(double d)
{
return Math.Floor(d);
}
/// <inheritdoc />
public double IEEERemainder(double x, double y)
{
return Math.IEEERemainder(x, y);
}
/// <inheritdoc />
public double Log(double d)
{
return Math.Log(d);
}
/// <inheritdoc />
public double Log(double a, double newBase)
{
return Math.Log(a, newBase);
}
/// <inheritdoc />
public double Log10(double d)
{
return Math.Log10(d);
}
/// <inheritdoc />
public byte Max(byte val1, byte val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public decimal Max(decimal val1, decimal val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public double Max(double val1, double val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public short Max(short val1, short val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public int Max(int val1, int val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public long Max(long val1, long val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public sbyte Max(sbyte val1, sbyte val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public float Max(float val1, float val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public ushort Max(ushort val1, ushort val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public uint Max(uint val1, uint val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public ulong Max(ulong val1, ulong val2)
{
return Math.Max(val1, val2);
}
/// <inheritdoc />
public byte Min(byte val1, byte val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public decimal Min(decimal val1, decimal val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public double Min(double val1, double val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public short Min(short val1, short val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public int Min(int val1, int val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public long Min(long val1, long val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public sbyte Min(sbyte val1, sbyte val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public float Min(float val1, float val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public ushort Min(ushort val1, ushort val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public uint Min(uint val1, uint val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public ulong Min(ulong val1, ulong val2)
{
return Math.Min(val1, val2);
}
/// <inheritdoc />
public double Pow(double x, double y)
{
return Math.Pow(x, y);
}
/// <inheritdoc />
public decimal Round(decimal d)
{
return Math.Round(d);
}
/// <inheritdoc />
public decimal Round(decimal d, int decimals)
{
return Math.Round(d, decimals);
}
/// <inheritdoc />
public decimal Round(decimal d, int decimals, MidpointRounding mode)
{
return Math.Round(d, decimals, mode);
}
/// <inheritdoc />
public decimal Round(decimal d, MidpointRounding mode)
{
return Math.Round(d, mode);
}
/// <inheritdoc />
public double Round(double a)
{
return Math.Round(a);
}
/// <inheritdoc />
public double Round(double value, int digits)
{
return Math.Round(value, digits);
}
/// <inheritdoc />
public double Round(double value, int digits, MidpointRounding mode)
{
return Math.Round(value, digits, mode);
}
/// <inheritdoc />
public double Round(double value, MidpointRounding mode)
{
return Math.Round(value, mode);
}
/// <inheritdoc />
public int Sign(decimal value)
{
return Math.Sign(value);
}
/// <inheritdoc />
public int Sign(double value)
{
return Math.Sign(value);
}
/// <inheritdoc />
public int Sign(short value)
{
return Math.Sign(value);
}
/// <inheritdoc />
public int Sign(int value)
{
return Math.Sign(value);
}
/// <inheritdoc />
public int Sign(long value)
{
return Math.Sign(value);
}
/// <inheritdoc />
public int Sign(sbyte value)
{
return Math.Sign(value);
}
/// <inheritdoc />
public int Sign(float value)
{
return Math.Sign(value);
}
/// <inheritdoc />
public double Sin(double a)
{
return Math.Sin(a);
}
/// <inheritdoc />
public double Sinh(double value)
{
return Math.Sinh(value);
}
/// <inheritdoc />
public double Sqrt(double d)
{
return Math.Sqrt(d);
}
/// <inheritdoc />
public double Tan(double a)
{
return Math.Tan(a);
}
/// <inheritdoc />
public double Tanh(double value)
{
return Math.Tanh(value);
}
/// <inheritdoc />
public decimal Truncate(decimal d)
{
return Math.Truncate(d);
}
/// <inheritdoc />
public double Truncate(double d)
{
return Math.Truncate(d);
}
/// <inheritdoc />
public long BigMul(int a, int b)
{
return Math.BigMul(a, b);
}
#if NET5_0
/// <inheritdoc />
public long BigMul(long a, long b, out long low)
{
return Math.BigMul(a, b, out low);
}
/// <inheritdoc />
public ulong BigMul(ulong a, ulong b, out ulong low)
{
return Math.BigMul(a, b, out low);
}
#endif
/// <inheritdoc />
public int DivRem(int a, int b, out int result)
{
return Math.DivRem(a, b, out result);
}
/// <inheritdoc />
public long DivRem(long a, long b, out long result)
{
return Math.DivRem(a, b, out result);
}
#if NETCOREAPP || NET5_0
/// <inheritdoc />
public double FusedMultiplyAdd(double x, double y, double z)
{
return Math.FusedMultiplyAdd(x, y, z);
}
/// <inheritdoc />
public int ILogB(double x)
{
return Math.ILogB(x);
}
/// <inheritdoc />
public double Log2(double x)
{
return Math.Log2(x);
}
/// <inheritdoc />
public double ScaleB(double x, int n)
{
return Math.ScaleB(x, n);
}
/// <inheritdoc />
public double BitDecrement(double x)
{
return Math.BitDecrement(x);
}
/// <inheritdoc />
public double BitIncrement(double x)
{
return Math.BitIncrement(x);
}
/// <inheritdoc />
public double CopySign(double x, double y)
{
return Math.CopySign(x, y);
}
/// <inheritdoc />
public double MaxMagnitude(double x, double y)
{
return Math.MaxMagnitude(x, y);
}
/// <inheritdoc />
public double MinMagnitude(double x, double y)
{
return Math.MinMagnitude(x, y);
}
#endif
}
}
| |
/*
* 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 ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the RunInstances operation.
/// Launches the specified number of instances using an AMI for which you have permissions.
///
///
/// <para>
/// When you launch an instance, it enters the <code>pending</code> state. After the instance
/// is ready for you, it enters the <code>running</code> state. To check the state of
/// your instance, call <a>DescribeInstances</a>.
/// </para>
///
/// <para>
/// If you don't specify a security group when launching an instance, Amazon EC2 uses
/// the default security group. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Security
/// Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// [EC2-VPC only accounts] If you don't specify a subnet in the request, we choose a
/// default subnet from your default VPC for you.
/// </para>
///
/// <para>
/// [EC2-Classic accounts] If you're launching into EC2-Classic and you don't specify
/// an Availability Zone, we choose one for you.
/// </para>
///
/// <para>
/// Linux instances have access to the public key of the key pair at boot. You can use
/// this key to provide secure access to the instance. Amazon EC2 public images use this
/// feature to provide secure access without passwords. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Key
/// Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// You can provide optional user data when launching an instance. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html">Instance
/// Metadata</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// If any of the AMIs have a product code attached for which the user has not subscribed,
/// <code>RunInstances</code> fails.
/// </para>
///
/// <para>
/// T2 instance types can only be launched into a VPC. If you do not have a default VPC,
/// or if you do not specify a subnet ID in the request, <code>RunInstances</code> fails.
/// </para>
///
/// <para>
/// For more information about troubleshooting, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html">What
/// To Do If An Instance Immediately Terminates</a>, and <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html">Troubleshooting
/// Connecting to Your Instance</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </summary>
public partial class RunInstancesRequest : AmazonEC2Request
{
private string _additionalInfo;
private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>();
private string _clientToken;
private bool? _disableApiTermination;
private bool? _ebsOptimized;
private IamInstanceProfileSpecification _iamInstanceProfile;
private string _imageId;
private ShutdownBehavior _instanceInitiatedShutdownBehavior;
private InstanceType _instanceType;
private string _kernelId;
private string _keyName;
private int? _maxCount;
private int? _minCount;
private bool? _monitoring;
private List<InstanceNetworkInterfaceSpecification> _networkInterfaces = new List<InstanceNetworkInterfaceSpecification>();
private Placement _placement;
private string _privateIpAddress;
private string _ramdiskId;
private List<string> _securityGroupIds = new List<string>();
private List<string> _securityGroups = new List<string>();
private string _subnetId;
private string _userData;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public RunInstancesRequest() { }
/// <summary>
/// Instantiates RunInstancesRequest with the parameterized properties
/// </summary>
/// <param name="imageId">The ID of the AMI, which you can get by calling <a>DescribeImages</a>.</param>
/// <param name="minCount">The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see <a href="http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2">How many instances can I run in Amazon EC2</a> in the Amazon EC2 General FAQ.</param>
/// <param name="maxCount">The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above <code>MinCount</code>. Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see <a href="http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2">How many instances can I run in Amazon EC2</a> in the Amazon EC2 General FAQ.</param>
public RunInstancesRequest(string imageId, int minCount, int maxCount)
{
_imageId = imageId;
_minCount = minCount;
_maxCount = maxCount;
}
/// <summary>
/// Gets and sets the property AdditionalInfo.
/// <para>
/// Reserved.
/// </para>
/// </summary>
public string AdditionalInfo
{
get { return this._additionalInfo; }
set { this._additionalInfo = value; }
}
// Check to see if AdditionalInfo property is set
internal bool IsSetAdditionalInfo()
{
return this._additionalInfo != null;
}
/// <summary>
/// Gets and sets the property BlockDeviceMappings.
/// <para>
/// The block device mapping.
/// </para>
/// </summary>
public List<BlockDeviceMapping> BlockDeviceMappings
{
get { return this._blockDeviceMappings; }
set { this._blockDeviceMappings = value; }
}
// Check to see if BlockDeviceMappings property is set
internal bool IsSetBlockDeviceMappings()
{
return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property ClientToken.
/// <para>
/// Unique, case-sensitive identifier you provide to ensure the idempotency of the request.
/// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html">Ensuring
/// Idempotency</a>.
/// </para>
///
/// <para>
/// Constraints: Maximum 64 ASCII characters
/// </para>
/// </summary>
public string ClientToken
{
get { return this._clientToken; }
set { this._clientToken = value; }
}
// Check to see if ClientToken property is set
internal bool IsSetClientToken()
{
return this._clientToken != null;
}
/// <summary>
/// Gets and sets the property DisableApiTermination.
/// <para>
/// If you set this parameter to <code>true</code>, you can't terminate the instance using
/// the Amazon EC2 console, CLI, or API; otherwise, you can. If you set this parameter
/// to <code>true</code> and then later want to be able to terminate the instance, you
/// must first change the value of the <code>disableApiTermination</code> attribute to
/// <code>false</code> using <a>ModifyInstanceAttribute</a>. Alternatively, if you set
/// <code>InstanceInitiatedShutdownBehavior</code> to <code>terminate</code>, you can
/// terminate the instance by running the shutdown command from the instance.
/// </para>
///
/// <para>
/// Default: <code>false</code>
/// </para>
/// </summary>
public bool DisableApiTermination
{
get { return this._disableApiTermination.GetValueOrDefault(); }
set { this._disableApiTermination = value; }
}
// Check to see if DisableApiTermination property is set
internal bool IsSetDisableApiTermination()
{
return this._disableApiTermination.HasValue;
}
/// <summary>
/// Gets and sets the property EbsOptimized.
/// <para>
/// Indicates whether the instance is optimized for EBS I/O. This optimization provides
/// dedicated throughput to Amazon EBS and an optimized configuration stack to provide
/// optimal EBS I/O performance. This optimization isn't available with all instance types.
/// Additional usage charges apply when using an EBS-optimized instance.
/// </para>
///
/// <para>
/// Default: <code>false</code>
/// </para>
/// </summary>
public bool EbsOptimized
{
get { return this._ebsOptimized.GetValueOrDefault(); }
set { this._ebsOptimized = value; }
}
// Check to see if EbsOptimized property is set
internal bool IsSetEbsOptimized()
{
return this._ebsOptimized.HasValue;
}
/// <summary>
/// Gets and sets the property IamInstanceProfile.
/// <para>
/// The IAM instance profile.
/// </para>
/// </summary>
public IamInstanceProfileSpecification IamInstanceProfile
{
get { return this._iamInstanceProfile; }
set { this._iamInstanceProfile = value; }
}
// Check to see if IamInstanceProfile property is set
internal bool IsSetIamInstanceProfile()
{
return this._iamInstanceProfile != null;
}
/// <summary>
/// Gets and sets the property ImageId.
/// <para>
/// The ID of the AMI, which you can get by calling <a>DescribeImages</a>.
/// </para>
/// </summary>
public string ImageId
{
get { return this._imageId; }
set { this._imageId = value; }
}
// Check to see if ImageId property is set
internal bool IsSetImageId()
{
return this._imageId != null;
}
/// <summary>
/// Gets and sets the property InstanceInitiatedShutdownBehavior.
/// <para>
/// Indicates whether an instance stops or terminates when you initiate shutdown from
/// the instance (using the operating system command for system shutdown).
/// </para>
///
/// <para>
/// Default: <code>stop</code>
/// </para>
/// </summary>
public ShutdownBehavior InstanceInitiatedShutdownBehavior
{
get { return this._instanceInitiatedShutdownBehavior; }
set { this._instanceInitiatedShutdownBehavior = value; }
}
// Check to see if InstanceInitiatedShutdownBehavior property is set
internal bool IsSetInstanceInitiatedShutdownBehavior()
{
return this._instanceInitiatedShutdownBehavior != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html">Instance
/// Types</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// Default: <code>m1.small</code>
/// </para>
/// </summary>
public InstanceType InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property KernelId.
/// <para>
/// The ID of the kernel.
/// </para>
/// <important>
/// <para>
/// We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html">
/// PV-GRUB</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </important>
/// </summary>
public string KernelId
{
get { return this._kernelId; }
set { this._kernelId = value; }
}
// Check to see if KernelId property is set
internal bool IsSetKernelId()
{
return this._kernelId != null;
}
/// <summary>
/// Gets and sets the property KeyName.
/// <para>
/// The name of the key pair. You can create a key pair using <a>CreateKeyPair</a> or
/// <a>ImportKeyPair</a>.
/// </para>
/// <important>
/// <para>
/// If you do not specify a key pair, you can't connect to the instance unless you choose
/// an AMI that is configured to allow users another way to log in.
/// </para>
/// </important>
/// </summary>
public string KeyName
{
get { return this._keyName; }
set { this._keyName = value; }
}
// Check to see if KeyName property is set
internal bool IsSetKeyName()
{
return this._keyName != null;
}
/// <summary>
/// Gets and sets the property MaxCount.
/// <para>
/// The maximum number of instances to launch. If you specify more instances than Amazon
/// EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible
/// number of instances above <code>MinCount</code>.
/// </para>
///
/// <para>
/// Constraints: Between 1 and the maximum number you're allowed for the specified instance
/// type. For more information about the default limits, and how to request an increase,
/// see <a href="http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2">How
/// many instances can I run in Amazon EC2</a> in the Amazon EC2 General FAQ.
/// </para>
/// </summary>
public int MaxCount
{
get { return this._maxCount.GetValueOrDefault(); }
set { this._maxCount = value; }
}
// Check to see if MaxCount property is set
internal bool IsSetMaxCount()
{
return this._maxCount.HasValue;
}
/// <summary>
/// Gets and sets the property MinCount.
/// <para>
/// The minimum number of instances to launch. If you specify a minimum that is more instances
/// than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no
/// instances.
/// </para>
///
/// <para>
/// Constraints: Between 1 and the maximum number you're allowed for the specified instance
/// type. For more information about the default limits, and how to request an increase,
/// see <a href="http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2">How
/// many instances can I run in Amazon EC2</a> in the Amazon EC2 General FAQ.
/// </para>
/// </summary>
public int MinCount
{
get { return this._minCount.GetValueOrDefault(); }
set { this._minCount = value; }
}
// Check to see if MinCount property is set
internal bool IsSetMinCount()
{
return this._minCount.HasValue;
}
/// <summary>
/// Gets and sets the property Monitoring.
/// <para>
/// The monitoring for the instance.
/// </para>
/// </summary>
public bool Monitoring
{
get { return this._monitoring.GetValueOrDefault(); }
set { this._monitoring = value; }
}
// Check to see if Monitoring property is set
internal bool IsSetMonitoring()
{
return this._monitoring.HasValue;
}
/// <summary>
/// Gets and sets the property NetworkInterfaces.
/// <para>
/// One or more network interfaces.
/// </para>
/// </summary>
public List<InstanceNetworkInterfaceSpecification> NetworkInterfaces
{
get { return this._networkInterfaces; }
set { this._networkInterfaces = value; }
}
// Check to see if NetworkInterfaces property is set
internal bool IsSetNetworkInterfaces()
{
return this._networkInterfaces != null && this._networkInterfaces.Count > 0;
}
/// <summary>
/// Gets and sets the property Placement.
/// <para>
/// The placement for the instance.
/// </para>
/// </summary>
public Placement Placement
{
get { return this._placement; }
set { this._placement = value; }
}
// Check to see if Placement property is set
internal bool IsSetPlacement()
{
return this._placement != null;
}
/// <summary>
/// Gets and sets the property PrivateIpAddress.
/// <para>
/// [EC2-VPC] The primary IP address. You must specify a value from the IP address range
/// of the subnet.
/// </para>
///
/// <para>
/// Only one private IP address can be designated as primary. Therefore, you can't specify
/// this parameter if <code>PrivateIpAddresses.n.Primary</code> is set to <code>true</code>
/// and <code>PrivateIpAddresses.n.PrivateIpAddress</code> is set to an IP address.
/// </para>
///
/// <para>
/// Default: We select an IP address from the IP address range of the subnet.
/// </para>
/// </summary>
public string PrivateIpAddress
{
get { return this._privateIpAddress; }
set { this._privateIpAddress = value; }
}
// Check to see if PrivateIpAddress property is set
internal bool IsSetPrivateIpAddress()
{
return this._privateIpAddress != null;
}
/// <summary>
/// Gets and sets the property RamdiskId.
/// <para>
/// The ID of the RAM disk.
/// </para>
/// <important>
/// <para>
/// We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html">
/// PV-GRUB</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
/// </important>
/// </summary>
public string RamdiskId
{
get { return this._ramdiskId; }
set { this._ramdiskId = value; }
}
// Check to see if RamdiskId property is set
internal bool IsSetRamdiskId()
{
return this._ramdiskId != null;
}
/// <summary>
/// Gets and sets the property SecurityGroupIds.
/// <para>
/// One or more security group IDs. You can create a security group using <a>CreateSecurityGroup</a>.
/// </para>
///
/// <para>
/// Default: Amazon EC2 uses the default security group.
/// </para>
/// </summary>
public List<string> SecurityGroupIds
{
get { return this._securityGroupIds; }
set { this._securityGroupIds = value; }
}
// Check to see if SecurityGroupIds property is set
internal bool IsSetSecurityGroupIds()
{
return this._securityGroupIds != null && this._securityGroupIds.Count > 0;
}
/// <summary>
/// Gets and sets the property SecurityGroups.
/// <para>
/// [EC2-Classic, default VPC] One or more security group names. For a nondefault VPC,
/// you must use security group IDs instead.
/// </para>
///
/// <para>
/// Default: Amazon EC2 uses the default security group.
/// </para>
/// </summary>
public List<string> SecurityGroups
{
get { return this._securityGroups; }
set { this._securityGroups = value; }
}
// Check to see if SecurityGroups property is set
internal bool IsSetSecurityGroups()
{
return this._securityGroups != null && this._securityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property SubnetId.
/// <para>
/// [EC2-VPC] The ID of the subnet to launch the instance into.
/// </para>
/// </summary>
public string SubnetId
{
get { return this._subnetId; }
set { this._subnetId = value; }
}
// Check to see if SubnetId property is set
internal bool IsSetSubnetId()
{
return this._subnetId != null;
}
/// <summary>
/// Gets and sets the property UserData.
/// <para>
/// The Base64-encoded MIME user data for the instances.
/// </para>
/// </summary>
public string UserData
{
get { return this._userData; }
set { this._userData = value; }
}
// Check to see if UserData property is set
internal bool IsSetUserData()
{
return this._userData != null;
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/type/phone_number.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Type {
/// <summary>Holder for reflection information generated from google/type/phone_number.proto</summary>
public static partial class PhoneNumberReflection {
#region Descriptor
/// <summary>File descriptor for google/type/phone_number.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PhoneNumberReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch5nb29nbGUvdHlwZS9waG9uZV9udW1iZXIucHJvdG8SC2dvb2dsZS50eXBl",
"IqsBCgtQaG9uZU51bWJlchIVCgtlMTY0X251bWJlchgBIAEoCUgAEjgKCnNo",
"b3J0X2NvZGUYAiABKAsyIi5nb29nbGUudHlwZS5QaG9uZU51bWJlci5TaG9y",
"dENvZGVIABIRCglleHRlbnNpb24YAyABKAkaMAoJU2hvcnRDb2RlEhMKC3Jl",
"Z2lvbl9jb2RlGAEgASgJEg4KBm51bWJlchgCIAEoCUIGCgRraW5kQnQKD2Nv",
"bS5nb29nbGUudHlwZUIQUGhvbmVOdW1iZXJQcm90b1ABWkRnb29nbGUuZ29s",
"YW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL3R5cGUvcGhvbmVfbnVtYmVy",
"O3Bob25lX251bWJlcvgBAaICA0dUUGIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.PhoneNumber), global::Google.Type.PhoneNumber.Parser, new[]{ "E164Number", "ShortCode", "Extension" }, new[]{ "Kind" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.PhoneNumber.Types.ShortCode), global::Google.Type.PhoneNumber.Types.ShortCode.Parser, new[]{ "RegionCode", "Number" }, null, null, null, null)})
}));
}
#endregion
}
#region Messages
/// <summary>
/// An object representing a phone number, suitable as an API wire format.
///
/// This representation:
///
/// - should not be used for locale-specific formatting of a phone number, such
/// as "+1 (650) 253-0000 ext. 123"
///
/// - is not designed for efficient storage
/// - may not be suitable for dialing - specialized libraries (see references)
/// should be used to parse the number for that purpose
///
/// To do something meaningful with this number, such as format it for various
/// use-cases, convert it to an `i18n.phonenumbers.PhoneNumber` object first.
///
/// For instance, in Java this would be:
///
/// com.google.type.PhoneNumber wireProto =
/// com.google.type.PhoneNumber.newBuilder().build();
/// com.google.i18n.phonenumbers.Phonenumber.PhoneNumber phoneNumber =
/// PhoneNumberUtil.getInstance().parse(wireProto.getE164Number(), "ZZ");
/// if (!wireProto.getExtension().isEmpty()) {
/// phoneNumber.setExtension(wireProto.getExtension());
/// }
///
/// Reference(s):
/// - https://github.com/google/libphonenumber
/// </summary>
public sealed partial class PhoneNumber : pb::IMessage<PhoneNumber>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<PhoneNumber> _parser = new pb::MessageParser<PhoneNumber>(() => new PhoneNumber());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<PhoneNumber> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.PhoneNumberReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public PhoneNumber() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public PhoneNumber(PhoneNumber other) : this() {
extension_ = other.extension_;
switch (other.KindCase) {
case KindOneofCase.E164Number:
E164Number = other.E164Number;
break;
case KindOneofCase.ShortCode:
ShortCode = other.ShortCode.Clone();
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public PhoneNumber Clone() {
return new PhoneNumber(this);
}
/// <summary>Field number for the "e164_number" field.</summary>
public const int E164NumberFieldNumber = 1;
/// <summary>
/// The phone number, represented as a leading plus sign ('+'), followed by a
/// phone number that uses a relaxed ITU E.164 format consisting of the
/// country calling code (1 to 3 digits) and the subscriber number, with no
/// additional spaces or formatting, e.g.:
/// - correct: "+15552220123"
/// - incorrect: "+1 (555) 222-01234 x123".
///
/// The ITU E.164 format limits the latter to 12 digits, but in practice not
/// all countries respect that, so we relax that restriction here.
/// National-only numbers are not allowed.
///
/// References:
/// - https://www.itu.int/rec/T-REC-E.164-201011-I
/// - https://en.wikipedia.org/wiki/E.164.
/// - https://en.wikipedia.org/wiki/List_of_country_calling_codes
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string E164Number {
get { return kindCase_ == KindOneofCase.E164Number ? (string) kind_ : ""; }
set {
kind_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
kindCase_ = KindOneofCase.E164Number;
}
}
/// <summary>Field number for the "short_code" field.</summary>
public const int ShortCodeFieldNumber = 2;
/// <summary>
/// A short code.
///
/// Reference(s):
/// - https://en.wikipedia.org/wiki/Short_code
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Type.PhoneNumber.Types.ShortCode ShortCode {
get { return kindCase_ == KindOneofCase.ShortCode ? (global::Google.Type.PhoneNumber.Types.ShortCode) kind_ : null; }
set {
kind_ = value;
kindCase_ = value == null ? KindOneofCase.None : KindOneofCase.ShortCode;
}
}
/// <summary>Field number for the "extension" field.</summary>
public const int ExtensionFieldNumber = 3;
private string extension_ = "";
/// <summary>
/// The phone number's extension. The extension is not standardized in ITU
/// recommendations, except for being defined as a series of numbers with a
/// maximum length of 40 digits. Other than digits, some other dialing
/// characters such as ',' (indicating a wait) or '#' may be stored here.
///
/// Note that no regions currently use extensions with short codes, so this
/// field is normally only set in conjunction with an E.164 number. It is held
/// separately from the E.164 number to allow for short code extensions in the
/// future.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Extension {
get { return extension_; }
set {
extension_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
private object kind_;
/// <summary>Enum of possible cases for the "kind" oneof.</summary>
public enum KindOneofCase {
None = 0,
E164Number = 1,
ShortCode = 2,
}
private KindOneofCase kindCase_ = KindOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public KindOneofCase KindCase {
get { return kindCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void ClearKind() {
kindCase_ = KindOneofCase.None;
kind_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as PhoneNumber);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(PhoneNumber other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (E164Number != other.E164Number) return false;
if (!object.Equals(ShortCode, other.ShortCode)) return false;
if (Extension != other.Extension) return false;
if (KindCase != other.KindCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (kindCase_ == KindOneofCase.E164Number) hash ^= E164Number.GetHashCode();
if (kindCase_ == KindOneofCase.ShortCode) hash ^= ShortCode.GetHashCode();
if (Extension.Length != 0) hash ^= Extension.GetHashCode();
hash ^= (int) kindCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (kindCase_ == KindOneofCase.E164Number) {
output.WriteRawTag(10);
output.WriteString(E164Number);
}
if (kindCase_ == KindOneofCase.ShortCode) {
output.WriteRawTag(18);
output.WriteMessage(ShortCode);
}
if (Extension.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Extension);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (kindCase_ == KindOneofCase.E164Number) {
output.WriteRawTag(10);
output.WriteString(E164Number);
}
if (kindCase_ == KindOneofCase.ShortCode) {
output.WriteRawTag(18);
output.WriteMessage(ShortCode);
}
if (Extension.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Extension);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (kindCase_ == KindOneofCase.E164Number) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(E164Number);
}
if (kindCase_ == KindOneofCase.ShortCode) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ShortCode);
}
if (Extension.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Extension);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(PhoneNumber other) {
if (other == null) {
return;
}
if (other.Extension.Length != 0) {
Extension = other.Extension;
}
switch (other.KindCase) {
case KindOneofCase.E164Number:
E164Number = other.E164Number;
break;
case KindOneofCase.ShortCode:
if (ShortCode == null) {
ShortCode = new global::Google.Type.PhoneNumber.Types.ShortCode();
}
ShortCode.MergeFrom(other.ShortCode);
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
E164Number = input.ReadString();
break;
}
case 18: {
global::Google.Type.PhoneNumber.Types.ShortCode subBuilder = new global::Google.Type.PhoneNumber.Types.ShortCode();
if (kindCase_ == KindOneofCase.ShortCode) {
subBuilder.MergeFrom(ShortCode);
}
input.ReadMessage(subBuilder);
ShortCode = subBuilder;
break;
}
case 26: {
Extension = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
E164Number = input.ReadString();
break;
}
case 18: {
global::Google.Type.PhoneNumber.Types.ShortCode subBuilder = new global::Google.Type.PhoneNumber.Types.ShortCode();
if (kindCase_ == KindOneofCase.ShortCode) {
subBuilder.MergeFrom(ShortCode);
}
input.ReadMessage(subBuilder);
ShortCode = subBuilder;
break;
}
case 26: {
Extension = input.ReadString();
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the PhoneNumber message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// An object representing a short code, which is a phone number that is
/// typically much shorter than regular phone numbers and can be used to
/// address messages in MMS and SMS systems, as well as for abbreviated dialing
/// (e.g. "Text 611 to see how many minutes you have remaining on your plan.").
///
/// Short codes are restricted to a region and are not internationally
/// dialable, which means the same short code can exist in different regions,
/// with different usage and pricing, even if those regions share the same
/// country calling code (e.g. US and CA).
/// </summary>
public sealed partial class ShortCode : pb::IMessage<ShortCode>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ShortCode> _parser = new pb::MessageParser<ShortCode>(() => new ShortCode());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<ShortCode> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.PhoneNumber.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ShortCode() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ShortCode(ShortCode other) : this() {
regionCode_ = other.regionCode_;
number_ = other.number_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public ShortCode Clone() {
return new ShortCode(this);
}
/// <summary>Field number for the "region_code" field.</summary>
public const int RegionCodeFieldNumber = 1;
private string regionCode_ = "";
/// <summary>
/// Required. The BCP-47 region code of the location where calls to this
/// short code can be made, such as "US" and "BB".
///
/// Reference(s):
/// - http://www.unicode.org/reports/tr35/#unicode_region_subtag
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string RegionCode {
get { return regionCode_; }
set {
regionCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "number" field.</summary>
public const int NumberFieldNumber = 2;
private string number_ = "";
/// <summary>
/// Required. The short code digits, without a leading plus ('+') or country
/// calling code, e.g. "611".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Number {
get { return number_; }
set {
number_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as ShortCode);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(ShortCode other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (RegionCode != other.RegionCode) return false;
if (Number != other.Number) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (RegionCode.Length != 0) hash ^= RegionCode.GetHashCode();
if (Number.Length != 0) hash ^= Number.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (RegionCode.Length != 0) {
output.WriteRawTag(10);
output.WriteString(RegionCode);
}
if (Number.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Number);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (RegionCode.Length != 0) {
output.WriteRawTag(10);
output.WriteString(RegionCode);
}
if (Number.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Number);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (RegionCode.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(RegionCode);
}
if (Number.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Number);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(ShortCode other) {
if (other == null) {
return;
}
if (other.RegionCode.Length != 0) {
RegionCode = other.RegionCode;
}
if (other.Number.Length != 0) {
Number = other.Number;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
RegionCode = input.ReadString();
break;
}
case 18: {
Number = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
RegionCode = input.ReadString();
break;
}
case 18: {
Number = input.ReadString();
break;
}
}
}
}
#endif
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace HardwhereApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System
{
public static class Console
{
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
private static readonly object InternalSyncObject = new object(); // for synchronizing changing of Console's static fields
private static TextReader s_in;
private static TextWriter s_out, s_error;
private static Encoding s_inputEncoding;
private static Encoding s_outputEncoding;
private static bool s_isOutTextWriterRedirected = false;
private static bool s_isErrorTextWriterRedirected = false;
private static ConsoleCancelEventHandler _cancelCallbacks;
private static ConsolePal.ControlCHandlerRegistrar _registrar;
internal static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class
{
lock (InternalSyncObject)
{
T result = Volatile.Read(ref field);
if (result == null)
{
result = initializer();
Volatile.Write(ref field, result);
}
return result;
}
}
public static TextReader In
{
get
{
return Volatile.Read(ref s_in) ?? EnsureInitialized(ref s_in, () => ConsolePal.GetOrCreateReader());
}
}
public static Encoding InputEncoding
{
get
{
return Volatile.Read(ref s_inputEncoding) ?? EnsureInitialized(ref s_inputEncoding, () => ConsolePal.InputEncoding);
}
set
{
CheckNonNull(value, "value");
lock (InternalSyncObject)
{
// Set the terminal console encoding.
ConsolePal.SetConsoleInputEncoding(value);
Volatile.Write(ref s_inputEncoding, (Encoding)value.Clone());
// We need to reinitialize Console.In in the next call to s_in
// This will discard the current StreamReader, potentially
// losing buffered data.
Volatile.Write(ref s_in, null);
}
}
}
public static Encoding OutputEncoding
{
get
{
return Volatile.Read(ref s_outputEncoding) ?? EnsureInitialized(ref s_outputEncoding, () => ConsolePal.OutputEncoding);
}
set
{
CheckNonNull(value, "value");
lock (InternalSyncObject)
{
// Set the terminal console encoding.
ConsolePal.SetConsoleOutputEncoding(value);
// Before changing the code page we need to flush the data
// if Out hasn't been redirected. Also, have the next call to
// s_out reinitialize the console code page.
if (Volatile.Read(ref s_out) != null && !s_isOutTextWriterRedirected)
{
s_out.Flush();
Volatile.Write(ref s_out, null);
}
if (Volatile.Read(ref s_error) != null && !s_isErrorTextWriterRedirected)
{
s_error.Flush();
Volatile.Write(ref s_error, null);
}
Volatile.Write(ref s_outputEncoding, (Encoding)value.Clone());
}
}
}
public static bool KeyAvailable
{
get
{
if (IsInputRedirected)
{
throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile);
}
return ConsolePal.KeyAvailable;
}
}
public static ConsoleKeyInfo ReadKey()
{
return ConsolePal.ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept)
{
return ConsolePal.ReadKey(intercept);
}
public static TextWriter Out
{
get { return Volatile.Read(ref s_out) ?? EnsureInitialized(ref s_out, () => CreateOutputWriter(OpenStandardOutput())); }
}
public static TextWriter Error
{
get { return Volatile.Read(ref s_error) ?? EnsureInitialized(ref s_error, () => CreateOutputWriter(OpenStandardError())); }
}
private static TextWriter CreateOutputWriter(Stream outputStream)
{
return SyncTextWriter.GetSynchronizedTextWriter(outputStream == Stream.Null ?
StreamWriter.Null :
new StreamWriter(
stream: outputStream,
encoding: new ConsoleEncoding(OutputEncoding), // This ensures no prefix is written to the stream.
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true) { AutoFlush = true });
}
private static StrongBox<bool> _isStdInRedirected;
private static StrongBox<bool> _isStdOutRedirected;
private static StrongBox<bool> _isStdErrRedirected;
public static bool IsInputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdInRedirected) ??
EnsureInitialized(ref _isStdInRedirected, () => new StrongBox<bool>(ConsolePal.IsInputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsOutputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdOutRedirected) ??
EnsureInitialized(ref _isStdOutRedirected, () => new StrongBox<bool>(ConsolePal.IsOutputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsErrorRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdErrRedirected) ??
EnsureInitialized(ref _isStdErrRedirected, () => new StrongBox<bool>(ConsolePal.IsErrorRedirectedCore()));
return redirected.Value;
}
}
public static int CursorSize
{
get { return ConsolePal.CursorSize; }
set { ConsolePal.CursorSize = value; }
}
public static bool NumberLock { get { return ConsolePal.NumberLock; } }
public static bool CapsLock { get { return ConsolePal.CapsLock; } }
internal const ConsoleColor UnknownColor = (ConsoleColor)(-1);
public static ConsoleColor BackgroundColor
{
get { return ConsolePal.BackgroundColor; }
set { ConsolePal.BackgroundColor = value; }
}
public static ConsoleColor ForegroundColor
{
get { return ConsolePal.ForegroundColor; }
set { ConsolePal.ForegroundColor = value; }
}
public static void ResetColor()
{
ConsolePal.ResetColor();
}
public static int BufferWidth
{
get { return ConsolePal.BufferWidth; }
set { ConsolePal.BufferWidth = value; }
}
public static int BufferHeight
{
get { return ConsolePal.BufferHeight; }
set { ConsolePal.BufferHeight = value; }
}
public static void SetBufferSize(int width, int height)
{
ConsolePal.SetBufferSize(width, height);
}
public static int WindowLeft
{
get { return ConsolePal.WindowLeft; }
set { ConsolePal.WindowLeft = value; }
}
public static int WindowTop
{
get { return ConsolePal.WindowTop; }
set { ConsolePal.WindowTop = value; }
}
public static int WindowWidth
{
get
{
return ConsolePal.WindowWidth;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedPosNum);
}
ConsolePal.WindowWidth = value;
}
}
public static int WindowHeight
{
get
{
return ConsolePal.WindowHeight;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedPosNum);
}
ConsolePal.WindowHeight = value;
}
}
public static void SetWindowPosition(int left, int top)
{
ConsolePal.SetWindowPosition(left, top);
}
public static void SetWindowSize(int width, int height)
{
ConsolePal.SetWindowSize(width, height);
}
public static int LargestWindowWidth
{
get { return ConsolePal.LargestWindowWidth; }
}
public static int LargestWindowHeight
{
get { return ConsolePal.LargestWindowHeight; }
}
public static bool CursorVisible
{
get { return ConsolePal.CursorVisible; }
set { ConsolePal.CursorVisible = value; }
}
public static int CursorLeft
{
get { return ConsolePal.CursorLeft; }
set { SetCursorPosition(value, CursorTop); }
}
public static int CursorTop
{
get { return ConsolePal.CursorTop; }
set { SetCursorPosition(CursorLeft, value); }
}
private const int MaxConsoleTitleLength = 24500; // same value as in .NET Framework
public static string Title
{
get { return ConsolePal.Title; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Length > MaxConsoleTitleLength)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_ConsoleTitleTooLong);
}
ConsolePal.Title = value;
}
}
public static void Beep()
{
ConsolePal.Beep();
}
public static void Beep(int frequency, int duration)
{
ConsolePal.Beep(frequency, duration);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop)
{
ConsolePal.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, ' ', ConsoleColor.Black, BackgroundColor);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
{
ConsolePal.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, sourceChar, sourceForeColor, sourceBackColor);
}
public static void Clear()
{
ConsolePal.Clear();
}
public static void SetCursorPosition(int left, int top)
{
// Basic argument validation. The PAL implementation may provide further validation.
if (left < 0 || left >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (top < 0 || top >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
ConsolePal.SetCursorPosition(left, top);
}
public static event ConsoleCancelEventHandler CancelKeyPress
{
add
{
lock (InternalSyncObject)
{
_cancelCallbacks += value;
// If we haven't registered our control-C handler, do it.
if (_registrar == null)
{
_registrar = new ConsolePal.ControlCHandlerRegistrar();
_registrar.Register();
}
}
}
remove
{
lock (InternalSyncObject)
{
_cancelCallbacks -= value;
if (_registrar != null && _cancelCallbacks == null)
{
_registrar.Unregister();
_registrar = null;
}
}
}
}
public static bool TreatControlCAsInput
{
get { return ConsolePal.TreatControlCAsInput; }
set { ConsolePal.TreatControlCAsInput = value; }
}
public static Stream OpenStandardInput()
{
return ConsolePal.OpenStandardInput();
}
public static Stream OpenStandardOutput()
{
return ConsolePal.OpenStandardOutput();
}
public static Stream OpenStandardError()
{
return ConsolePal.OpenStandardError();
}
public static void SetIn(TextReader newIn)
{
CheckNonNull(newIn, "newIn");
newIn = SyncTextReader.GetSynchronizedTextReader(newIn);
lock (InternalSyncObject)
{
Volatile.Write(ref s_in, newIn);
}
}
public static void SetOut(TextWriter newOut)
{
CheckNonNull(newOut, "newOut");
newOut = SyncTextWriter.GetSynchronizedTextWriter(newOut);
Volatile.Write(ref s_isOutTextWriterRedirected, true);
lock (InternalSyncObject)
{
Volatile.Write(ref s_out, newOut);
}
}
public static void SetError(TextWriter newError)
{
CheckNonNull(newError, "newError");
newError = SyncTextWriter.GetSynchronizedTextWriter(newError);
Volatile.Write(ref s_isErrorTextWriterRedirected, true);
lock (InternalSyncObject)
{
Volatile.Write(ref s_error, newError);
}
}
private static void CheckNonNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException(paramName);
}
//
// Give a hint to the code generator to not inline the common console methods. The console methods are
// not performance critical. It is unnecessary code bloat to have them inlined.
//
// Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out
// the inlined console writelines from them.
//
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int Read()
{
return In.Read();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static String ReadLine()
{
return In.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine()
{
Out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer)
{
Out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer, int index, int count)
{
Out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(decimal value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(Object value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0)
{
Out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1)
{
Out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg);
else
Out.WriteLine(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0)
{
Out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1)
{
Out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1, Object arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg);
else
Out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(bool value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer)
{
Out.Write(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer, int index, int count)
{
Out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(double value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(decimal value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(float value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(int value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(uint value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(long value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(ulong value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(Object value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String value)
{
Out.Write(value);
}
private sealed class ControlCDelegateData
{
private readonly ConsoleSpecialKey _controlKey;
private readonly ConsoleCancelEventHandler _cancelCallbacks;
internal bool Cancel;
internal bool DelegateStarted;
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks)
{
_controlKey = controlKey;
_cancelCallbacks = cancelCallbacks;
}
// This is the worker delegate that is called on the Threadpool thread to fire the actual events. It sets the DelegateStarted flag so
// the thread that queued the work to the threadpool knows it has started (since it does not want to block indefinitely on the task
// to start).
internal void HandleBreakEvent()
{
DelegateStarted = true;
var args = new ConsoleCancelEventArgs(_controlKey);
_cancelCallbacks(null, args);
Cancel = args.Cancel;
}
}
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey)
{
// The thread that this gets called back on has a very small stack on some systems. There is
// not enough space to handle a managed exception being caught and thrown. So, run a task
// on the threadpool for the actual event callback.
// To avoid the race condition between remove handler and raising the event
ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks;
if (cancelCallbacks == null)
{
return false;
}
var delegateData = new ControlCDelegateData(controlKey, cancelCallbacks);
Task callBackTask = Task.Factory.StartNew(
d => ((ControlCDelegateData)d).HandleBreakEvent(),
delegateData,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Block until the delegate is done. We need to be robust in the face of the task not executing
// but we also want to get control back immediately after it is done and we don't want to give the
// handler a fixed time limit in case it needs to display UI. Wait on the task twice, once with a
// timeout and a second time without if we are sure that the handler actually started.
TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds
callBackTask.Wait(controlCWaitTime);
if (!delegateData.DelegateStarted)
{
Debug.Assert(false, "The task to execute the handler did not start within 30 seconds.");
return false;
}
callBackTask.Wait();
return delegateData.Cancel;
}
}
}
| |
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 agile9.outlook.context.db.Areas.HelpPage.Models;
namespace agile9.outlook.context.db.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
namespace Microsoft.Msagl.Layout.Layered {
/// <summary>
/// Defines the anchors for a node; anchors can be not symmetrical in general
///
/// |TopAnchor
///Left anchor|
/// ======Origin==================RightAnchor
/// |
/// |
/// |BottomAnchor
/// </summary>
#if TEST_MSAGL
public
#else
internal
#endif
class Anchor {
/// <summary>
/// ToString
/// </summary>
/// <returns></returns>
public override string ToString() {
return "la:ra " +
la.ToString("#.##", CultureInfo.InvariantCulture) + " " + ra.ToString("#.##", CultureInfo.InvariantCulture) + " ta:ba " + ta.ToString("#.##", CultureInfo.InvariantCulture) + " " + ba.ToString("#.##", CultureInfo.InvariantCulture) + " x:y " + x.ToString("#.##", CultureInfo.InvariantCulture) + " " + y.ToString("#.##", CultureInfo.InvariantCulture);
}
double la;
double ra;
double ta;
double ba;
double labelCornersPreserveCoefficient;
/// <summary>
/// distance for the center of the node to its left boundary
/// </summary>
public double LeftAnchor {
get {
return la;
}
set {
//the absence of this check allows a situation when an edge crosses its label or
// a label which does not belong to the edge
// if(value<-Curve.DistEps)
// throw new Exception("assigning negative value to a anchor");
la = Math.Max(value, 0); ;
}
}
/// <summary>
/// distance from the center of the node to its right boundary
/// </summary>
public double RightAnchor {
get {
return ra;
}
set {
// if(value<-Curve.DistEps)
// throw new Exception("assigning negative value to a anchor: "+value );
ra = Math.Max(value, 0);
}
}
/// <summary>
/// distance from the center of the node to its top boundary
/// </summary>
public double TopAnchor {
get {
return ta;
}
set {
//if(value<-Curve.DistEps)
//throw new Exception("assigning negative value to a anchor");
ta = Math.Max(value, 0);
}
}
/// <summary>
/// distance from the center of the node to it bottom boundary
/// </summary>
public double BottomAnchor {
get {
return ba;
}
set {
//if(value<-Curve.DistEps)
//throw new InvalidOperationException();//"assigning negative value to a anchor");
ba = Math.Max(value, 0);
}
}
/// <summary>
/// Left boundary of the node
/// </summary>
public double Left {
get { return x - la; }
}
/// <summary>
/// right boundary of the node
/// </summary>
public double Right {
get { return x + ra; }
}
/// <summary>
/// top boundary of the node
/// </summary>
public double Top {
get { return y + ta; }
set {
y += value - Top;
}
}
/// <summary>
/// bottom of the node
/// </summary>
public double Bottom {
get { return y - ba; }
set { y += value - Bottom; }
}
/// <summary>
/// Left top corner
/// </summary>
public Point LeftTop {
get { return new Point(Left, Top); }
}
/// <summary>
/// Left bottom of the node
/// </summary>
public Point LeftBottom {
get { return new Point(Left, Bottom); }
}
/// <summary>
/// Right bottom of the node
/// </summary>
public Point RightBottom {
get { return new Point(Right, Bottom); }
}
Node node;
internal Node Node {
get { return node; }
set {
node = value;
this.polygonalBoundary = null;
}
}
/// <summary>
/// Right top of the node
/// </summary>
public Point RightTop {
get { return new Point(Right, Top); }
}
/// <summary>
/// an empty constructor
/// </summary>
public Anchor(double labelCornersPreserveCoefficient) {
this.labelCornersPreserveCoefficient = labelCornersPreserveCoefficient;
}
/// <summary>
/// constructor
/// </summary>
public Anchor(double leftAnchor, double rightAnchor,
double topAnchor, double bottomAnchor, Node node, double labelCornersPreserveCoefficient) {
la = leftAnchor;
ra = rightAnchor;
ta = topAnchor;
ba = bottomAnchor;
Node = node;
this.labelCornersPreserveCoefficient = labelCornersPreserveCoefficient;
}
double x;
/// <summary>
/// the x position
/// </summary>
internal double X {
get {
return x;
}
set {
polygonalBoundary = null;
x = value;
}
}
double y;
/// <summary>
/// the y position
/// </summary>
internal double Y {
get {
return y;
}
set {
polygonalBoundary = null;
y = value;
}
}
/// <summary>
/// Center of the node
/// </summary>
public Point Origin {
get {
return new Point(x, y);
}
}
bool alreadySitsOnASpline;
/// <summary>
/// signals if the spline has been routed already through the node
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811")]
public bool AlreadySitsOnASpline {
get { return alreadySitsOnASpline; }
set { alreadySitsOnASpline = value; }
}
/// <summary>
/// node widths
/// </summary>
public double Width {
get { return this.la + this.ra; }
}
/// <summary>
/// node height
/// </summary>
public double Height {
get { return this.ta + this.ba; }
}
/// <summary>
/// set to true if the anchor has been introduced for a label
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811")]
public bool RepresentsLabel {
get { return LabelToTheRightOfAnchorCenter || LabelToTheLeftOfAnchorCenter; }
}
bool labelIsToTheLeftOfTheSpline;
/// <summary>
/// An anchor for an edge label with the label to the right of the spline has its height equal to the one of the label
/// Its leftAnchor is a reserved space for the spline and the rightAnchor is equal to the label width.
/// </summary>
internal bool LabelToTheLeftOfAnchorCenter {
get { return labelIsToTheLeftOfTheSpline; }
set { labelIsToTheLeftOfTheSpline = value; }
}
bool labelIsToTheRightOfTheSpline;
/// <summary>
/// An anchor for an edge label with the label to the left of the spline has its height equal to the one of the label
/// Its rightAnchor is a reserved space for the spline and the leftAnchor is equal to the label width.
/// </summary>
internal bool LabelToTheRightOfAnchorCenter {
get { return labelIsToTheRightOfTheSpline; }
set { labelIsToTheRightOfTheSpline = value; }
}
internal bool HasLabel {
get { return LabelToTheRightOfAnchorCenter || LabelToTheLeftOfAnchorCenter; }
}
internal double LabelWidth {
get {
if (LabelToTheLeftOfAnchorCenter)
return LeftAnchor;
if (LabelToTheRightOfAnchorCenter)
return RightAnchor;
throw new InvalidOperationException();
}
}
Polyline polygonalBoundary;
/// <summary>
/// the polygon representing the boundary of a node
/// </summary>
#if TEST_MSAGL
public
#else
internal
#endif
Polyline PolygonalBoundary {
get {
if (polygonalBoundary != null)
return polygonalBoundary;
return polygonalBoundary = Pad(CreatPolygonalBoundaryWithoutPadding(),Padding);
}
}
static Polyline Pad(Polyline curve, double padding) {
if (padding == 0)
return curve;
if (CurveIsConvex(curve)) {
return PadConvexCurve(curve, padding);
} else
return PadConvexCurve(Curve.StandardRectBoundary(curve), padding);
}
static void PadCorner(Polyline poly, PolylinePoint p0, PolylinePoint p1, PolylinePoint p2, double padding) {
Point a, b;
int numberOfPoints=GetPaddedCorner(p0, p1, p2, out a, out b, padding);
poly.AddPoint(a);
if (numberOfPoints==2)
poly.AddPoint(b);
}
static Polyline PadConvexCurve(Polyline poly, double padding) {
Polyline ret = new Polyline();
PadCorner(ret, poly.EndPoint.Prev, poly.EndPoint, poly.StartPoint, padding);
PadCorner(ret, poly.EndPoint, poly.StartPoint, poly.StartPoint.Next, padding);
for (PolylinePoint pp = poly.StartPoint; pp.Next.Next != null; pp = pp.Next)
PadCorner(ret, pp, pp.Next, pp.Next.Next, padding);
ret.Closed = true;
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <param name="third"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="padding"></param>
/// <returns>number of new points</returns>
static int GetPaddedCorner(PolylinePoint first, PolylinePoint second, PolylinePoint third, out Point a, out Point b,
double padding) {
Point u = first.Point;
Point v = second.Point;
Point w = third.Point;
// System.Diagnostics.Debug.Assert(Point.GetTriangleOrientation(u, v, w) == TriangleOrientation.Clockwise);
Point uvPerp = (v - u).Rotate(Math.PI / 2).Normalize();
////uvPerp has to look outside of the curve
//if (uvPerp * (v - Origin) < 0)
// uvPerp *= -1;
Point l = (v - u).Normalize() + (v - w).Normalize();
if (l.Length < ApproximateComparer.IntersectionEpsilon) {
a = b = v + padding * uvPerp;
return 1;
}
Point d = l.Normalize() * padding;
Point dp = d.Rotate(Math.PI / 2);
//look for a in the form d+x*dp
//we have: Padding=(d+x*dp)*uvPerp
double xp = (padding - d * uvPerp) / (dp * uvPerp);
a = d + xp * dp + v;
b = d - xp * dp + v;
return 2; //number of points to add
}
static bool CurveIsConvex(Polyline poly) {
TriangleOrientation orientation = Point.GetTriangleOrientation(poly.EndPoint.Point, poly.StartPoint.Point, poly.StartPoint.Next.Point);
if (Point.GetTriangleOrientation(poly.EndPoint.Prev.Point, poly.EndPoint.Point, poly.StartPoint.Point) != orientation)
return false;
PolylinePoint pp = poly.StartPoint;
while (pp.Next.Next != null) {
if (Point.GetTriangleOrientation(pp.Point, pp.Next.Point, pp.Next.Next.Point) != orientation)
return false;
pp = pp.Next;
}
return true;
}
//private static double TurnAfterSeg(Curve curve, int i) {
// return Point.SignedDoubledTriangleArea(curve.Segments[i].Start, curve.Segments[i].End, curve.Segments[(i + 1) / curve.Segments.Count].End);
//}
private Polyline CreatPolygonalBoundaryWithoutPadding() {
Polyline ret;
if (this.HasLabel)
ret = LabelToTheLeftOfAnchorCenter ? PolygonOnLeftLabel() : PolygonOnRightLabel();
else if (this.NodeBoundary == null)
ret = StandardRectBoundary();
else
ret = Curve.PolylineAroundClosedCurve(this.NodeBoundary);
return ret;
}
private Polyline StandardRectBoundary() {
Polyline poly = new Polyline();
poly.AddPoint(LeftTop);
poly.AddPoint(RightTop);
poly.AddPoint(RightBottom);
poly.AddPoint(LeftBottom);
poly.Closed = true;
return poly;
}
private Polyline PolygonOnLeftLabel() {
Polyline poly = new Polyline();
double t = Left + (1 - this.labelCornersPreserveCoefficient) * LabelWidth;
poly.AddPoint(new Point(t, Top));
poly.AddPoint(RightTop);
poly.AddPoint(RightBottom);
poly.AddPoint(new Point(t, Bottom));
poly.AddPoint(new Point(Left, Y));
poly.Closed = true;
return poly;
}
private Polyline PolygonOnRightLabel() {
Polyline poly = new Polyline();
double t = Right - (1 - this.labelCornersPreserveCoefficient) * LabelWidth;
poly.AddPoint(t, Top);
poly.AddPoint(Right, Y);
poly.AddPoint(t, Bottom);
poly.AddPoint(Left, Bottom);
poly.AddPoint(Left, Top);
poly.Closed = true;
return poly;
}
internal ICurve NodeBoundary {
get { return Node!=null?Node.BoundaryCurve:null; }
}
double padding;
/// <summary>
/// node padding
/// </summary>
public double Padding {
get { return padding; }
set { padding = value; }
}
internal void Move(Point p){
this.X += p.X;
this.Y += p.Y;
}
#if TEST_MSAGL
/// <summary>
/// UserData
/// </summary>
public object UserData { get; set; }
#endif
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// NationalResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry
{
public class NationalResource : Resource
{
private static Request BuildReadRequest(ReadNationalOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/AvailablePhoneNumbers/" + options.PathCountryCode + "/National.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read National parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of National </returns>
public static ResourceSet<NationalResource> Read(ReadNationalOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<NationalResource>.FromJson("available_phone_numbers", response.Content);
return new ResourceSet<NationalResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read National parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of National </returns>
public static async System.Threading.Tasks.Task<ResourceSet<NationalResource>> ReadAsync(ReadNationalOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<NationalResource>.FromJson("available_phone_numbers", response.Content);
return new ResourceSet<NationalResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param>
/// <param name="pathAccountSid"> The SID of the Account requesting the AvailablePhoneNumber resources </param>
/// <param name="areaCode"> The area code of the phone numbers to read </param>
/// <param name="contains"> The pattern on which to match phone numbers </param>
/// <param name="smsEnabled"> Whether the phone numbers can receive text messages </param>
/// <param name="mmsEnabled"> Whether the phone numbers can receive MMS messages </param>
/// <param name="voiceEnabled"> Whether the phone numbers can receive calls. </param>
/// <param name="excludeAllAddressRequired"> Whether to exclude phone numbers that require an Address </param>
/// <param name="excludeLocalAddressRequired"> Whether to exclude phone numbers that require a local address </param>
/// <param name="excludeForeignAddressRequired"> Whether to exclude phone numbers that require a foreign address
/// </param>
/// <param name="beta"> Whether to read phone numbers new to the Twilio platform </param>
/// <param name="nearNumber"> Given a phone number, find a geographically close number within distance miles.
/// (US/Canada only) </param>
/// <param name="nearLatLong"> Given a latitude/longitude pair lat,long find geographically close numbers within
/// distance miles. (US/Canada only) </param>
/// <param name="distance"> The search radius, in miles, for a near_ query. (US/Canada only) </param>
/// <param name="inPostalCode"> Limit results to a particular postal code. (US/Canada only) </param>
/// <param name="inRegion"> Limit results to a particular region. (US/Canada only) </param>
/// <param name="inRateCenter"> Limit results to a specific rate center, or given a phone number search within the same
/// rate center as that number. (US/Canada only) </param>
/// <param name="inLata"> Limit results to a specific local access and transport area. (US/Canada only) </param>
/// <param name="inLocality"> Limit results to a particular locality </param>
/// <param name="faxEnabled"> Whether the phone numbers can receive faxes </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of National </returns>
public static ResourceSet<NationalResource> Read(string pathCountryCode,
string pathAccountSid = null,
int? areaCode = null,
string contains = null,
bool? smsEnabled = null,
bool? mmsEnabled = null,
bool? voiceEnabled = null,
bool? excludeAllAddressRequired = null,
bool? excludeLocalAddressRequired = null,
bool? excludeForeignAddressRequired = null,
bool? beta = null,
Types.PhoneNumber nearNumber = null,
string nearLatLong = null,
int? distance = null,
string inPostalCode = null,
string inRegion = null,
string inRateCenter = null,
string inLata = null,
string inLocality = null,
bool? faxEnabled = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadNationalOptions(pathCountryCode){PathAccountSid = pathAccountSid, AreaCode = areaCode, Contains = contains, SmsEnabled = smsEnabled, MmsEnabled = mmsEnabled, VoiceEnabled = voiceEnabled, ExcludeAllAddressRequired = excludeAllAddressRequired, ExcludeLocalAddressRequired = excludeLocalAddressRequired, ExcludeForeignAddressRequired = excludeForeignAddressRequired, Beta = beta, NearNumber = nearNumber, NearLatLong = nearLatLong, Distance = distance, InPostalCode = inPostalCode, InRegion = inRegion, InRateCenter = inRateCenter, InLata = inLata, InLocality = inLocality, FaxEnabled = faxEnabled, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param>
/// <param name="pathAccountSid"> The SID of the Account requesting the AvailablePhoneNumber resources </param>
/// <param name="areaCode"> The area code of the phone numbers to read </param>
/// <param name="contains"> The pattern on which to match phone numbers </param>
/// <param name="smsEnabled"> Whether the phone numbers can receive text messages </param>
/// <param name="mmsEnabled"> Whether the phone numbers can receive MMS messages </param>
/// <param name="voiceEnabled"> Whether the phone numbers can receive calls. </param>
/// <param name="excludeAllAddressRequired"> Whether to exclude phone numbers that require an Address </param>
/// <param name="excludeLocalAddressRequired"> Whether to exclude phone numbers that require a local address </param>
/// <param name="excludeForeignAddressRequired"> Whether to exclude phone numbers that require a foreign address
/// </param>
/// <param name="beta"> Whether to read phone numbers new to the Twilio platform </param>
/// <param name="nearNumber"> Given a phone number, find a geographically close number within distance miles.
/// (US/Canada only) </param>
/// <param name="nearLatLong"> Given a latitude/longitude pair lat,long find geographically close numbers within
/// distance miles. (US/Canada only) </param>
/// <param name="distance"> The search radius, in miles, for a near_ query. (US/Canada only) </param>
/// <param name="inPostalCode"> Limit results to a particular postal code. (US/Canada only) </param>
/// <param name="inRegion"> Limit results to a particular region. (US/Canada only) </param>
/// <param name="inRateCenter"> Limit results to a specific rate center, or given a phone number search within the same
/// rate center as that number. (US/Canada only) </param>
/// <param name="inLata"> Limit results to a specific local access and transport area. (US/Canada only) </param>
/// <param name="inLocality"> Limit results to a particular locality </param>
/// <param name="faxEnabled"> Whether the phone numbers can receive faxes </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of National </returns>
public static async System.Threading.Tasks.Task<ResourceSet<NationalResource>> ReadAsync(string pathCountryCode,
string pathAccountSid = null,
int? areaCode = null,
string contains = null,
bool? smsEnabled = null,
bool? mmsEnabled = null,
bool? voiceEnabled = null,
bool? excludeAllAddressRequired = null,
bool? excludeLocalAddressRequired = null,
bool? excludeForeignAddressRequired = null,
bool? beta = null,
Types.PhoneNumber nearNumber = null,
string nearLatLong = null,
int? distance = null,
string inPostalCode = null,
string inRegion = null,
string inRateCenter = null,
string inLata = null,
string inLocality = null,
bool? faxEnabled = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadNationalOptions(pathCountryCode){PathAccountSid = pathAccountSid, AreaCode = areaCode, Contains = contains, SmsEnabled = smsEnabled, MmsEnabled = mmsEnabled, VoiceEnabled = voiceEnabled, ExcludeAllAddressRequired = excludeAllAddressRequired, ExcludeLocalAddressRequired = excludeLocalAddressRequired, ExcludeForeignAddressRequired = excludeForeignAddressRequired, Beta = beta, NearNumber = nearNumber, NearLatLong = nearLatLong, Distance = distance, InPostalCode = inPostalCode, InRegion = inRegion, InRateCenter = inRateCenter, InLata = inLata, InLocality = inLocality, FaxEnabled = faxEnabled, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<NationalResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<NationalResource>.FromJson("available_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<NationalResource> NextPage(Page<NationalResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<NationalResource>.FromJson("available_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<NationalResource> PreviousPage(Page<NationalResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<NationalResource>.FromJson("available_phone_numbers", response.Content);
}
/// <summary>
/// Converts a JSON string into a NationalResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> NationalResource object represented by the provided JSON </returns>
public static NationalResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<NationalResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// A formatted version of the phone number
/// </summary>
[JsonProperty("friendly_name")]
[JsonConverter(typeof(PhoneNumberConverter))]
public Types.PhoneNumber FriendlyName { get; private set; }
/// <summary>
/// The phone number in E.164 format
/// </summary>
[JsonProperty("phone_number")]
[JsonConverter(typeof(PhoneNumberConverter))]
public Types.PhoneNumber PhoneNumber { get; private set; }
/// <summary>
/// The LATA of this phone number
/// </summary>
[JsonProperty("lata")]
public string Lata { get; private set; }
/// <summary>
/// The locality or city of this phone number's location
/// </summary>
[JsonProperty("locality")]
public string Locality { get; private set; }
/// <summary>
/// The rate center of this phone number
/// </summary>
[JsonProperty("rate_center")]
public string RateCenter { get; private set; }
/// <summary>
/// The latitude of this phone number's location
/// </summary>
[JsonProperty("latitude")]
public decimal? Latitude { get; private set; }
/// <summary>
/// The longitude of this phone number's location
/// </summary>
[JsonProperty("longitude")]
public decimal? Longitude { get; private set; }
/// <summary>
/// The two-letter state or province abbreviation of this phone number's location
/// </summary>
[JsonProperty("region")]
public string Region { get; private set; }
/// <summary>
/// The postal or ZIP code of this phone number's location
/// </summary>
[JsonProperty("postal_code")]
public string PostalCode { get; private set; }
/// <summary>
/// The ISO country code of this phone number
/// </summary>
[JsonProperty("iso_country")]
public string IsoCountry { get; private set; }
/// <summary>
/// The type of Address resource the phone number requires
/// </summary>
[JsonProperty("address_requirements")]
public string AddressRequirements { get; private set; }
/// <summary>
/// Whether the phone number is new to the Twilio platform
/// </summary>
[JsonProperty("beta")]
public bool? Beta { get; private set; }
/// <summary>
/// Whether a phone number can receive calls or messages
/// </summary>
[JsonProperty("capabilities")]
public PhoneNumberCapabilities Capabilities { get; private set; }
private NationalResource()
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.ComponentModel;
namespace Python.Runtime
{
/// <summary>
/// Performs data conversions between managed types and Python types.
/// </summary>
[SuppressUnmanagedCodeSecurity]
internal class Converter
{
private Converter()
{
}
private static NumberFormatInfo nfi;
private static Type objectType;
private static Type stringType;
private static Type singleType;
private static Type doubleType;
private static Type decimalType;
private static Type int16Type;
private static Type int32Type;
private static Type int64Type;
private static Type flagsType;
private static Type boolType;
private static Type typeType;
static Converter()
{
nfi = NumberFormatInfo.InvariantInfo;
objectType = typeof(Object);
stringType = typeof(String);
int16Type = typeof(Int16);
int32Type = typeof(Int32);
int64Type = typeof(Int64);
singleType = typeof(Single);
doubleType = typeof(Double);
decimalType = typeof(Decimal);
flagsType = typeof(FlagsAttribute);
boolType = typeof(Boolean);
typeType = typeof(Type);
}
/// <summary>
/// Given a builtin Python type, return the corresponding CLR type.
/// </summary>
internal static Type GetTypeByAlias(IntPtr op)
{
if (op == Runtime.PyStringType)
return stringType;
if (op == Runtime.PyUnicodeType)
return stringType;
if (op == Runtime.PyIntType)
return int32Type;
if (op == Runtime.PyLongType)
return int64Type;
if (op == Runtime.PyFloatType)
return doubleType;
if (op == Runtime.PyBoolType)
return boolType;
return null;
}
internal static IntPtr GetPythonTypeByAlias(Type op)
{
if (op == stringType)
return Runtime.PyUnicodeType;
if (op == int16Type)
return Runtime.PyIntType;
if (op == int32Type)
return Runtime.PyIntType;
if (op == int64Type && Runtime.IsPython2)
return Runtime.PyLongType;
if (op == int64Type)
return Runtime.PyIntType;
if (op == doubleType)
return Runtime.PyFloatType;
if (op == singleType)
return Runtime.PyFloatType;
if (op == boolType)
return Runtime.PyBoolType;
return IntPtr.Zero;
}
/// <summary>
/// Return a Python object for the given native object, converting
/// basic types (string, int, etc.) into equivalent Python objects.
/// This always returns a new reference. Note that the System.Decimal
/// type has no Python equivalent and converts to a managed instance.
/// </summary>
internal static IntPtr ToPython<T>(T value)
{
return ToPython(value, typeof(T));
}
internal static IntPtr ToPython(object value, Type type)
{
if (value is PyObject)
{
IntPtr handle = ((PyObject)value).Handle;
Runtime.XIncref(handle);
return handle;
}
IntPtr result = IntPtr.Zero;
// Null always converts to None in Python.
if (value == null)
{
result = Runtime.PyNone;
Runtime.XIncref(result);
return result;
}
if (value is IList && !(value is INotifyPropertyChanged) && value.GetType().IsGenericType)
{
using (var resultlist = new PyList())
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o?.GetType())))
{
resultlist.Append(p);
}
}
Runtime.XIncref(resultlist.Handle);
return resultlist.Handle;
}
}
// it the type is a python subclass of a managed type then return the
// underlying python object rather than construct a new wrapper object.
var pyderived = value as IPythonDerivedType;
if (null != pyderived)
{
#if NETSTANDARD
return ClassDerivedObject.ToPython(pyderived);
#else
// if object is remote don't do this
if (!System.Runtime.Remoting.RemotingServices.IsTransparentProxy(pyderived))
{
return ClassDerivedObject.ToPython(pyderived);
}
#endif
}
// hmm - from Python, we almost never care what the declared
// type is. we'd rather have the object bound to the actual
// implementing class.
type = value.GetType();
TypeCode tc = Type.GetTypeCode(type);
switch (tc)
{
case TypeCode.Object:
return CLRObject.GetInstHandle(value, type);
case TypeCode.String:
return Runtime.PyUnicode_FromString((string)value);
case TypeCode.Int32:
return Runtime.PyInt_FromInt32((int)value);
case TypeCode.Boolean:
if ((bool)value)
{
Runtime.XIncref(Runtime.PyTrue);
return Runtime.PyTrue;
}
Runtime.XIncref(Runtime.PyFalse);
return Runtime.PyFalse;
case TypeCode.Byte:
return Runtime.PyInt_FromInt32((int)((byte)value));
case TypeCode.Char:
return Runtime.PyUnicode_FromOrdinal((int)((char)value));
case TypeCode.Int16:
return Runtime.PyInt_FromInt32((int)((short)value));
case TypeCode.Int64:
return Runtime.PyLong_FromLongLong((long)value);
case TypeCode.Single:
// return Runtime.PyFloat_FromDouble((double)((float)value));
string ss = ((float)value).ToString(nfi);
IntPtr ps = Runtime.PyString_FromString(ss);
IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
Runtime.XDecref(ps);
return op;
case TypeCode.Double:
return Runtime.PyFloat_FromDouble((double)value);
case TypeCode.SByte:
return Runtime.PyInt_FromInt32((int)((sbyte)value));
case TypeCode.UInt16:
return Runtime.PyInt_FromInt32((int)((ushort)value));
case TypeCode.UInt32:
return Runtime.PyLong_FromUnsignedLong((uint)value);
case TypeCode.UInt64:
return Runtime.PyLong_FromUnsignedLongLong((ulong)value);
default:
if (value is IEnumerable)
{
using (var resultlist = new PyList())
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o?.GetType())))
{
resultlist.Append(p);
}
}
Runtime.XIncref(resultlist.Handle);
return resultlist.Handle;
}
}
result = CLRObject.GetInstHandle(value, type);
return result;
}
}
/// <summary>
/// In a few situations, we don't have any advisory type information
/// when we want to convert an object to Python.
/// </summary>
internal static IntPtr ToPythonImplicit(object value)
{
if (value == null)
{
IntPtr result = Runtime.PyNone;
Runtime.XIncref(result);
return result;
}
return ToPython(value, objectType);
}
/// <summary>
/// Return a managed object for the given Python object, taking funny
/// byref types into account.
/// </summary>
internal static bool ToManaged(IntPtr value, Type type,
out object result, bool setError)
{
if (type.IsByRef)
{
type = type.GetElementType();
}
return Converter.ToManagedValue(value, type, out result, setError);
}
internal static bool ToManagedValue(IntPtr value, Type obType,
out object result, bool setError)
{
if (obType == typeof(PyObject))
{
Runtime.XIncref(value); // PyObject() assumes ownership
result = new PyObject(value);
return true;
}
// Common case: if the Python value is a wrapped managed object
// instance, just return the wrapped object.
ManagedType mt = ManagedType.GetManagedObject(value);
result = null;
if (mt != null)
{
if (mt is CLRObject)
{
object tmp = ((CLRObject)mt).inst;
if (obType.IsInstanceOfType(tmp))
{
result = tmp;
return true;
}
Exceptions.SetError(Exceptions.TypeError, $"value cannot be converted to {obType}");
return false;
}
if (mt is ClassBase)
{
result = ((ClassBase)mt).type;
return true;
}
// shouldn't happen
return false;
}
if (value == Runtime.PyNone && !obType.IsValueType)
{
result = null;
return true;
}
if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if( value == Runtime.PyNone )
{
result = null;
return true;
}
// Set type to underlying type
obType = obType.GetGenericArguments()[0];
}
if (obType.IsArray)
{
return ToArray(value, obType, out result, setError);
}
if (obType.IsEnum)
{
return ToEnum(value, obType, out result, setError);
}
// Conversion to 'Object' is done based on some reasonable default
// conversions (Python string -> managed string, Python int -> Int32 etc.).
if (obType == objectType)
{
if (Runtime.IsStringType(value))
{
return ToPrimitive(value, stringType, out result, setError);
}
if (Runtime.PyBool_Check(value))
{
return ToPrimitive(value, boolType, out result, setError);
}
if (Runtime.PyInt_Check(value))
{
return ToPrimitive(value, int32Type, out result, setError);
}
if (Runtime.PyLong_Check(value))
{
return ToPrimitive(value, int64Type, out result, setError);
}
if (Runtime.PyFloat_Check(value))
{
return ToPrimitive(value, doubleType, out result, setError);
}
if (Runtime.PySequence_Check(value))
{
return ToArray(value, typeof(object[]), out result, setError);
}
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Object");
}
return false;
}
// Conversion to 'Type' is done using the same mappings as above for objects.
if (obType == typeType)
{
if (value == Runtime.PyStringType)
{
result = stringType;
return true;
}
if (value == Runtime.PyBoolType)
{
result = boolType;
return true;
}
if (value == Runtime.PyIntType)
{
result = int32Type;
return true;
}
if (value == Runtime.PyLongType)
{
result = int64Type;
return true;
}
if (value == Runtime.PyFloatType)
{
result = doubleType;
return true;
}
if (value == Runtime.PyListType || value == Runtime.PyTupleType)
{
result = typeof(object[]);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type");
}
return false;
}
return ToPrimitive(value, obType, out result, setError);
}
/// <summary>
/// Convert a Python value to an instance of a primitive managed type.
/// </summary>
private static bool ToPrimitive(IntPtr value, Type obType, out object result, bool setError)
{
IntPtr overflow = Exceptions.OverflowError;
TypeCode tc = Type.GetTypeCode(obType);
result = null;
IntPtr op;
int ival;
switch (tc)
{
case TypeCode.String:
string st = Runtime.GetManagedString(value);
if (st == null)
{
goto type_error;
}
result = st;
return true;
case TypeCode.Int32:
// Trickery to support 64-bit platforms.
if (Runtime.IsPython2 && Runtime.Is32Bit)
{
op = Runtime.PyNumber_Int(value);
// As of Python 2.3, large ints magically convert :(
if (Runtime.PyLong_Check(op))
{
Runtime.XDecref(op);
goto overflow;
}
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
result = ival;
return true;
}
else // Python3 always use PyLong API
{
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
{
Exceptions.Clear();
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
long ll = (long)Runtime.PyLong_AsLongLong(op);
Runtime.XDecref(op);
if (ll == -1 && Exceptions.ErrorOccurred())
{
goto overflow;
}
if (ll > Int32.MaxValue || ll < Int32.MinValue)
{
goto overflow;
}
result = (int)ll;
return true;
}
case TypeCode.Boolean:
result = Runtime.PyObject_IsTrue(value) != 0;
return true;
case TypeCode.Byte:
#if PYTHON3
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#elif PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
{
op = Runtime.PyString_AsString(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#endif
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > Byte.MaxValue || ival < Byte.MinValue)
{
goto overflow;
}
byte b = (byte)ival;
result = b;
return true;
case TypeCode.SByte:
#if PYTHON3
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#elif PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
{
op = Runtime.PyString_AsString(value);
result = (sbyte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#endif
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > SByte.MaxValue || ival < SByte.MinValue)
{
goto overflow;
}
sbyte sb = (sbyte)ival;
result = sb;
return true;
case TypeCode.Char:
#if PYTHON3
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
op = Runtime.PyBytes_AS_STRING(value);
result = (byte)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#elif PYTHON2
if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType))
{
if (Runtime.PyString_Size(value) == 1)
{
op = Runtime.PyString_AsString(value);
result = (char)Marshal.ReadByte(op);
return true;
}
goto type_error;
}
#endif
else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType))
{
if (Runtime.PyUnicode_GetSize(value) == 1)
{
op = Runtime.PyUnicode_AsUnicode(value);
Char[] buff = new Char[1];
Marshal.Copy(op, buff, 0, 1);
result = buff[0];
return true;
}
goto type_error;
}
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
goto type_error;
}
ival = Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > Char.MaxValue || ival < Char.MinValue)
{
goto overflow;
}
result = (char)ival;
return true;
case TypeCode.Int16:
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > Int16.MaxValue || ival < Int16.MinValue)
{
goto overflow;
}
short s = (short)ival;
result = s;
return true;
case TypeCode.Int64:
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
long l = (long)Runtime.PyLong_AsLongLong(op);
Runtime.XDecref(op);
if ((l == -1) && Exceptions.ErrorOccurred())
{
goto overflow;
}
result = l;
return true;
case TypeCode.UInt16:
op = Runtime.PyNumber_Int(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ival = (int)Runtime.PyInt_AsLong(op);
Runtime.XDecref(op);
if (ival > UInt16.MaxValue || ival < UInt16.MinValue)
{
goto overflow;
}
ushort us = (ushort)ival;
result = us;
return true;
case TypeCode.UInt32:
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
uint ui;
try
{
ui = Convert.ToUInt32(Runtime.PyLong_AsUnsignedLong(op));
} catch (OverflowException)
{
// Probably wasn't an overflow in python but was in C# (e.g. if cpython
// longs are 64 bit then 0xFFFFFFFF + 1 will not overflow in
// PyLong_AsUnsignedLong)
Runtime.XDecref(op);
goto overflow;
}
if (Exceptions.ErrorOccurred())
{
Runtime.XDecref(op);
goto overflow;
}
IntPtr check = Runtime.PyLong_FromUnsignedLong(ui);
int err = Runtime.PyObject_Compare(check, op);
Runtime.XDecref(check);
Runtime.XDecref(op);
if (0 != err || Exceptions.ErrorOccurred())
{
goto overflow;
}
result = ui;
return true;
case TypeCode.UInt64:
op = Runtime.PyNumber_Long(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
ulong ul = (ulong)Runtime.PyLong_AsUnsignedLongLong(op);
Runtime.XDecref(op);
if (Exceptions.ErrorOccurred())
{
goto overflow;
}
result = ul;
return true;
case TypeCode.Single:
op = Runtime.PyNumber_Float(value);
if (op == IntPtr.Zero)
{
if (Exceptions.ExceptionMatches(overflow))
{
goto overflow;
}
goto type_error;
}
double dd = Runtime.PyFloat_AsDouble(op);
Runtime.CheckExceptionOccurred();
Runtime.XDecref(op);
if (dd > Single.MaxValue || dd < Single.MinValue)
{
if (!double.IsInfinity(dd))
{
goto overflow;
}
}
result = (float)dd;
return true;
case TypeCode.Double:
op = Runtime.PyNumber_Float(value);
if (op == IntPtr.Zero)
{
goto type_error;
}
double d = Runtime.PyFloat_AsDouble(op);
Runtime.CheckExceptionOccurred();
Runtime.XDecref(op);
result = d;
return true;
}
type_error:
if (setError)
{
string tpName = Runtime.PyObject_GetTypeName(value);
Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}");
}
return false;
overflow:
if (setError)
{
Exceptions.SetError(Exceptions.OverflowError, "value too large to convert");
}
return false;
}
private static void SetConversionError(IntPtr value, Type target)
{
IntPtr ob = Runtime.PyObject_Repr(value);
string src = Runtime.GetManagedString(ob);
Runtime.XDecref(ob);
Exceptions.SetError(Exceptions.TypeError, $"Cannot convert {src} to {target}");
}
/// <summary>
/// Convert a Python value to a correctly typed managed array instance.
/// The Python value must support the Python iterator protocol or and the
/// items in the sequence must be convertible to the target array type.
/// </summary>
private static bool ToArray(IntPtr value, Type obType, out object result, bool setError)
{
Type elementType = obType.GetElementType();
result = null;
bool IsSeqObj = Runtime.PySequence_Check(value);
var len = IsSeqObj ? Runtime.PySequence_Size(value) : -1;
IntPtr IterObject = Runtime.PyObject_GetIter(value);
if(IterObject==IntPtr.Zero) {
if (setError)
{
SetConversionError(value, obType);
}
return false;
}
Array items;
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(elementType);
IList list = IsSeqObj ? (IList) Activator.CreateInstance(constructedListType, new Object[] {(int) len}) :
(IList) Activator.CreateInstance(constructedListType);
IntPtr item;
while ((item = Runtime.PyIter_Next(IterObject)) != IntPtr.Zero)
{
object obj = null;
if (!Converter.ToManaged(item, elementType, out obj, true))
{
Runtime.XDecref(item);
return false;
}
list.Add(obj);
Runtime.XDecref(item);
}
Runtime.XDecref(IterObject);
items = Array.CreateInstance(elementType, list.Count);
list.CopyTo(items, 0);
result = items;
return true;
}
/// <summary>
/// Convert a Python value to a correctly typed managed enum instance.
/// </summary>
private static bool ToEnum(IntPtr value, Type obType, out object result, bool setError)
{
Type etype = Enum.GetUnderlyingType(obType);
result = null;
if (!ToPrimitive(value, etype, out result, setError))
{
return false;
}
if (Enum.IsDefined(obType, result))
{
result = Enum.ToObject(obType, result);
return true;
}
if (obType.GetCustomAttributes(flagsType, true).Length > 0)
{
result = Enum.ToObject(obType, result);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.ValueError, "invalid enumeration value");
}
return false;
}
}
public static class ConverterExtension
{
public static PyObject ToPython(this object o)
{
return new PyObject(Converter.ToPython(o, o?.GetType()));
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// TaskAwaiter.cs
//
// <OWNER>[....]</OWNER>
//
// Types for awaiting Task and Task<T>. These types are emitted from Task{<T>}.GetAwaiter
// and Task{<T>}.ConfigureAwait. They are meant to be used only by the compiler, e.g.
//
// await nonGenericTask;
// =====================
// var $awaiter = nonGenericTask.GetAwaiter();
// if (!$awaiter.IsCompleted)
// {
// SPILL:
// $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this);
// return;
// Label:
// UNSPILL;
// }
// $awaiter.GetResult();
//
// result += await genericTask.ConfigureAwait(false);
// ===================================================================================
// var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter();
// if (!$awaiter.IsCompleted)
// {
// SPILL;
// $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this);
// return;
// Label:
// UNSPILL;
// }
// result += $awaiter.GetResult();
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Permissions;
using System.Diagnostics.Tracing;
// NOTE: For performance reasons, initialization is not verified. If a developer
// incorrectly initializes a task awaiter, which should only be done by the compiler,
// NullReferenceExceptions may be generated (the alternative would be for us to detect
// this case and then throw a different exception instead). This is the same tradeoff
// that's made with other compiler-focused value types like List<T>.Enumerator.
namespace System.Runtime.CompilerServices
{
/// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
[HostProtection(Synchronization = true, ExternalThreading = true)]
public struct TaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
private readonly Task m_task;
/// <summary>Initializes the <see cref="TaskAwaiter"/>.</summary>
/// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param>
internal TaskAwaiter(Task task)
{
Contract.Requires(task != null, "Constructing an awaiter requires a task to await.");
m_task = task;
}
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception>
/// <exception cref="System.Exception">The task completed in a Faulted state.</exception>
public void GetResult()
{
ValidateEnd(m_task);
}
/// <summary>
/// Fast checks for the end of an await operation to determine whether more needs to be done
/// prior to completing the await.
/// </summary>
/// <param name="task">The awaited task.</param>
internal static void ValidateEnd(Task task)
{
// Fast checks that can be inlined.
if (task.IsWaitNotificationEnabledOrNotRanToCompletion)
{
// If either the end await bit is set or we're not completed successfully,
// fall back to the slower path.
HandleNonSuccessAndDebuggerNotification(task);
}
}
/// <summary>
/// Ensures the task is completed, triggers any necessary debugger breakpoints for completing
/// the await on the task, and throws an exception if the task did not complete successfully.
/// </summary>
/// <param name="task">The awaited task.</param>
private static void HandleNonSuccessAndDebuggerNotification(Task task)
{
// NOTE: The JIT refuses to inline ValidateEnd when it contains the contents
// of HandleNonSuccessAndDebuggerNotification, hence the separation.
// Synchronously wait for the task to complete. When used by the compiler,
// the task will already be complete. This code exists only for direct GetResult use,
// for cases where the same exception propagation semantics used by "await" are desired,
// but where for one reason or another synchronous rather than asynchronous waiting is needed.
if (!task.IsCompleted)
{
bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken));
Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed.");
}
// Now that we're done, alert the debugger if so requested
task.NotifyDebuggerOfWaitCompletionIfNecessary();
// And throw an exception if the task is faulted or canceled.
if (!task.IsRanToCompletion) ThrowForNonSuccess(task);
}
/// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary>
private static void ThrowForNonSuccess(Task task)
{
Contract.Requires(task.IsCompleted, "Task must have been completed by now.");
Contract.Requires(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully.");
// Handle whether the task has been canceled or faulted
switch (task.Status)
{
// If the task completed in a canceled state, throw an OperationCanceledException.
// This will either be the OCE that actually caused the task to cancel, or it will be a new
// TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the
// completed task's CancellationToken if it has one, including that CT in the OCE.
case TaskStatus.Canceled:
var oceEdi = task.GetCancellationExceptionDispatchInfo();
if (oceEdi != null)
{
oceEdi.Throw();
Contract.Assert(false, "Throw() should have thrown");
}
throw new TaskCanceledException(task);
// If the task faulted, throw its first exception,
// even if it contained more than one.
case TaskStatus.Faulted:
var edis = task.GetExceptionDispatchInfos();
if (edis.Count > 0)
{
edis[0].Throw();
Contract.Assert(false, "Throw() should have thrown");
break; // Necessary to compile: non-reachable, but compiler can't determine that
}
else
{
Contract.Assert(false, "There should be exceptions if we're Faulted.");
throw task.Exception;
}
}
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="task">The task being awaited.</param>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param>
/// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
[SecurityCritical]
internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext)
{
if (continuation == null) throw new ArgumentNullException("continuation");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
#if !MONO
// If TaskWait* ETW events are enabled, trace a beginning event for this await
// and set up an ending event to be traced when the asynchronous await completes.
if ( TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled)
{
continuation = OutputWaitEtwEvents(task, continuation);
}
#endif
// Set the continuation onto the awaited task.
task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext, ref stackMark);
}
/// <summary>
/// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event.
/// </summary>
/// <param name="task">The task being awaited.</param>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <returns>The action to use as the actual continuation.</returns>
private static Action OutputWaitEtwEvents(Task task, Action continuation)
{
Contract.Requires(task != null, "Need a task to wait on");
Contract.Requires(continuation != null, "Need a continuation to invoke when the wait completes");
if (Task.s_asyncDebuggingEnabled)
{
Task.AddToActiveTasks(task);
}
#if !MONO
var etwLog = TplEtwProvider.Log;
if (etwLog.IsEnabled())
{
// ETW event for Task Wait Begin
var currentTaskAtBegin = Task.InternalCurrent;
// If this task's continuation is another task, get it.
var continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation);
etwLog.TaskWaitBegin(
(currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id),
(currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0),
task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous,
(continuationTask != null ? continuationTask.Id : 0), System.Threading.Thread.GetDomainID());
}
#endif
// Create a continuation action that outputs the end event and then invokes the user
// provided delegate. This incurs the allocations for the closure/delegate, but only if the event
// is enabled, and in doing so it allows us to pass the awaited task's information into the end event
// in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter
// just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred).
return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, () =>
{
if (Task.s_asyncDebuggingEnabled)
{
Task.RemoveFromActiveTasks(task.Id);
}
#if !MONO
// ETW event for Task Wait End.
Guid prevActivityId = new Guid();
bool bEtwLogEnabled = etwLog.IsEnabled();
if (bEtwLogEnabled)
{
var currentTaskAtEnd = Task.InternalCurrent;
etwLog.TaskWaitEnd(
(currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id),
(currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0),
task.Id);
// Ensure the continuation runs under the activity ID of the task that completed for the
// case the antecendent is a promise (in the other cases this is already the case).
if (etwLog.TasksSetActivityIds && (task.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0)
EventSource.SetCurrentThreadActivityId(TplEtwProvider.CreateGuidForTaskID(task.Id), out prevActivityId);
}
#endif
// Invoke the original continuation provided to OnCompleted.
continuation();
#if !MONO
if (bEtwLogEnabled)
{
etwLog.TaskWaitContinuationComplete(task.Id);
if (etwLog.TasksSetActivityIds && (task.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0)
EventSource.SetCurrentThreadActivityId(prevActivityId);
}
#endif
});
}
}
/// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
[HostProtection(Synchronization = true, ExternalThreading = true)]
public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
private readonly Task<TResult> m_task;
/// <summary>Initializes the <see cref="TaskAwaiter{TResult}"/>.</summary>
/// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param>
internal TaskAwaiter(Task<TResult> task)
{
Contract.Requires(task != null, "Constructing an awaiter requires a task to await.");
m_task = task;
}
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception>
/// <exception cref="System.Exception">The task completed in a Faulted state.</exception>
public TResult GetResult()
{
TaskAwaiter.ValidateEnd(m_task);
return m_task.ResultOnSuccess;
}
}
/// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
public struct ConfiguredTaskAwaitable
{
/// <summary>The task being awaited.</summary>
private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter;
/// <summary>Initializes the <see cref="ConfiguredTaskAwaitable"/>.</summary>
/// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task"/>.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
/// </param>
internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext)
{
Contract.Requires(task != null, "Constructing an awaitable requires a task to await.");
m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext);
}
/// <summary>Gets an awaiter for this awaitable.</summary>
/// <returns>The awaiter.</returns>
public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter()
{
return m_configuredTaskAwaiter;
}
/// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
[HostProtection(Synchronization = true, ExternalThreading = true)]
public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
private readonly Task m_task;
/// <summary>Whether to attempt marshaling back to the original context.</summary>
private readonly bool m_continueOnCapturedContext;
/// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary>
/// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to await.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original context captured
/// when BeginAwait is called; otherwise, false.
/// </param>
internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext)
{
Contract.Requires(task != null, "Constructing an awaiter requires a task to await.");
m_task = task;
m_continueOnCapturedContext = continueOnCapturedContext;
}
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception>
/// <exception cref="System.Exception">The task completed in a Faulted state.</exception>
public void GetResult()
{
TaskAwaiter.ValidateEnd(m_task);
}
}
}
/// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
public struct ConfiguredTaskAwaitable<TResult>
{
/// <summary>The underlying awaitable on whose logic this awaitable relies.</summary>
private readonly ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter m_configuredTaskAwaiter;
/// <summary>Initializes the <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary>
/// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
/// </param>
internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext)
{
m_configuredTaskAwaiter = new ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter(task, continueOnCapturedContext);
}
/// <summary>Gets an awaiter for this awaitable.</summary>
/// <returns>The awaiter.</returns>
public ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter GetAwaiter()
{
return m_configuredTaskAwaiter;
}
/// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
[HostProtection(Synchronization = true, ExternalThreading = true)]
public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
private readonly Task<TResult> m_task;
/// <summary>Whether to attempt marshaling back to the original context.</summary>
private readonly bool m_continueOnCapturedContext;
/// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary>
/// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
/// </param>
internal ConfiguredTaskAwaiter(Task<TResult> task, bool continueOnCapturedContext)
{
Contract.Requires(task != null, "Constructing an awaiter requires a task to await.");
m_task = task;
m_continueOnCapturedContext = continueOnCapturedContext;
}
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
/// <param name="continuation">The action to invoke when the await operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception>
/// <exception cref="System.Exception">The task completed in a Faulted state.</exception>
public TResult GetResult()
{
TaskAwaiter.ValidateEnd(m_task);
return m_task.ResultOnSuccess;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TheBraverest.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Requests;
using Cassandra.Tasks;
namespace Cassandra
{
/// <summary>
/// Keeps metadata on the connected cluster, including known nodes and schema
/// definitions.
/// </summary>
public class Metadata : IDisposable
{
private const string SelectSchemaVersionPeers = "SELECT schema_version FROM system.peers";
private const string SelectSchemaVersionLocal = "SELECT schema_version FROM system.local";
private static readonly Logger Logger = new Logger(typeof(ControlConnection));
private volatile TokenMap _tokenMap;
private volatile ConcurrentDictionary<string, KeyspaceMetadata> _keyspaces = new ConcurrentDictionary<string,KeyspaceMetadata>();
private volatile SchemaParser _schemaParser;
public event HostsEventHandler HostsEvent;
public event SchemaChangedEventHandler SchemaChangedEvent;
/// <summary>
/// Returns the name of currently connected cluster.
/// </summary>
/// <returns>the Cassandra name of currently connected cluster.</returns>
public String ClusterName { get; internal set; }
/// <summary>
/// Gets the configuration associated with this instance.
/// </summary>
internal Configuration Configuration { get; private set; }
/// <summary>
/// Control connection to be used to execute the queries to retrieve the metadata
/// </summary>
internal IMetadataQueryProvider ControlConnection { get; set; }
internal SchemaParser SchemaParser { get { return _schemaParser; } }
internal string Partitioner { get; set; }
internal Hosts Hosts { get; private set; }
internal Metadata(Configuration configuration)
{
Configuration = configuration;
Hosts = new Hosts(configuration.Policies.ReconnectionPolicy);
Hosts.Down += OnHostDown;
Hosts.Up += OnHostUp;
}
public void Dispose()
{
ShutDown();
}
public Host GetHost(IPEndPoint address)
{
Host host;
if (Hosts.TryGet(address, out host))
return host;
return null;
}
internal Host AddHost(IPEndPoint address)
{
return Hosts.Add(address);
}
internal void RemoveHost(IPEndPoint address)
{
Hosts.RemoveIfExists(address);
}
internal void FireSchemaChangedEvent(SchemaChangedEventArgs.Kind what, string keyspace, string table, object sender = null)
{
if (SchemaChangedEvent != null)
{
SchemaChangedEvent(sender ?? this, new SchemaChangedEventArgs {Keyspace = keyspace, What = what, Table = table});
}
}
internal void SetDownHost(IPEndPoint address, object sender = null)
{
Hosts.SetDownIfExists(address);
}
private void OnHostDown(Host h, long reconnectionDelay)
{
if (HostsEvent != null)
{
HostsEvent(this, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Down });
}
}
private void OnHostUp(Host h)
{
if (HostsEvent != null)
{
HostsEvent(h, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Up });
}
}
internal void BringUpHost(IPEndPoint address, object sender = null)
{
//Add the host if not already present
var host = Hosts.Add(address);
//Bring it UP
host.BringUpIfDown();
}
/// <summary>
/// Returns all known hosts of this cluster.
/// </summary>
/// <returns>collection of all known hosts of this cluster.</returns>
public ICollection<Host> AllHosts()
{
return Hosts.ToCollection();
}
public IEnumerable<IPEndPoint> AllReplicas()
{
return Hosts.AllEndPointsToCollection();
}
internal void RebuildTokenMap()
{
Logger.Info("Rebuilding token map");
if (Partitioner == null)
{
throw new DriverInternalError("Partitioner can not be null");
}
_tokenMap = TokenMap.Build(Partitioner, Hosts.ToCollection(), _keyspaces.Values);
}
/// <summary>
/// Get the replicas for a given partition key and keyspace
/// </summary>
public ICollection<Host> GetReplicas(string keyspaceName, byte[] partitionKey)
{
if (_tokenMap == null)
{
return new Host[0];
}
return _tokenMap.GetReplicas(keyspaceName, _tokenMap.Factory.Hash(partitionKey));
}
public ICollection<Host> GetReplicas(byte[] partitionKey)
{
return GetReplicas(null, partitionKey);
}
/// <summary>
/// Returns metadata of specified keyspace.
/// </summary>
/// <param name="keyspace"> the name of the keyspace for which metadata should be
/// returned. </param>
/// <returns>the metadata of the requested keyspace or <c>null</c> if
/// <c>* keyspace</c> is not a known keyspace.</returns>
public KeyspaceMetadata GetKeyspace(string keyspace)
{
//Use local cache
KeyspaceMetadata ksInfo;
_keyspaces.TryGetValue(keyspace, out ksInfo);
return ksInfo;
}
/// <summary>
/// Returns a collection of all defined keyspaces names.
/// </summary>
/// <returns>a collection of all defined keyspaces names.</returns>
public ICollection<string> GetKeyspaces()
{
//Use local cache
return _keyspaces.Keys;
}
/// <summary>
/// Returns names of all tables which are defined within specified keyspace.
/// </summary>
/// <param name="keyspace">the name of the keyspace for which all tables metadata should be
/// returned.</param>
/// <returns>an ICollection of the metadata for the tables defined in this
/// keyspace.</returns>
public ICollection<string> GetTables(string keyspace)
{
KeyspaceMetadata ksMetadata;
if (!_keyspaces.TryGetValue(keyspace, out ksMetadata))
{
return new string[0];
}
return ksMetadata.GetTablesNames();
}
/// <summary>
/// Returns TableMetadata for specified table in specified keyspace.
/// </summary>
/// <param name="keyspace">name of the keyspace within specified table is defined.</param>
/// <param name="tableName">name of table for which metadata should be returned.</param>
/// <returns>a TableMetadata for the specified table in the specified keyspace.</returns>
public TableMetadata GetTable(string keyspace, string tableName)
{
KeyspaceMetadata ksMetadata;
if (!_keyspaces.TryGetValue(keyspace, out ksMetadata))
{
return null;
}
return ksMetadata.GetTableMetadata(tableName);
}
internal Task<TableMetadata> GetTableAsync(string keyspace, string tableName)
{
KeyspaceMetadata ksMetadata;
if (!_keyspaces.TryGetValue(keyspace, out ksMetadata))
{
return TaskHelper.ToTask((TableMetadata)null);
}
return ksMetadata.GetTableMetadataAsync(tableName);
}
/// <summary>
/// Returns the view metadata for the provided view name in the keyspace.
/// </summary>
/// <param name="keyspace">name of the keyspace within specified view is defined.</param>
/// <param name="name">name of view.</param>
/// <returns>a MaterializedViewMetadata for the view in the specified keyspace.</returns>
public MaterializedViewMetadata GetMaterializedView(string keyspace, string name)
{
KeyspaceMetadata ksMetadata;
if (!_keyspaces.TryGetValue(keyspace, out ksMetadata))
{
return null;
}
return ksMetadata.GetMaterializedViewMetadata(name);
}
/// <summary>
/// Gets the definition associated with a User Defined Type from Cassandra
/// </summary>
public UdtColumnInfo GetUdtDefinition(string keyspace, string typeName)
{
KeyspaceMetadata ksMetadata;
if (!_keyspaces.TryGetValue(keyspace, out ksMetadata))
{
return null;
}
return ksMetadata.GetUdtDefinition(typeName);
}
/// <summary>
/// Gets the definition associated with a User Defined Type from Cassandra
/// </summary>
public Task<UdtColumnInfo> GetUdtDefinitionAsync(string keyspace, string typeName)
{
KeyspaceMetadata ksMetadata;
if (!_keyspaces.TryGetValue(keyspace, out ksMetadata))
{
return TaskHelper.ToTask<UdtColumnInfo>(null);
}
return ksMetadata.GetUdtDefinitionAsync(typeName);
}
/// <summary>
/// Gets the definition associated with a User Defined Function from Cassandra
/// </summary>
/// <returns>The function metadata or null if not found.</returns>
public FunctionMetadata GetFunction(string keyspace, string name, string[] signature)
{
KeyspaceMetadata ksMetadata;
if (!_keyspaces.TryGetValue(keyspace, out ksMetadata))
{
return null;
}
return ksMetadata.GetFunction(name, signature);
}
/// <summary>
/// Gets the definition associated with a aggregate from Cassandra
/// </summary>
/// <returns>The aggregate metadata or null if not found.</returns>
public AggregateMetadata GetAggregate(string keyspace, string name, string[] signature)
{
KeyspaceMetadata ksMetadata;
if (!_keyspaces.TryGetValue(keyspace, out ksMetadata))
{
return null;
}
return ksMetadata.GetAggregate(name, signature);
}
/// <summary>
/// Gets the query trace.
/// </summary>
/// <param name="trace">The query trace that contains the id, which properties are going to be populated.</param>
/// <returns></returns>
internal Task<QueryTrace> GetQueryTraceAsync(QueryTrace trace)
{
return _schemaParser.GetQueryTrace(trace, Configuration.Timer);
}
/// <summary>
/// Updates the keyspace and token information
/// </summary>
public bool RefreshSchema(string keyspace = null, string table = null)
{
if (table == null)
{
//Refresh all the keyspaces and tables information
return TaskHelper.WaitToComplete(RefreshKeyspaces(true), Configuration.ClientOptions.QueryAbortTimeout);
}
var ks = GetKeyspace(keyspace);
if (ks == null)
{
return false;
}
ks.ClearTableMetadata(table);
return true;
}
/// <summary>
/// Retrieves the keyspaces, stores the information in the internal state and rebuilds the token map
/// </summary>
internal Task<bool> RefreshKeyspaces(bool retry)
{
Logger.Info("Retrieving keyspaces metadata");
return _schemaParser
.GetKeyspaces(retry)
.ContinueSync(ksList =>
{
var ksMap = new ConcurrentDictionary<string, KeyspaceMetadata>();
foreach (var ks in ksList)
{
ksMap.AddOrUpdate(ks.Name, ks, (k, v) => v);
}
_keyspaces = ksMap;
RebuildTokenMap();
return true;
});
}
public void ShutDown(int timeoutMs = Timeout.Infinite)
{
//it is really not required to be called, left as it is part of the public API
//dereference the control connection
ControlConnection = null;
}
internal bool RemoveKeyspace(string name)
{
Logger.Verbose("Removing keyspace metadata: " + name);
KeyspaceMetadata ks;
if (!_keyspaces.TryRemove(name, out ks))
{
//The keyspace didn't exist
return false;
}
RebuildTokenMap();
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this);
return true;
}
internal Task<KeyspaceMetadata> RefreshSingleKeyspace(bool added, string name)
{
Logger.Verbose("Updating keyspace metadata: " + name);
return _schemaParser.GetKeyspace(name).ContinueSync(ks =>
{
if (ks == null)
{
return null;
}
_keyspaces.AddOrUpdate(name, ks, (k, v) => ks);
RebuildTokenMap();
var eventKind = added ? SchemaChangedEventArgs.Kind.Created : SchemaChangedEventArgs.Kind.Updated;
FireSchemaChangedEvent(eventKind, name, null, this);
return ks;
});
}
internal void RefreshTable(string keyspaceName, string tableName)
{
KeyspaceMetadata ksMetadata;
if (_keyspaces.TryGetValue(keyspaceName, out ksMetadata))
{
ksMetadata.ClearTableMetadata(tableName);
}
}
internal void RefreshView(string keyspaceName, string name)
{
KeyspaceMetadata ksMetadata;
if (_keyspaces.TryGetValue(keyspaceName, out ksMetadata))
{
ksMetadata.ClearViewMetadata(name);
}
}
internal void ClearFunction(string keyspaceName, string functionName, string[] signature)
{
KeyspaceMetadata ksMetadata;
if (_keyspaces.TryGetValue(keyspaceName, out ksMetadata))
{
ksMetadata.ClearFunction(functionName, signature);
}
}
internal void ClearAggregate(string keyspaceName, string aggregateName, string[] signature)
{
KeyspaceMetadata ksMetadata;
if (_keyspaces.TryGetValue(keyspaceName, out ksMetadata))
{
ksMetadata.ClearAggregate(aggregateName, signature);
}
}
/// <summary>
/// Waits until that the schema version in all nodes is the same or the waiting time passed.
/// This method blocks the calling thread.
/// </summary>
internal void WaitForSchemaAgreement(Connection connection)
{
if (Hosts.Count == 1)
{
//If there is just one node, the schema is up to date in all nodes :)
return;
}
var start = DateTime.Now;
var waitSeconds = Configuration.ProtocolOptions.MaxSchemaAgreementWaitSeconds;
Logger.Info("Waiting for schema agreement");
try
{
var totalVersions = 0;
while (DateTime.Now.Subtract(start).TotalSeconds < waitSeconds)
{
var schemaVersionLocalQuery = new QueryRequest(ControlConnection.ProtocolVersion, SelectSchemaVersionLocal, false, QueryProtocolOptions.Default);
var schemaVersionPeersQuery = new QueryRequest(ControlConnection.ProtocolVersion, SelectSchemaVersionPeers, false, QueryProtocolOptions.Default);
var queries = new [] { connection.Send(schemaVersionLocalQuery), connection.Send(schemaVersionPeersQuery) };
// ReSharper disable once CoVariantArrayConversion
Task.WaitAll(queries, Configuration.ClientOptions.QueryAbortTimeout);
var versions = new HashSet<Guid>
{
Cassandra.ControlConnection.GetRowSet(queries[0].Result).First().GetValue<Guid>("schema_version")
};
var peerVersions = Cassandra.ControlConnection.GetRowSet(queries[1].Result).Select(r => r.GetValue<Guid>("schema_version"));
foreach (var v in peerVersions)
{
versions.Add(v);
}
totalVersions = versions.Count;
if (versions.Count == 1)
{
return;
}
Thread.Sleep(500);
}
Logger.Info(String.Format("Waited for schema agreement, still {0} schema versions in the cluster.", totalVersions));
}
catch (Exception ex)
{
//Exceptions are not fatal
Logger.Error("There was an exception while trying to retrieve schema versions", ex);
}
}
/// <summary>
/// Sets the Cassandra version in order to identify how to parse the metadata information
/// </summary>
/// <param name="version"></param>
internal void SetCassandraVersion(Version version)
{
_schemaParser = SchemaParser.GetInstance(version, this, GetUdtDefinitionAsync, _schemaParser);
}
}
}
| |
namespace Macabresoft.Macabre2D.Framework;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Macabresoft.Core;
using Microsoft.Xna.Framework;
/// <summary>
/// Represents four directions from a single tile.
/// </summary>
[Flags]
public enum CardinalDirections : byte {
None = 0,
North = 1 << 0,
West = 1 << 1,
East = 1 << 2,
South = 1 << 3,
All = North | West | East | South
}
/// <summary>
/// A tileable entity. Contains a <see cref="TileGrid" /> and implements
/// <see cref="ITileableEntity" />
/// </summary>
public abstract class TileableEntity : Entity, ITileableEntity {
private readonly ResettableLazy<BoundingArea> _boundingArea;
private readonly Dictionary<Point, BoundingArea> _tilePositionToBoundingArea = new();
/// <inheritdoc />
public event EventHandler? TilesChanged;
/// <summary>
/// Initializes a new instance of the <see cref="TileableEntity" /> class.
/// </summary>
protected TileableEntity() : base() {
this._boundingArea = new ResettableLazy<BoundingArea>(this.CreateBoundingArea);
}
/// <inheritdoc />
public abstract IReadOnlyCollection<Point> ActiveTiles { get; }
/// <inheritdoc />
public BoundingArea BoundingArea => this._boundingArea.Value;
/// <inheritdoc />
public IGridContainer CurrentGrid { get; private set; } = GridContainer.EmptyGridContainer;
/// <inheritdoc />
public Point MaximumTile { get; private set; }
/// <inheritdoc />
public Point MinimumTile { get; private set; }
/// <inheritdoc />
public bool AddTile(Point tile) {
var result = this.TryAddTile(tile);
if (result) {
if (tile.X > this.MaximumTile.X) {
this.MaximumTile = new Point(tile.X, this.MaximumTile.Y);
}
else if (tile.X < this.MinimumTile.X) {
this.MinimumTile = new Point(tile.X, this.MinimumTile.Y);
}
if (tile.Y > this.MaximumTile.Y) {
this.MaximumTile = new Point(this.MaximumTile.X, tile.Y);
}
else if (tile.Y < this.MinimumTile.Y) {
this.MinimumTile = new Point(this.MinimumTile.X, tile.Y);
}
this.ResetBoundingArea();
this.TilesChanged.SafeInvoke(this);
}
return result;
}
/// <summary>
/// Clears all active tiles.
/// </summary>
[EntityCommand("Clear Tiles")]
public void ClearTiles() {
this.ClearActiveTiles();
this.MinimumTile = Point.Zero;
this.MaximumTile = Point.Zero;
this.ResetBoundingArea();
this.TilesChanged.SafeInvoke(this);
}
/// <inheritdoc />
public Point GetTileThatContains(Vector2 worldPosition) {
var result = Point.Zero;
var grid = this.CurrentGrid;
if (grid.WorldTileSize.X > 0 && grid.WorldTileSize.Y > 0) {
var xTile = Math.Floor(worldPosition.X / grid.WorldTileSize.X);
var yTile = Math.Floor(worldPosition.Y / grid.WorldTileSize.Y);
result = new Point((int)xTile, (int)yTile);
}
return result;
}
/// <inheritdoc />
public abstract bool HasActiveTileAt(Point tilePosition);
/// <inheritdoc />
public bool HasActiveTileAt(Vector2 worldPosition) {
var tile = this.GetTileThatContains(worldPosition);
return this.HasActiveTileAt(tile);
}
/// <inheritdoc />
public override void Initialize(IScene scene, IEntity parent) {
base.Initialize(scene, parent);
this.ResetGridContainer();
this.ResetMinimumTile();
this.ResetMaximumTile();
}
/// <inheritdoc />
public override void OnRemovedFromSceneTree() {
this.CurrentGrid.PropertyChanged -= this.GridContainer_PropertyChanged;
base.OnRemovedFromSceneTree();
}
/// <inheritdoc />
public bool RemoveTile(Point tile) {
var result = this.TryRemoveTile(tile);
if (result) {
this._tilePositionToBoundingArea.Remove(tile);
if (tile.X == this.MinimumTile.X || tile.Y == this.MinimumTile.Y) {
this.ResetMinimumTile();
this.ResetBoundingArea();
}
if (tile.X == this.MaximumTile.X || tile.Y == this.MaximumTile.Y) {
this.ResetMaximumTile();
this.ResetBoundingArea();
}
this.TilesChanged.SafeInvoke(this);
}
return result;
}
/// <summary>
/// Clears the active tiles.
/// </summary>
protected abstract void ClearActiveTiles();
/// <summary>
/// Gets the maximum tile.
/// </summary>
/// <returns>The maximum tile.</returns>
protected abstract Point GetMaximumTile();
/// <summary>
/// Gets the minimum tile.
/// </summary>
/// <returns>The minimum tile.</returns>
protected abstract Point GetMinimumTile();
/// <summary>
/// Gets the bounding area for the tile at the specified position.
/// </summary>
/// <param name="tile">The tile.</param>
/// <returns>The bounding area.</returns>
protected BoundingArea GetTileBoundingArea(Point tile) {
if (!this._tilePositionToBoundingArea.TryGetValue(tile, out var boundingArea)) {
var grid = this.CurrentGrid;
var tilePosition = grid.GetTilePosition(tile);
boundingArea = new BoundingArea(tilePosition, tilePosition + grid.WorldTileSize);
this._tilePositionToBoundingArea.Add(tile, boundingArea);
}
return boundingArea;
}
/// <summary>
/// Gets the tile scale for the specified sprite.
/// </summary>
/// <param name="spriteSize">The sprite size.</param>
/// <returns>The scale for the sprite to fit within the tile grid.</returns>
protected Vector2 GetTileScale(Point spriteSize) {
var inversePixelsPerUnit = this.Scene.Game.Project.Settings.InversePixelsPerUnit;
var result = this.CurrentGrid.WorldTileSize;
if (spriteSize.X != 0 && spriteSize.Y != 0) {
var spriteWidth = spriteSize.X * inversePixelsPerUnit;
var spriteHeight = spriteSize.Y * inversePixelsPerUnit;
result = new Vector2(result.X / spriteWidth, result.Y / spriteHeight);
}
return result;
}
/// <summary>
/// Determines whether this has active tiles.
/// </summary>
/// <returns><c>true</c> if this has active tiles; otherwise, <c>false</c>.</returns>
protected abstract bool HasActiveTiles();
/// <inheritdoc />
protected override void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) {
base.OnPropertyChanged(sender, e);
if (e.PropertyName == nameof(IEntity.Parent)) {
this.ResetGridContainer();
}
}
/// <summary>
/// Resets the bounding area.
/// </summary>
protected virtual void ResetBoundingArea() {
this._tilePositionToBoundingArea.Clear();
this._boundingArea.Reset();
}
/// <summary>
/// Tries to add the specified tile.
/// </summary>
/// <param name="tile">The tile.</param>
/// <returns>A value indicating whether or not the tile was added.</returns>
protected abstract bool TryAddTile(Point tile);
/// <summary>
/// Tries to remove the specified tile.
/// </summary>
/// <param name="tile">The tile.</param>
/// <returns>A value indicating whether or not the tile was removed.</returns>
protected abstract bool TryRemoveTile(Point tile);
private BoundingArea CreateBoundingArea() {
BoundingArea result;
if (this.HasActiveTiles() && this.CurrentGrid is { } grid and not EmptyGridContainer) {
result = new BoundingArea(grid.GetTilePosition(this.MinimumTile), grid.GetTilePosition(this.MaximumTile + new Point(1, 1)));
}
else {
result = new BoundingArea();
}
return result;
}
private void GridContainer_PropertyChanged(object? sender, PropertyChangedEventArgs e) {
if (e.PropertyName == nameof(IGridContainer.WorldTileSize)) {
this.ResetBoundingArea();
this.TilesChanged?.SafeInvoke(this);
}
}
private void ResetGridContainer() {
this.CurrentGrid.PropertyChanged -= this.GridContainer_PropertyChanged;
if (this.TryGetParentEntity<IGridContainer>(out var gridContainer) && gridContainer != null) {
this.CurrentGrid = gridContainer;
this.CurrentGrid.PropertyChanged += this.GridContainer_PropertyChanged;
}
else {
this.CurrentGrid = GridContainer.EmptyGridContainer;
}
this.ResetBoundingArea();
}
private void ResetMaximumTile() {
this.MaximumTile = this.HasActiveTiles() ? this.GetMaximumTile() : Point.Zero;
this._boundingArea.Reset();
}
private void ResetMinimumTile() {
this.MinimumTile = this.HasActiveTiles() ? this.GetMinimumTile() : Point.Zero;
this._boundingArea.Reset();
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Trionic5Tools
{
/// <summary>
/// </summary>
abstract public class IECUProperties
{
/// <summary>
/// </summary>
public abstract bool Afterstartenrichment
{
get;
set;
}
public abstract bool HasVSSOptions
{
get;
set;
}
public abstract bool ExtendedProgramModeOptions
{
get;
set;
}
public abstract InjectorType InjectorType
{
get;
set;
}
public abstract MapSensorType MapSensorType
{
get;
set;
}
public abstract TurboType TurboType
{
get;
set;
}
public abstract TuningStage TuningStage
{
get;
set;
}
public abstract DateTime SyncDateTime
{
get;
set;
}
public abstract bool WOTenrichment
{
get;
set;
}
public abstract bool Interpolationofdelay
{
get;
set;
}
public abstract bool Temperaturecompensation
{
get;
set;
}
public abstract bool Lambdacontrol
{
get;
set;
}
public abstract bool Adaptivity
{
get;
set;
}
public abstract bool Idlecontrol
{
get;
set;
}
public abstract bool Enrichmentduringstart
{
get;
set;
}
public abstract bool ConstantinjectiontimeE51
{
get;
set;
}
public abstract bool Lambdacontrolduringtransients
{
get;
set;
}
public abstract bool Fuelcut
{
get;
set;
}
public abstract bool Constantinjtimeduringidle
{
get;
set;
}
public abstract bool Accelerationsenrichment
{
get;
set;
}
public abstract bool Decelerationsenleanment
{
get;
set;
}
public abstract bool Car104
{
get;
set;
}
public abstract bool Adaptivitywithclosedthrottle
{
get;
set;
}
public abstract bool Factortolambdawhenthrottleopening
{
get;
set;
}
public abstract bool Usesseparateinjmapduringidle
{
get;
set;
}
public abstract bool FactortolambdawhenACisengaged
{
get;
set;
}
public abstract bool ThrottleAccRetadjustsimultMY95
{
get;
set;
}
public abstract bool Fueladjustingduringidle
{
get;
set;
}
public abstract bool Purge
{
get;
set;
}
public abstract bool Adaptionofidlecontrol
{
get;
set;
}
public abstract bool Lambdacontrolduringidle
{
get;
set;
}
public abstract bool Heatedplates
{
get;
set;
}
public abstract bool AutomaticTransmission
{
get;
set;
}
public abstract bool Loadcontrol
{
get;
set;
}
public abstract bool ETS
{
get;
set;
}
public abstract bool APCcontrol
{
get;
set;
}
public abstract bool Higheridleduringstart
{
get;
set;
}
public abstract bool Globaladaption
{
get;
set;
}
public abstract bool Tempcompwithactivelambdacontrol
{
get;
set;
}
public abstract bool Loadbufferduringidle
{
get;
set;
}
public abstract bool Constidleignangleduringgearoneandtwo
{
get;
set;
}
public abstract bool NofuelcutR12
{
get;
set;
}
public abstract bool Airpumpcontrol
{
get;
set;
}
public abstract bool Normalasperatedengine
{
get;
set;
}
public abstract bool Knockregulatingdisabled
{
get;
set;
}
public abstract bool Constantangle
{
get;
set;
}
public abstract bool PurgevalveMY94
{
get;
set;
}
public abstract string VSSCode
{
get;
set;
}
public abstract bool VSSactive
{
get;
set;
}
public abstract string Carmodel
{
get;
set;
}
public abstract string Enginetype
{
get;
set;
}
public abstract string Partnumber
{
get;
set;
}
public abstract string SoftwareID
{
get;
set;
}
public abstract string Dataname
{
get;
set;
}
public abstract string CPUspeed
{
get;
set;
}
public abstract bool RAMlocked
{
get;
set;
}
public abstract bool IsTrionic55
{
get;
set;
}
public abstract bool SecondO2Enable
{
get;
set;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id$")]
namespace Elmah
{
#region Imports
using System;
using System.Collections.Specialized;
using System.IO;
using System.Threading;
using System.Web;
using System.Xml;
using XmlReader = System.Xml.XmlReader;
using XmlWriter = System.Xml.XmlWriter;
using Thread = System.Threading.Thread;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
using XmlConvert = System.Xml.XmlConvert;
using WriteState = System.Xml.WriteState;
#endregion
/// <summary>
/// Responsible for primarily encoding the JSON representation of
/// <see cref="Error"/> objects.
/// </summary>
[ Serializable ]
public sealed class ErrorJson
{
/// <summary>
/// Encodes the default JSON representation of an <see cref="Error"/>
/// object to a string.
/// </summary>
/// <remarks>
/// Only properties and collection entires with non-null
/// and non-empty strings are emitted.
/// </remarks>
public static string EncodeString(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
StringWriter writer = new StringWriter();
Encode(error, writer);
return writer.ToString();
}
/// <summary>
/// Encodes the default JSON representation of an <see cref="Error"/>
/// object to a <see cref="TextWriter" />.
/// </summary>
/// <remarks>
/// Only properties and collection entires with non-null
/// and non-empty strings are emitted.
/// </remarks>
public static void Encode(Error error, TextWriter writer)
{
if (error == null)
throw new ArgumentNullException("error");
if (writer == null)
throw new ArgumentNullException("writer");
EncodeEnclosed(error, new JsonTextWriter(writer));
}
private static void EncodeEnclosed(Error error, JsonTextWriter writer)
{
Debug.Assert(error != null);
Debug.Assert(writer != null);
writer.Object();
Encode(error, writer);
writer.Pop();
}
internal static void Encode(Error error, JsonTextWriter writer)
{
Debug.Assert(error != null);
Debug.Assert(writer != null);
Member(writer, "application", error.ApplicationName);
Member(writer, "host", error.HostName);
Member(writer, "type", error.Type);
Member(writer, "message", error.Message);
Member(writer, "source", error.Source);
Member(writer, "detail", error.Detail);
Member(writer, "user", error.User);
Member(writer, "time", error.Time, DateTime.MinValue);
Member(writer, "statusCode", error.StatusCode, 0);
Member(writer, "webHostHtmlMessage", error.WebHostHtmlMessage);
Member(writer, "serverVariables", error.ServerVariables);
Member(writer, "queryString", error.QueryString);
Member(writer, "form", error.Form);
Member(writer, "cookies", error.Cookies);
}
private static void Member(JsonTextWriter writer, string name, int value, int defaultValue)
{
if (value == defaultValue)
return;
writer.Member(name).Number(value);
}
private static void Member(JsonTextWriter writer, string name, DateTime value, DateTime defaultValue)
{
if (value == defaultValue)
return;
writer.Member(name).String(value);
}
private static void Member(JsonTextWriter writer, string name, string value)
{
Debug.Assert(writer != null);
Debug.AssertStringNotEmpty(name);
if (value == null || value.Length == 0)
return;
writer.Member(name).String(value);
}
private static void Member(JsonTextWriter writer, string name, NameValueCollection collection)
{
Debug.Assert(writer != null);
Debug.AssertStringNotEmpty(name);
//
// Bail out early if the collection is null or empty.
//
if (collection == null || collection.Count == 0)
return;
//
// Save the depth, which we'll use to lazily emit the collection.
// That is, if we find that there is nothing useful in it, then
// we could simply avoid emitting anything.
//
int depth = writer.Depth;
//
// For each key, we get all associated values and loop through
// twice. The first time round, we count strings that are
// neither null nor empty. If none are found then the key is
// skipped. Otherwise, second time round, we encode
// strings that are neither null nor empty. If only such string
// exists for a key then it is written directly, otherwise
// multiple strings are naturally wrapped in an array.
//
foreach (string key in collection.Keys)
{
string[] values = collection.GetValues(key);
if (values == null || values.Length == 0)
continue;
int count = 0; // Strings neither null nor empty.
for (int i = 0; i < values.Length; i++)
{
string value = values[i];
if (value != null && value.Length > 0)
count++;
}
if (count == 0) // None?
continue; // Skip key
//
// There is at least one value so now we emit the key.
// Before doing that, we check if the collection member
// was ever started. If not, this would be a good time.
//
if (depth == writer.Depth)
{
writer.Member(name);
writer.Object();
}
writer.Member(key);
if (count > 1)
writer.Array(); // Wrap multiples in an array
for (int i = 0; i < values.Length; i++)
{
string value = values[i];
if (value != null && value.Length > 0)
writer.String(value);
}
if (count > 1)
writer.Pop(); // Close multiples array
}
//
// If we are deeper than when we began then the collection was
// started so we terminate it here.
//
if (writer.Depth > depth)
writer.Pop();
}
private ErrorJson()
{
throw new NotSupportedException();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
namespace CCVersions
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.GroupBox groupProjects;
System.Windows.Forms.GroupBox groupSources;
System.Windows.Forms.Label label3;
System.Windows.Forms.Label label1;
System.Windows.Forms.Label label2;
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea2 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea3 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea4 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea5 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
System.Windows.Forms.DataVisualization.Charting.Legend legend2 = new System.Windows.Forms.DataVisualization.Charting.Legend();
System.Windows.Forms.DataVisualization.Charting.Legend legend3 = new System.Windows.Forms.DataVisualization.Charting.Legend();
System.Windows.Forms.DataVisualization.Charting.Legend legend4 = new System.Windows.Forms.DataVisualization.Charting.Legend();
System.Windows.Forms.DataVisualization.Charting.Legend legend5 = new System.Windows.Forms.DataVisualization.Charting.Legend();
System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series3 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series4 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series5 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series6 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series7 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series8 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series9 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series10 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series11 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series12 = new System.Windows.Forms.DataVisualization.Charting.Series();
this.listProjects = new System.Windows.Forms.ListBox();
this.listSources = new System.Windows.Forms.ListBox();
this.backgroundEnumerateVersions = new System.ComponentModel.BackgroundWorker();
this.splitMain = new System.Windows.Forms.SplitContainer();
this.tableLayoutPanelLeft = new System.Windows.Forms.TableLayoutPanel();
this.panel1 = new System.Windows.Forms.Panel();
this.buttonCharts = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.progressEnumerateVersions = new System.Windows.Forms.ProgressBar();
this.labelStatus = new System.Windows.Forms.Label();
this.textFirstVersion = new System.Windows.Forms.TextBox();
this.textLastVersion = new System.Windows.Forms.TextBox();
this.buttonDoIt = new System.Windows.Forms.Button();
this.labelVersion = new System.Windows.Forms.Label();
this.versionsGroup = new System.Windows.Forms.GroupBox();
this.label4 = new System.Windows.Forms.Label();
this.versionFilterBox = new System.Windows.Forms.TextBox();
this.listVersions = new System.Windows.Forms.ListBox();
this.splitRight = new System.Windows.Forms.SplitContainer();
this.splitTopRight = new System.Windows.Forms.SplitContainer();
this.groupAssemblies = new System.Windows.Forms.GroupBox();
this.listAssemblies = new System.Windows.Forms.ListBox();
this.groupChartTypes = new System.Windows.Forms.GroupBox();
this.listChartTypes = new System.Windows.Forms.ListBox();
this.chart = new System.Windows.Forms.DataVisualization.Charting.Chart();
this.GetVersionsButton = new System.Windows.Forms.Button();
groupProjects = new System.Windows.Forms.GroupBox();
groupSources = new System.Windows.Forms.GroupBox();
label3 = new System.Windows.Forms.Label();
label1 = new System.Windows.Forms.Label();
label2 = new System.Windows.Forms.Label();
groupProjects.SuspendLayout();
groupSources.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitMain)).BeginInit();
this.splitMain.Panel1.SuspendLayout();
this.splitMain.Panel2.SuspendLayout();
this.splitMain.SuspendLayout();
this.tableLayoutPanelLeft.SuspendLayout();
this.panel1.SuspendLayout();
this.versionsGroup.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitRight)).BeginInit();
this.splitRight.Panel1.SuspendLayout();
this.splitRight.Panel2.SuspendLayout();
this.splitRight.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitTopRight)).BeginInit();
this.splitTopRight.Panel1.SuspendLayout();
this.splitTopRight.Panel2.SuspendLayout();
this.splitTopRight.SuspendLayout();
this.groupAssemblies.SuspendLayout();
this.groupChartTypes.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.chart)).BeginInit();
this.SuspendLayout();
//
// groupProjects
//
groupProjects.Controls.Add(this.listProjects);
groupProjects.Dock = System.Windows.Forms.DockStyle.Fill;
groupProjects.Location = new System.Drawing.Point(3, 148);
groupProjects.Name = "groupProjects";
groupProjects.Size = new System.Drawing.Size(544, 140);
groupProjects.TabIndex = 2;
groupProjects.TabStop = false;
groupProjects.Text = "Projects/Solutions";
//
// listProjects
//
this.listProjects.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listProjects.DisplayMember = "Id";
this.listProjects.FormattingEnabled = true;
this.listProjects.IntegralHeight = false;
this.listProjects.Location = new System.Drawing.Point(9, 19);
this.listProjects.Name = "listProjects";
this.listProjects.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.listProjects.Size = new System.Drawing.Size(526, 115);
this.listProjects.TabIndex = 2;
this.listProjects.ValueMember = "Id";
this.listProjects.SelectedIndexChanged += new System.EventHandler(this.listProjects_SelectedIndexChanged);
//
// groupSources
//
groupSources.Controls.Add(this.listSources);
groupSources.Dock = System.Windows.Forms.DockStyle.Fill;
groupSources.Location = new System.Drawing.Point(3, 3);
groupSources.Name = "groupSources";
groupSources.Size = new System.Drawing.Size(544, 139);
groupSources.TabIndex = 1;
groupSources.TabStop = false;
groupSources.Text = "Sources";
//
// listSources
//
this.listSources.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listSources.DisplayMember = "Id";
this.listSources.FormattingEnabled = true;
this.listSources.IntegralHeight = false;
this.listSources.Location = new System.Drawing.Point(9, 19);
this.listSources.Name = "listSources";
this.listSources.Size = new System.Drawing.Size(526, 114);
this.listSources.TabIndex = 1;
this.listSources.ValueMember = "Id";
this.listSources.SelectedIndexChanged += new System.EventHandler(this.listSources_SelectedIndexChanged);
//
// label3
//
label3.AutoSize = true;
label3.Location = new System.Drawing.Point(9, 44);
label3.Name = "label3";
label3.Size = new System.Drawing.Size(45, 13);
label3.TabIndex = 26;
label3.Text = "Version:";
//
// label1
//
label1.AutoSize = true;
label1.Location = new System.Drawing.Point(6, 15);
label1.Name = "label1";
label1.Size = new System.Drawing.Size(67, 13);
label1.TabIndex = 23;
label1.Text = "From version";
//
// label2
//
label2.AutoSize = true;
label2.Location = new System.Drawing.Point(240, 15);
label2.Name = "label2";
label2.Size = new System.Drawing.Size(16, 13);
label2.TabIndex = 21;
label2.Text = "to";
//
// backgroundEnumerateVersions
//
this.backgroundEnumerateVersions.WorkerReportsProgress = true;
this.backgroundEnumerateVersions.WorkerSupportsCancellation = true;
this.backgroundEnumerateVersions.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundEnumerateVersions_DoWork);
this.backgroundEnumerateVersions.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundEnumerateVersions_ProgressChanged);
this.backgroundEnumerateVersions.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundEnumerateVersions_RunWorkerCompleted);
//
// splitMain
//
this.splitMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitMain.Location = new System.Drawing.Point(0, 0);
this.splitMain.Name = "splitMain";
//
// splitMain.Panel1
//
this.splitMain.Panel1.Controls.Add(this.tableLayoutPanelLeft);
this.splitMain.Panel1MinSize = 550;
//
// splitMain.Panel2
//
this.splitMain.Panel2.Controls.Add(this.splitRight);
this.splitMain.Panel2MinSize = 100;
this.splitMain.Size = new System.Drawing.Size(1396, 809);
this.splitMain.SplitterDistance = 550;
this.splitMain.TabIndex = 0;
//
// tableLayoutPanelLeft
//
this.tableLayoutPanelLeft.ColumnCount = 1;
this.tableLayoutPanelLeft.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanelLeft.Controls.Add(groupProjects, 0, 1);
this.tableLayoutPanelLeft.Controls.Add(groupSources, 0, 0);
this.tableLayoutPanelLeft.Controls.Add(this.panel1, 0, 3);
this.tableLayoutPanelLeft.Controls.Add(this.versionsGroup, 0, 2);
this.tableLayoutPanelLeft.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanelLeft.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanelLeft.Name = "tableLayoutPanelLeft";
this.tableLayoutPanelLeft.RowCount = 4;
this.tableLayoutPanelLeft.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 22.01151F));
this.tableLayoutPanelLeft.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 22.28242F));
this.tableLayoutPanelLeft.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 55.70606F));
this.tableLayoutPanelLeft.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 150F));
this.tableLayoutPanelLeft.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanelLeft.Size = new System.Drawing.Size(550, 809);
this.tableLayoutPanelLeft.TabIndex = 1;
//
// panel1
//
this.panel1.Controls.Add(this.buttonCharts);
this.panel1.Controls.Add(this.buttonCancel);
this.panel1.Controls.Add(label3);
this.panel1.Controls.Add(this.progressEnumerateVersions);
this.panel1.Controls.Add(this.labelStatus);
this.panel1.Controls.Add(label1);
this.panel1.Controls.Add(this.textFirstVersion);
this.panel1.Controls.Add(label2);
this.panel1.Controls.Add(this.textLastVersion);
this.panel1.Controls.Add(this.buttonDoIt);
this.panel1.Controls.Add(this.labelVersion);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(3, 661);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(544, 145);
this.panel1.TabIndex = 3;
//
// buttonCharts
//
this.buttonCharts.Location = new System.Drawing.Point(444, 68);
this.buttonCharts.Name = "buttonCharts";
this.buttonCharts.Size = new System.Drawing.Size(75, 23);
this.buttonCharts.TabIndex = 7;
this.buttonCharts.Text = "Charts";
this.buttonCharts.UseVisualStyleBackColor = true;
this.buttonCharts.Click += new System.EventHandler(this.buttonCharts_Click);
//
// buttonCancel
//
this.buttonCancel.Enabled = false;
this.buttonCancel.Location = new System.Drawing.Point(444, 39);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// progressEnumerateVersions
//
this.progressEnumerateVersions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressEnumerateVersions.Location = new System.Drawing.Point(9, 108);
this.progressEnumerateVersions.Name = "progressEnumerateVersions";
this.progressEnumerateVersions.Size = new System.Drawing.Size(526, 23);
this.progressEnumerateVersions.TabIndex = 8;
//
// labelStatus
//
this.labelStatus.AutoSize = true;
this.labelStatus.Location = new System.Drawing.Point(73, 68);
this.labelStatus.Name = "labelStatus";
this.labelStatus.Size = new System.Drawing.Size(0, 13);
this.labelStatus.TabIndex = 24;
//
// textFirstVersion
//
this.textFirstVersion.Location = new System.Drawing.Point(76, 12);
this.textFirstVersion.Name = "textFirstVersion";
this.textFirstVersion.Size = new System.Drawing.Size(143, 20);
this.textFirstVersion.TabIndex = 3;
//
// textLastVersion
//
this.textLastVersion.Location = new System.Drawing.Point(272, 12);
this.textLastVersion.Name = "textLastVersion";
this.textLastVersion.Size = new System.Drawing.Size(143, 20);
this.textLastVersion.TabIndex = 4;
//
// buttonDoIt
//
this.buttonDoIt.Location = new System.Drawing.Point(444, 10);
this.buttonDoIt.Name = "buttonDoIt";
this.buttonDoIt.Size = new System.Drawing.Size(75, 23);
this.buttonDoIt.TabIndex = 5;
this.buttonDoIt.Text = "Do it!";
this.buttonDoIt.UseVisualStyleBackColor = true;
this.buttonDoIt.Click += new System.EventHandler(this.buttonDoIt_Click);
//
// labelVersion
//
this.labelVersion.AutoSize = true;
this.labelVersion.Location = new System.Drawing.Point(73, 44);
this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(0, 13);
this.labelVersion.TabIndex = 18;
//
// versionsGroup
//
this.versionsGroup.Controls.Add(this.GetVersionsButton);
this.versionsGroup.Controls.Add(this.label4);
this.versionsGroup.Controls.Add(this.versionFilterBox);
this.versionsGroup.Controls.Add(this.listVersions);
this.versionsGroup.Location = new System.Drawing.Point(3, 294);
this.versionsGroup.Name = "versionsGroup";
this.versionsGroup.Size = new System.Drawing.Size(544, 361);
this.versionsGroup.TabIndex = 4;
this.versionsGroup.TabStop = false;
this.versionsGroup.Text = "Versions";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(14, 23);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(29, 13);
this.label4.TabIndex = 2;
this.label4.Text = "Filter";
//
// versionFilterBox
//
this.versionFilterBox.Location = new System.Drawing.Point(49, 20);
this.versionFilterBox.Name = "versionFilterBox";
this.versionFilterBox.Size = new System.Drawing.Size(276, 20);
this.versionFilterBox.TabIndex = 1;
//
// listVersions
//
this.listVersions.FormattingEnabled = true;
this.listVersions.Location = new System.Drawing.Point(12, 45);
this.listVersions.Name = "listVersions";
this.listVersions.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this.listVersions.Size = new System.Drawing.Size(523, 303);
this.listVersions.TabIndex = 0;
this.listVersions.SelectedIndexChanged += new System.EventHandler(this.listVersions_SelectedIndexChanged);
//
// splitRight
//
this.splitRight.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitRight.Location = new System.Drawing.Point(0, 0);
this.splitRight.Name = "splitRight";
this.splitRight.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitRight.Panel1
//
this.splitRight.Panel1.Controls.Add(this.splitTopRight);
this.splitRight.Panel1.Padding = new System.Windows.Forms.Padding(0, 0, 4, 0);
//
// splitRight.Panel2
//
this.splitRight.Panel2.Controls.Add(this.chart);
this.splitRight.Size = new System.Drawing.Size(842, 809);
this.splitRight.SplitterDistance = 164;
this.splitRight.TabIndex = 9;
//
// splitTopRight
//
this.splitTopRight.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitTopRight.Location = new System.Drawing.Point(0, 0);
this.splitTopRight.Name = "splitTopRight";
//
// splitTopRight.Panel1
//
this.splitTopRight.Panel1.Controls.Add(this.groupAssemblies);
this.splitTopRight.Panel1MinSize = 50;
//
// splitTopRight.Panel2
//
this.splitTopRight.Panel2.Controls.Add(this.groupChartTypes);
this.splitTopRight.Panel2MinSize = 50;
this.splitTopRight.Size = new System.Drawing.Size(838, 164);
this.splitTopRight.SplitterDistance = 426;
this.splitTopRight.TabIndex = 10;
//
// groupAssemblies
//
this.groupAssemblies.Controls.Add(this.listAssemblies);
this.groupAssemblies.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupAssemblies.Location = new System.Drawing.Point(0, 0);
this.groupAssemblies.Name = "groupAssemblies";
this.groupAssemblies.Size = new System.Drawing.Size(426, 164);
this.groupAssemblies.TabIndex = 11;
this.groupAssemblies.TabStop = false;
this.groupAssemblies.Text = "Assemblies";
//
// listAssemblies
//
this.listAssemblies.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listAssemblies.DisplayMember = "AssemblyName";
this.listAssemblies.FormattingEnabled = true;
this.listAssemblies.IntegralHeight = false;
this.listAssemblies.Location = new System.Drawing.Point(6, 22);
this.listAssemblies.Name = "listAssemblies";
this.listAssemblies.Size = new System.Drawing.Size(414, 139);
this.listAssemblies.TabIndex = 11;
this.listAssemblies.ValueMember = "FileName";
this.listAssemblies.SelectedIndexChanged += new System.EventHandler(this.listAssemblies_SelectedIndexChanged);
//
// groupChartTypes
//
this.groupChartTypes.Controls.Add(this.listChartTypes);
this.groupChartTypes.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupChartTypes.Location = new System.Drawing.Point(0, 0);
this.groupChartTypes.Name = "groupChartTypes";
this.groupChartTypes.Size = new System.Drawing.Size(408, 164);
this.groupChartTypes.TabIndex = 12;
this.groupChartTypes.TabStop = false;
this.groupChartTypes.Text = "Chart Types";
//
// listChartTypes
//
this.listChartTypes.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listChartTypes.FormattingEnabled = true;
this.listChartTypes.IntegralHeight = false;
this.listChartTypes.Items.AddRange(new object[] {
"Ok, filtered, warnings",
"Contracts",
"Contracts per method",
"Contract density",
"Ok, filtered, warnings (normalized)"});
this.listChartTypes.Location = new System.Drawing.Point(6, 22);
this.listChartTypes.Name = "listChartTypes";
this.listChartTypes.Size = new System.Drawing.Size(396, 139);
this.listChartTypes.TabIndex = 12;
this.listChartTypes.SelectedIndexChanged += new System.EventHandler(this.listChartTypes_SelectedIndexChanged);
//
// chart
//
chartArea1.AxisX.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea1.AxisY.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea1.AxisY2.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea1.AxisY2.MajorGrid.Enabled = false;
chartArea1.Name = "Stacked3";
chartArea2.AxisX.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea2.AxisY.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea2.AxisY2.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea2.AxisY2.MajorGrid.Enabled = false;
chartArea2.Name = "Contracts";
chartArea3.AxisX.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea3.AxisY.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea3.AxisY2.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea3.AxisY2.MajorGrid.Enabled = false;
chartArea3.Name = "ContractsPerMethod";
chartArea4.AxisX.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea4.AxisX2.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea4.AxisX2.MajorGrid.Enabled = false;
chartArea4.AxisY.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea4.AxisY2.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea4.AxisY2.MajorGrid.Enabled = false;
chartArea4.Name = "ContractDensity";
chartArea5.AxisX.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea5.AxisY.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea5.AxisY2.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartArea5.AxisY2.MajorGrid.Enabled = false;
chartArea5.Name = "Stacked3norm";
this.chart.ChartAreas.Add(chartArea1);
this.chart.ChartAreas.Add(chartArea2);
this.chart.ChartAreas.Add(chartArea3);
this.chart.ChartAreas.Add(chartArea4);
this.chart.ChartAreas.Add(chartArea5);
this.chart.Dock = System.Windows.Forms.DockStyle.Fill;
legend1.Alignment = System.Drawing.StringAlignment.Center;
legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
legend1.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Row;
legend1.Name = "Stacked3";
legend2.Alignment = System.Drawing.StringAlignment.Center;
legend2.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
legend2.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Row;
legend2.Name = "Contracts";
legend3.Alignment = System.Drawing.StringAlignment.Center;
legend3.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
legend3.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Row;
legend3.Name = "ContractsPerMethod";
legend4.Alignment = System.Drawing.StringAlignment.Center;
legend4.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
legend4.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Row;
legend4.Name = "ContractDensity";
legend5.Alignment = System.Drawing.StringAlignment.Center;
legend5.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
legend5.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Row;
legend5.Name = "Stacked3norm";
this.chart.Legends.Add(legend1);
this.chart.Legends.Add(legend2);
this.chart.Legends.Add(legend3);
this.chart.Legends.Add(legend4);
this.chart.Legends.Add(legend5);
this.chart.Location = new System.Drawing.Point(0, 0);
this.chart.Name = "chart";
series1.ChartArea = "Stacked3";
series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.StackedColumn;
series1.CustomProperties = "PointWidth=1";
series1.IsXValueIndexed = true;
series1.Legend = "Stacked3";
series1.LegendText = "OK";
series1.Name = "Stacked3_StatsTrue";
series1.XValueMember = "Version";
series1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int64;
series1.YValueMembers = "StatsTrue";
series1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
series2.ChartArea = "Stacked3";
series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.StackedColumn;
series2.CustomProperties = "PointWidth=1";
series2.IsXValueIndexed = true;
series2.Legend = "Stacked3";
series2.LegendText = "Filtered";
series2.Name = "Stacked3_SwallowedWarnings";
series2.XValueMember = "Version";
series2.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int64;
series2.YValueMembers = "SwallowedWarnings";
series2.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
series3.ChartArea = "Stacked3";
series3.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.StackedColumn;
series3.CustomProperties = "PointWidth=1";
series3.IsXValueIndexed = true;
series3.Legend = "Stacked3";
series3.LegendText = "Warnings";
series3.Name = "Stacked3_DisplayedWarnings";
series3.XValueMember = "Version";
series3.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int64;
series3.YValueMembers = "DisplayedWarnings";
series3.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
series4.BorderWidth = 3;
series4.ChartArea = "Stacked3";
series4.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
series4.Color = System.Drawing.Color.SteelBlue;
series4.IsXValueIndexed = true;
series4.Legend = "Stacked3";
series4.LegendText = "Methods";
series4.Name = "Stacked3_Methods";
series4.XValueMember = "Version";
series4.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
series4.YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary;
series4.YValueMembers = "Methods";
series5.BorderWidth = 3;
series5.ChartArea = "ContractsPerMethod";
series5.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
series5.Color = System.Drawing.Color.SteelBlue;
series5.IsXValueIndexed = true;
series5.Legend = "ContractsPerMethod";
series5.LegendText = "Methods";
series5.Name = "ContractsPerMethod_Methods";
series5.XValueMember = "Version";
series5.YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary;
series5.YValueMembers = "Methods";
series6.BorderWidth = 3;
series6.ChartArea = "ContractsPerMethod";
series6.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
series6.Color = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
series6.IsXValueIndexed = true;
series6.Legend = "ContractsPerMethod";
series6.LegendText = "Contracts per method";
series6.Name = "ContractsPerMethod";
series6.XValueMember = "Version";
series6.YValueMembers = "ContractsPerMethod";
series7.BorderWidth = 3;
series7.ChartArea = "Contracts";
series7.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
series7.Color = System.Drawing.Color.SteelBlue;
series7.IsXValueIndexed = true;
series7.Legend = "Contracts";
series7.LegendText = "Methods";
series7.Name = "Contracts_Methods";
series7.XValueMember = "Version";
series7.YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary;
series7.YValueMembers = "Methods";
series8.BorderWidth = 3;
series8.ChartArea = "Contracts";
series8.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
series8.Color = System.Drawing.Color.SeaGreen;
series8.IsXValueIndexed = true;
series8.Legend = "Contracts";
series8.LegendText = "Contracts";
series8.Name = "Contracts_Contracts";
series8.XValueMember = "Version";
series8.YValueMembers = "Contracts";
series9.BorderWidth = 3;
series9.ChartArea = "ContractDensity";
series9.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
series9.Color = System.Drawing.Color.SaddleBrown;
series9.IsXValueIndexed = true;
series9.Legend = "ContractDensity";
series9.LegendText = "Contract density";
series9.Name = "ContractDensity";
series9.XValueMember = "Version";
series9.YValueMembers = "ContractDensity";
series10.ChartArea = "Stacked3norm";
series10.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.StackedColumn100;
series10.Color = System.Drawing.Color.DodgerBlue;
series10.CustomProperties = "PointWidth=1";
series10.IsXValueIndexed = true;
series10.Legend = "Stacked3norm";
series10.LegendText = "OK";
series10.Name = "Stacked3norm_StatsTrue";
series10.XValueMember = "Version";
series10.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int64;
series10.YValueMembers = "StatsTrue";
series10.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
series11.ChartArea = "Stacked3norm";
series11.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.StackedColumn100;
series11.Color = System.Drawing.Color.Orange;
series11.CustomProperties = "PointWidth=1";
series11.IsXValueIndexed = true;
series11.Legend = "Stacked3norm";
series11.LegendText = "Filtered";
series11.Name = "Stacked3norm_SwallowedWarnings";
series11.XValueMember = "Version";
series11.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int64;
series11.YValueMembers = "SwallowedWarnings";
series11.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
series12.ChartArea = "Stacked3norm";
series12.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.StackedColumn100;
series12.Color = System.Drawing.Color.OrangeRed;
series12.CustomProperties = "PointWidth=1";
series12.IsXValueIndexed = true;
series12.Legend = "Stacked3norm";
series12.LegendText = "Warnings";
series12.Name = "Stacked3norm_DisplayedWarnings";
series12.XValueMember = "Version";
series12.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int64;
series12.YValueMembers = "DisplayedWarnings";
series12.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
this.chart.Series.Add(series1);
this.chart.Series.Add(series2);
this.chart.Series.Add(series3);
this.chart.Series.Add(series4);
this.chart.Series.Add(series5);
this.chart.Series.Add(series6);
this.chart.Series.Add(series7);
this.chart.Series.Add(series8);
this.chart.Series.Add(series9);
this.chart.Series.Add(series10);
this.chart.Series.Add(series11);
this.chart.Series.Add(series12);
this.chart.Size = new System.Drawing.Size(842, 641);
this.chart.TabIndex = 13;
//
// GetVersionsButton
//
this.GetVersionsButton.Location = new System.Drawing.Point(331, 17);
this.GetVersionsButton.Name = "GetVersionsButton";
this.GetVersionsButton.Size = new System.Drawing.Size(75, 23);
this.GetVersionsButton.TabIndex = 3;
this.GetVersionsButton.Text = "Get Versions";
this.GetVersionsButton.UseVisualStyleBackColor = true;
this.GetVersionsButton.Click += new System.EventHandler(this.GetVersionsButton_Click);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1396, 809);
this.Controls.Add(this.splitMain);
this.MinimumSize = new System.Drawing.Size(600, 300);
this.Name = "MainForm";
this.Text = "CCVersions";
this.Load += new System.EventHandler(this.MainForm_Load);
groupProjects.ResumeLayout(false);
groupSources.ResumeLayout(false);
this.splitMain.Panel1.ResumeLayout(false);
this.splitMain.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitMain)).EndInit();
this.splitMain.ResumeLayout(false);
this.tableLayoutPanelLeft.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.versionsGroup.ResumeLayout(false);
this.versionsGroup.PerformLayout();
this.splitRight.Panel1.ResumeLayout(false);
this.splitRight.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitRight)).EndInit();
this.splitRight.ResumeLayout(false);
this.splitTopRight.Panel1.ResumeLayout(false);
this.splitTopRight.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitTopRight)).EndInit();
this.splitTopRight.ResumeLayout(false);
this.groupAssemblies.ResumeLayout(false);
this.groupChartTypes.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.chart)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.ComponentModel.BackgroundWorker backgroundEnumerateVersions;
private System.Windows.Forms.SplitContainer splitMain;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelLeft;
private System.Windows.Forms.ListBox listProjects;
private System.Windows.Forms.ListBox listSources;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.ProgressBar progressEnumerateVersions;
private System.Windows.Forms.Label labelStatus;
private System.Windows.Forms.TextBox textFirstVersion;
private System.Windows.Forms.TextBox textLastVersion;
private System.Windows.Forms.Button buttonDoIt;
private System.Windows.Forms.Label labelVersion;
private System.Windows.Forms.SplitContainer splitRight;
private System.Windows.Forms.Button buttonCharts;
private System.Windows.Forms.DataVisualization.Charting.Chart chart;
private System.Windows.Forms.SplitContainer splitTopRight;
private System.Windows.Forms.GroupBox groupAssemblies;
private System.Windows.Forms.ListBox listAssemblies;
private System.Windows.Forms.GroupBox groupChartTypes;
private System.Windows.Forms.ListBox listChartTypes;
private System.Windows.Forms.GroupBox versionsGroup;
private System.Windows.Forms.ListBox listVersions;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox versionFilterBox;
private System.Windows.Forms.Button GetVersionsButton;
}
}
| |
//
// Client.cs
//
// Author:
// Scott Thomas <[email protected]>
//
// Copyright (C) 2008 S&S Black Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Ssdp;
using Mono.Upnp.Internal;
using Mono.Upnp.Xml;
namespace Mono.Upnp
{
public class Client : IDisposable
{
static WeakReference static_deserializer = new WeakReference (null);
readonly Dictionary<DeviceAnnouncement, DeviceAnnouncement> devices =
new Dictionary<DeviceAnnouncement, DeviceAnnouncement> ();
readonly Dictionary<ServiceAnnouncement, ServiceAnnouncement> services =
new Dictionary<ServiceAnnouncement, ServiceAnnouncement> ();
readonly Dictionary<string, Root> descriptions =
new Dictionary<string, Root> ();
readonly Mono.Ssdp.Client client = new Mono.Ssdp.Client ();
DeserializerProducer deserializer_producer;
public Client ()
: this (null)
{
}
public Client (DeserializerProducer deserializerProducer)
{
DeserializerProducer = deserializerProducer ?? (xmlDeserializer => new Deserializer (xmlDeserializer));
client.ServiceAdded += ClientServiceAdded;
client.ServiceRemoved += ClientServiceRemoved;
}
public DeserializerProducer DeserializerProducer {
get { return deserializer_producer; }
set {
if (value == null) {
throw new ArgumentNullException ("value");
}
deserializer_producer = value;
}
}
public event EventHandler<DeviceEventArgs> DeviceAdded;
public event EventHandler<DeviceEventArgs> DeviceRemoved;
public event EventHandler<ServiceEventArgs> ServiceAdded;
public event EventHandler<ServiceEventArgs> ServiceRemoved;
public void BrowseRoots ()
{
client.Browse ("upnp:rootdevice");
}
public void BrowseAll ()
{
client.BrowseAll ();
}
public void Browse (TypeInfo type)
{
client.Browse (type.ToString ());
}
void ClientServiceAdded (object sender, Mono.Ssdp.ServiceArgs args)
{
ClientServiceEvent (args,
(device) => {
if (!devices.ContainsKey (device)) {
OnDeviceAdded (new DeviceEventArgs (device, UpnpOperation.Added));
devices.Add (device, device);
}
},
(service) => {
if (!services.ContainsKey (service)) {
OnServiceAdded (new ServiceEventArgs (service, UpnpOperation.Added));
services.Add (service, service);
}
}
);
}
void ClientServiceRemoved (object sender, Mono.Ssdp.ServiceArgs args)
{
ClientServiceEvent (args,
(device) => {
if (devices.ContainsKey (device)) {
device.Dispose ();
OnDeviceRemoved (new DeviceEventArgs (device, UpnpOperation.Removed));
devices.Remove (device);
}
},
(service) => {
if (services.ContainsKey (service)) {
service.Dispose ();
OnServiceRemoved (new ServiceEventArgs (service, UpnpOperation.Removed));
services.Remove (service);
}
}
);
}
void ClientServiceEvent (Mono.Ssdp.ServiceArgs args,
Action<DeviceAnnouncement> deviceHandler,
Action<ServiceAnnouncement> serviceHandler)
{
if (!args.Usn.StartsWith ("uuid:")) {
return;
}
var colon = args.Usn.IndexOf (':', 5);
var usn = colon == -1 ? args.Usn : args.Usn.Substring (0, colon);
var suffix = colon == -1 ? args.Usn : args.Usn.Substring (colon + 2);
var service_type = args.Service == null ? suffix : args.Service.ServiceType;
var locations = args.Service == null ? null : args.Service.Locations;
if (args.Usn.Contains (":device:")) {
var type = DeviceType.Parse (service_type);
var device = new DeviceAnnouncement (this, type, usn, locations);
deviceHandler (device);
} else if (args.Usn.Contains (":service:")) {
var type = ServiceType.Parse (service_type);
var service = new ServiceAnnouncement (this, type, usn, locations);
serviceHandler (service);
}
}
protected virtual void OnDeviceAdded (DeviceEventArgs e)
{
OnEvent (DeviceAdded, e);
}
protected virtual void OnServiceAdded (ServiceEventArgs e)
{
OnEvent (ServiceAdded, e);
}
protected virtual void OnDeviceRemoved (DeviceEventArgs e)
{
OnEvent (DeviceRemoved, e);
}
protected virtual void OnServiceRemoved (ServiceEventArgs e)
{
OnEvent (ServiceRemoved, e);
}
void OnEvent<T> (EventHandler<T> handler, T e)
where T : EventArgs
{
if (handler != null) {
handler (this, e);
}
}
internal Service GetService (ServiceAnnouncement announcement)
{
return GetDescription<ServiceAnnouncement, Service> (announcement.Locations, announcement, GetService);
}
internal Device GetDevice (DeviceAnnouncement announcement)
{
return GetDescription<DeviceAnnouncement, Device> (announcement.Locations, announcement, GetDevice);
}
TResult GetDescription<TAnnouncement, TResult> (IEnumerable<string> urls,
TAnnouncement announcement,
Mono.Upnp.Internal.Func<TAnnouncement, Device, TResult> getter)
where TResult : class
{
foreach (var url in urls) {
Root root;
if (descriptions.TryGetValue (url, out root)) {
if (!root.IsDisposed) {
var result = getter (announcement, root.RootDevice);
if (result != null) {
return result;
}
}
}
try {
var deserializer = Helper.Get<XmlDeserializer> (static_deserializer);
root = deserializer_producer (deserializer).DeserializeRoot (new Uri (url));
if (root == null) {
continue;
}
descriptions[url] = root;
if (root.RootDevice == null) {
Log.Error (string.Format ("The description root does not have a root device: {0}.", url));
continue;
}
var result = getter (announcement, root.RootDevice);
if (result == null) {
continue;
}
return result;
} catch (Exception e) {
Log.Exception (string.Format ("There was a problem fetching the description at {0}.", url), e);
}
}
return null;
}
Service GetService (ServiceAnnouncement announcement, Device device)
{
foreach (var description in device.Services) {
if (device.Udn == announcement.DeviceUdn && announcement.Type == description.Type) {
return description;
}
}
foreach (var childDevice in device.Devices) {
var description = GetService (announcement, childDevice);
if (description != null) {
return description;
}
}
return null;
}
Device GetDevice (DeviceAnnouncement announcement, Device device)
{
if (device.Type == announcement.Type && device.Udn == announcement.Udn) {
return device;
}
foreach (var childDevice in device.Devices) {
var description = GetDevice (announcement, childDevice);
if (description != null) {
return description;
}
}
return null;
}
public void Dispose ()
{
// TODO proper dispose pattern
client.Dispose ();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Insights
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AlertRuleIncidentsOperations operations.
/// </summary>
internal partial class AlertRuleIncidentsOperations : IServiceOperations<MonitorManagementClient>, IAlertRuleIncidentsOperations
{
/// <summary>
/// Initializes a new instance of the AlertRuleIncidentsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal AlertRuleIncidentsOperations(MonitorManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the MonitorManagementClient
/// </summary>
public MonitorManagementClient Client { get; private set; }
/// <summary>
/// Gets an incident associated to an alert rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='incidentName'>
/// The name of the incident to retrieve.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Incident>> GetWithHttpMessagesAsync(string resourceGroupName, string ruleName, string incidentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (incidentName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "incidentName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("incidentName", incidentName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents/{incidentName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{incidentName}", System.Uri.EscapeDataString(incidentName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Incident>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Incident>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of incidents associated to an alert rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Incident>>> ListByAlertRuleWithHttpMessagesAsync(string resourceGroupName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByAlertRule", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Incident>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Incident>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Collections;
namespace log4net.Plugin
{
/// <summary>
/// A strongly-typed collection of <see cref="IPlugin"/> objects.
/// </summary>
/// <author>Nicko Cadell</author>
public class PluginCollection : ICollection, IList, IEnumerable
#if !NETSTANDARD1_3
, ICloneable
#endif
{
#region Interfaces
/// <summary>
/// Supports type-safe iteration over a <see cref="PluginCollection"/>.
/// </summary>
/// <exclude/>
public interface IPluginCollectionEnumerator
{
/// <summary>
/// Gets the current element in the collection.
/// </summary>
IPlugin Current { get; }
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
bool MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
void Reset();
}
#endregion Interfaces
private const int DEFAULT_CAPACITY = 16;
#region Implementation (data)
private IPlugin[] m_array;
private int m_count = 0;
private int m_version = 0;
#endregion Implementation (data)
#region Static Wrappers
/// <summary>
/// Creates a read-only wrapper for a <c>PluginCollection</c> instance.
/// </summary>
/// <param name="list">list to create a readonly wrapper arround</param>
/// <returns>
/// A <c>PluginCollection</c> wrapper that is read-only.
/// </returns>
public static PluginCollection ReadOnly(PluginCollection list)
{
if(list == null) throw new ArgumentNullException("list");
return new ReadOnlyPluginCollection(list);
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <c>PluginCollection</c> class
/// that is empty and has the default initial capacity.
/// </summary>
public PluginCollection()
{
m_array = new IPlugin[DEFAULT_CAPACITY];
}
/// <summary>
/// Initializes a new instance of the <c>PluginCollection</c> class
/// that has the specified initial capacity.
/// </summary>
/// <param name="capacity">
/// The number of elements that the new <c>PluginCollection</c> is initially capable of storing.
/// </param>
public PluginCollection(int capacity)
{
m_array = new IPlugin[capacity];
}
/// <summary>
/// Initializes a new instance of the <c>PluginCollection</c> class
/// that contains elements copied from the specified <c>PluginCollection</c>.
/// </summary>
/// <param name="c">The <c>PluginCollection</c> whose elements are copied to the new collection.</param>
public PluginCollection(PluginCollection c)
{
m_array = new IPlugin[c.Count];
AddRange(c);
}
/// <summary>
/// Initializes a new instance of the <c>PluginCollection</c> class
/// that contains elements copied from the specified <see cref="IPlugin"/> array.
/// </summary>
/// <param name="a">The <see cref="IPlugin"/> array whose elements are copied to the new list.</param>
public PluginCollection(IPlugin[] a)
{
m_array = new IPlugin[a.Length];
AddRange(a);
}
/// <summary>
/// Initializes a new instance of the <c>PluginCollection</c> class
/// that contains elements copied from the specified <see cref="IPlugin"/> collection.
/// </summary>
/// <param name="col">The <see cref="IPlugin"/> collection whose elements are copied to the new list.</param>
public PluginCollection(ICollection col)
{
m_array = new IPlugin[col.Count];
AddRange(col);
}
/// <summary>
/// Type visible only to our subclasses
/// Used to access protected constructor
/// </summary>
/// <exclude/>
protected internal enum Tag
{
/// <summary>
/// A value
/// </summary>
Default
}
/// <summary>
/// Allow subclasses to avoid our default constructors
/// </summary>
/// <param name="tag"></param>
/// <exclude/>
protected internal PluginCollection(Tag tag)
{
m_array = null;
}
#endregion
#region Operations (type-safe ICollection)
/// <summary>
/// Gets the number of elements actually contained in the <c>PluginCollection</c>.
/// </summary>
public virtual int Count
{
get { return m_count; }
}
/// <summary>
/// Copies the entire <c>PluginCollection</c> to a one-dimensional
/// <see cref="IPlugin"/> array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="IPlugin"/> array to copy to.</param>
public virtual void CopyTo(IPlugin[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
/// Copies the entire <c>PluginCollection</c> to a one-dimensional
/// <see cref="IPlugin"/> array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="IPlugin"/> array to copy to.</param>
/// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(IPlugin[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
{
throw new System.ArgumentException("Destination array was not long enough.");
}
Array.Copy(m_array, 0, array, start, m_count);
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <returns>false, because the backing type is an array, which is never thread-safe.</returns>
public virtual bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
/// <value>
/// An object that can be used to synchronize access to the collection.
/// </value>
public virtual object SyncRoot
{
get { return m_array; }
}
#endregion
#region Operations (type-safe IList)
/// <summary>
/// Gets or sets the <see cref="IPlugin"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="IPlugin"/> at the specified index.
/// </value>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero.</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para>
/// </exception>
public virtual IPlugin this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
/// Adds a <see cref="IPlugin"/> to the end of the <c>PluginCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IPlugin"/> to be added to the end of the <c>PluginCollection</c>.</param>
/// <returns>The index at which the value has been added.</returns>
public virtual int Add(IPlugin item)
{
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
m_array[m_count] = item;
m_version++;
return m_count++;
}
/// <summary>
/// Removes all elements from the <c>PluginCollection</c>.
/// </summary>
public virtual void Clear()
{
++m_version;
m_array = new IPlugin[DEFAULT_CAPACITY];
m_count = 0;
}
/// <summary>
/// Creates a shallow copy of the <see cref="PluginCollection"/>.
/// </summary>
/// <returns>A new <see cref="PluginCollection"/> with a shallow copy of the collection data.</returns>
public virtual object Clone()
{
PluginCollection newCol = new PluginCollection(m_count);
Array.Copy(m_array, 0, newCol.m_array, 0, m_count);
newCol.m_count = m_count;
newCol.m_version = m_version;
return newCol;
}
/// <summary>
/// Determines whether a given <see cref="IPlugin"/> is in the <c>PluginCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IPlugin"/> to check for.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <c>PluginCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(IPlugin item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the zero-based index of the first occurrence of a <see cref="IPlugin"/>
/// in the <c>PluginCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IPlugin"/> to locate in the <c>PluginCollection</c>.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/>
/// in the entire <c>PluginCollection</c>, if found; otherwise, -1.
/// </returns>
public virtual int IndexOf(IPlugin item)
{
for (int i=0; i != m_count; ++i)
{
if (m_array[i].Equals(item))
{
return i;
}
}
return -1;
}
/// <summary>
/// Inserts an element into the <c>PluginCollection</c> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The <see cref="IPlugin"/> to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para>
/// </exception>
public virtual void Insert(int index, IPlugin item)
{
ValidateIndex(index, true); // throws
if (m_count == m_array.Length)
{
EnsureCapacity(m_count + 1);
}
if (index < m_count)
{
Array.Copy(m_array, index, m_array, index + 1, m_count - index);
}
m_array[index] = item;
m_count++;
m_version++;
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="IPlugin"/> from the <c>PluginCollection</c>.
/// </summary>
/// <param name="item">The <see cref="IPlugin"/> to remove from the <c>PluginCollection</c>.</param>
/// <exception cref="ArgumentException">
/// The specified <see cref="IPlugin"/> was not found in the <c>PluginCollection</c>.
/// </exception>
public virtual void Remove(IPlugin item)
{
int i = IndexOf(item);
if (i < 0)
{
throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
}
++m_version;
RemoveAt(i);
}
/// <summary>
/// Removes the element at the specified index of the <c>PluginCollection</c>.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero.</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para>
/// </exception>
public virtual void RemoveAt(int index)
{
ValidateIndex(index); // throws
m_count--;
if (index < m_count)
{
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
}
// We can't set the deleted entry equal to null, because it might be a value type.
// Instead, we'll create an empty single-element array of the right type and copy it
// over the entry we want to erase.
IPlugin[] temp = new IPlugin[1];
Array.Copy(temp, 0, m_array, m_count, 1);
m_version++;
}
/// <summary>
/// Gets a value indicating whether the collection has a fixed size.
/// </summary>
/// <value><c>true</c> if the collection has a fixed size; otherwise, <c>false</c>. The default is <c>false</c>.</value>
public virtual bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the IList is read-only.
/// </summary>
/// <value><c>true</c> if the collection is read-only; otherwise, <c>false</c>. The default is <c>false</c>.</value>
public virtual bool IsReadOnly
{
get { return false; }
}
#endregion
#region Operations (type-safe IEnumerable)
/// <summary>
/// Returns an enumerator that can iterate through the <c>PluginCollection</c>.
/// </summary>
/// <returns>An <see cref="Enumerator"/> for the entire <c>PluginCollection</c>.</returns>
public virtual IPluginCollectionEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
/// Gets or sets the number of elements the <c>PluginCollection</c> can contain.
/// </summary>
/// <value>
/// The number of elements the <c>PluginCollection</c> can contain.
/// </value>
public virtual int Capacity
{
get
{
return m_array.Length;
}
set
{
if (value < m_count)
{
value = m_count;
}
if (value != m_array.Length)
{
if (value > 0)
{
IPlugin[] temp = new IPlugin[value];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
else
{
m_array = new IPlugin[DEFAULT_CAPACITY];
}
}
}
}
/// <summary>
/// Adds the elements of another <c>PluginCollection</c> to the current <c>PluginCollection</c>.
/// </summary>
/// <param name="x">The <c>PluginCollection</c> whose elements should be added to the end of the current <c>PluginCollection</c>.</param>
/// <returns>The new <see cref="PluginCollection.Count"/> of the <c>PluginCollection</c>.</returns>
public virtual int AddRange(PluginCollection x)
{
if (m_count + x.Count >= m_array.Length)
{
EnsureCapacity(m_count + x.Count);
}
Array.Copy(x.m_array, 0, m_array, m_count, x.Count);
m_count += x.Count;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="IPlugin"/> array to the current <c>PluginCollection</c>.
/// </summary>
/// <param name="x">The <see cref="IPlugin"/> array whose elements should be added to the end of the <c>PluginCollection</c>.</param>
/// <returns>The new <see cref="PluginCollection.Count"/> of the <c>PluginCollection</c>.</returns>
public virtual int AddRange(IPlugin[] x)
{
if (m_count + x.Length >= m_array.Length)
{
EnsureCapacity(m_count + x.Length);
}
Array.Copy(x, 0, m_array, m_count, x.Length);
m_count += x.Length;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="IPlugin"/> collection to the current <c>PluginCollection</c>.
/// </summary>
/// <param name="col">The <see cref="IPlugin"/> collection whose elements should be added to the end of the <c>PluginCollection</c>.</param>
/// <returns>The new <see cref="PluginCollection.Count"/> of the <c>PluginCollection</c>.</returns>
public virtual int AddRange(ICollection col)
{
if (m_count + col.Count >= m_array.Length)
{
EnsureCapacity(m_count + col.Count);
}
foreach(object item in col)
{
Add((IPlugin)item);
}
return m_count;
}
/// <summary>
/// Sets the capacity to the actual number of elements.
/// </summary>
public virtual void TrimToSize()
{
this.Capacity = m_count;
}
#endregion
#region Implementation (helpers)
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="i"/> is less than zero.</para>
/// <para>-or-</para>
/// <para><paramref name="i"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i)
{
ValidateIndex(i, false);
}
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="i"/> is less than zero.</para>
/// <para>-or-</para>
/// <para><paramref name="i"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i, bool allowEqualEnd)
{
int max = (allowEqualEnd) ? (m_count) : (m_count-1);
if (i < 0 || i > max)
{
throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values.");
}
}
private void EnsureCapacity(int min)
{
int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2);
if (newCapacity < min)
{
newCapacity = min;
}
this.Capacity = newCapacity;
}
#endregion
#region Implementation (ICollection)
void ICollection.CopyTo(Array array, int start)
{
Array.Copy(m_array, 0, array, start, m_count);
}
#endregion
#region Implementation (IList)
object IList.this[int i]
{
get { return (object)this[i]; }
set { this[i] = (IPlugin)value; }
}
int IList.Add(object x)
{
return this.Add((IPlugin)x);
}
bool IList.Contains(object x)
{
return this.Contains((IPlugin)x);
}
int IList.IndexOf(object x)
{
return this.IndexOf((IPlugin)x);
}
void IList.Insert(int pos, object x)
{
this.Insert(pos, (IPlugin)x);
}
void IList.Remove(object x)
{
this.Remove((IPlugin)x);
}
void IList.RemoveAt(int pos)
{
this.RemoveAt(pos);
}
#endregion
#region Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(this.GetEnumerator());
}
#endregion Implementation (IEnumerable)
#region Nested enumerator class
/// <summary>
/// Supports simple iteration over a <see cref="PluginCollection"/>.
/// </summary>
/// <exclude/>
private sealed class Enumerator : IEnumerator, IPluginCollectionEnumerator
{
#region Implementation (data)
private readonly PluginCollection m_collection;
private int m_index;
private int m_version;
#endregion Implementation (data)
#region Construction
/// <summary>
/// Initializes a new instance of the <c>Enumerator</c> class.
/// </summary>
/// <param name="tc"></param>
internal Enumerator(PluginCollection tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
#endregion
#region Operations (type-safe IEnumerator)
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <value>
/// The current element in the collection.
/// </value>
public IPlugin Current
{
get { return m_collection[m_index]; }
}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
{
throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute.");
}
++m_index;
return (m_index < m_collection.Count);
}
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
public void Reset()
{
m_index = -1;
}
#endregion
#region Implementation (IEnumerator)
object IEnumerator.Current
{
get { return this.Current; }
}
#endregion
}
#endregion
#region Nested Read Only Wrapper class
/// <exclude/>
private sealed class ReadOnlyPluginCollection : PluginCollection
{
#region Implementation (data)
private readonly PluginCollection m_collection;
#endregion
#region Construction
internal ReadOnlyPluginCollection(PluginCollection list) : base(Tag.Default)
{
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(IPlugin[] array)
{
m_collection.CopyTo(array);
}
public override void CopyTo(IPlugin[] array, int start)
{
m_collection.CopyTo(array,start);
}
public override int Count
{
get { return m_collection.Count; }
}
public override bool IsSynchronized
{
get { return m_collection.IsSynchronized; }
}
public override object SyncRoot
{
get { return this.m_collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override IPlugin this[int i]
{
get { return m_collection[i]; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int Add(IPlugin x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Clear()
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool Contains(IPlugin x)
{
return m_collection.Contains(x);
}
public override int IndexOf(IPlugin x)
{
return m_collection.IndexOf(x);
}
public override void Insert(int pos, IPlugin x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Remove(IPlugin x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void RemoveAt(int pos)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool IsFixedSize
{
get { return true; }
}
public override bool IsReadOnly
{
get { return true; }
}
#endregion
#region Type-safe IEnumerable
public override IPluginCollectionEnumerator GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get { return m_collection.Capacity; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int AddRange(PluginCollection x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override int AddRange(IPlugin[] x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
#endregion
}
#endregion
}
}
| |
// 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 System.Drawing;
namespace DotSpatial.Data
{
/// <summary>
/// TiledImage is a special kind of image coverage where the images specifically form tiles that
/// are adjacent and perfectly aligned to represent a larger image.
/// </summary>
public class TiledImage : RasterBoundDataSet, ITiledImage, IImageData
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="TiledImage"/> class where the fileName is specified.
/// This doesn't actually open the file until the Open method is called.
/// </summary>
/// <param name="fileName">The name of the file.</param>
public TiledImage(string fileName)
{
Filename = fileName;
}
/// <summary>
/// Initializes a new instance of the <see cref="TiledImage"/> class.
/// </summary>
/// <param name="width">The width of the image.</param>
/// <param name="height">The height of the image.</param>
public TiledImage(int width, int height)
{
Init(width, height);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the band type. This is not implemented.
/// </summary>
public ImageBandType BandType
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <inheritdoc />
public int BytesPerPixel
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <inheritdoc />
public int Count => TileCollection.NumTiles;
/// <inheritdoc />
public override Extent Extent
{
get
{
Extent ext = new Extent();
foreach (IImageData image in TileCollection)
{
ext.ExpandToInclude(image.Extent);
}
return ext;
}
}
/// <inheritdoc />
public int Height
{
get
{
return TileCollection.Height;
}
set
{
}
}
/// <summary>
/// Gets or sets the number of bands.
/// </summary>
public int NumBands { get; set; }
/// <inheritdoc />
public int Stride { get; set; }
/// <inheritdoc />
public int TileHeight => TileCollection.TileHeight;
/// <summary>
/// Gets or sets the array of tiles used for this.
/// </summary>
public virtual IImageData[,] Tiles
{
get
{
return TileCollection.Tiles;
}
set
{
TileCollection.Tiles = value;
}
}
/// <inheritdoc />
public int TileWidth => TileCollection.TileWidth;
/// <inheritdoc />
public byte[] Values
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <inheritdoc />
public int Width
{
get
{
return TileCollection.Width;
}
set
{
}
}
/// <summary>
/// Gets or sets the WorldFile for this set of tiles.
/// </summary>
public WorldFile WorldFile { get; set; }
/// <summary>
/// Gets or sets the tile collection.
/// </summary>
protected TileCollection TileCollection { get; set; }
#endregion
#region Methods
/// <inheritdoc />
public override void Close()
{
if (Tiles == null) return;
foreach (IImageData image in Tiles)
{
image?.Close();
}
base.Close();
}
/// <inheritdoc />
public void CopyBitmapToValues()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void CopyValues(IImageData source)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void CopyValuesToBitmap()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public virtual Bitmap GetBitmap(Extent envelope, Size pixelSize)
{
Bitmap result = new Bitmap(pixelSize.Width, pixelSize.Height);
Graphics g = Graphics.FromImage(result);
foreach (var image in GetImages())
{
Extent bounds = envelope.Intersection(image.Extent);
Size ps = new Size((int)(pixelSize.Width * bounds.Width / envelope.Width), (int)(pixelSize.Height * bounds.Height / envelope.Height));
int x = pixelSize.Width * (int)((bounds.X - envelope.X) / envelope.Width);
int y = pixelSize.Height * (int)((envelope.Y - bounds.Y) / envelope.Height);
if (ps.Width > 0 && ps.Height > 0)
{
Bitmap tile = image.GetBitmap(bounds, ps);
g.DrawImageUnscaled(tile, x, y);
}
}
return result;
}
/// <inheritdoc />
public Bitmap GetBitmap()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public Bitmap GetBitmap(Extent envelope, Rectangle window)
{
return GetBitmap(envelope, new Size(window.Width, window.Height));
}
/// <inheritdoc />
public Color GetColor(int row, int column)
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented.
/// </summary>
/// <returns>The color palette.</returns>
public IEnumerable<Color> GetColorPalette()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public IEnumerable<IImageData> GetImages()
{
return TileCollection;
}
/// <summary>
/// Even if this TiledImage has already been constructed, we can initialize the tile collection later.
/// </summary>
/// <param name="width">The width of the image.</param>
/// <param name="height">The height of the image.</param>
public void Init(int width, int height)
{
TileCollection = new TileCollection(width, height);
}
/// <summary>
/// This should be overridden with custom file handling
/// </summary>
public virtual void Open()
{
}
/// <summary>
/// Not implemented
/// </summary>
/// <param name="xOffset">The x offset.</param>
/// <param name="yOffset">The y offset.</param>
/// <param name="xSize">The x size.</param>
/// <param name="ySize">The y size.</param>
/// <returns>A bitmap.</returns>
public Bitmap ReadBlock(int xOffset, int yOffset, int xSize, int ySize)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void Save()
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void SaveAs(string fileName)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public void SetColor(int row, int column, Color col)
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
/// <param name="value">The color palette.</param>
public void SetColorPalette(IEnumerable<Color> value)
{
throw new NotImplementedException();
}
/// <summary>
/// Calls a method that calculates the proper image bounds for each of the extents of the tiles,
/// given the affine coefficients for the whole image.
/// </summary>
/// <param name="affine"> x' = A + Bx + Cy; y' = D + Ex + Fy</param>
public void SetTileBounds(double[] affine)
{
TileCollection.SetTileBounds(affine);
}
/// <summary>
/// Not implemented
/// </summary>
public void UpdateOverviews()
{
throw new NotImplementedException();
}
/// <summary>
/// Not Implemented
/// </summary>
/// <param name="value">The value.</param>
/// <param name="xOffset">The x offset.</param>
/// <param name="yOffset">The y offset.</param>
public void WriteBlock(Bitmap value, int xOffset, int yOffset)
{
throw new NotImplementedException();
}
/// <inheritdoc />
protected override void Dispose(bool disposeManagedResources)
{
foreach (IImageData tile in TileCollection)
{
tile.Dispose();
}
base.Dispose(disposeManagedResources);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject
{
// Zero parameters
public class SubContainerCreatorByMethod : ISubContainerCreator
{
readonly Action<DiContainer> _installMethod;
readonly DiContainer _container;
public SubContainerCreatorByMethod(
DiContainer container,
Action<DiContainer> installMethod)
{
_installMethod = installMethod;
_container = container;
}
public DiContainer CreateSubContainer(List<TypeValuePair> args, InjectContext context)
{
Assert.IsEmpty(args);
var subContainer = _container.CreateSubContainer();
_installMethod(subContainer);
subContainer.ResolveDependencyRoots();
subContainer.FlushInjectQueue();
if (subContainer.IsValidating)
{
// The root-level Container has its ValidateValidatables method
// called explicitly - however, this is not so for sub-containers
// so call it here instead
subContainer.ValidateValidatables();
}
return subContainer;
}
}
// One parameters
public class SubContainerCreatorByMethod<TParam1> : ISubContainerCreator
{
readonly Action<DiContainer, TParam1> _installMethod;
readonly DiContainer _container;
public SubContainerCreatorByMethod(
DiContainer container,
Action<DiContainer, TParam1> installMethod)
{
_installMethod = installMethod;
_container = container;
}
public DiContainer CreateSubContainer(List<TypeValuePair> args, InjectContext context)
{
Assert.IsEqual(args.Count, 1);
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
var subContainer = _container.CreateSubContainer();
_installMethod(subContainer, (TParam1)args[0].Value);
subContainer.ResolveDependencyRoots();
subContainer.FlushInjectQueue();
if (subContainer.IsValidating)
{
// The root-level Container has its ValidateValidatables method
// called explicitly - however, this is not so for sub-containers
// so call it here instead
subContainer.ValidateValidatables();
}
return subContainer;
}
}
// Two parameters
public class SubContainerCreatorByMethod<TParam1, TParam2> : ISubContainerCreator
{
readonly Action<DiContainer, TParam1, TParam2> _installMethod;
readonly DiContainer _container;
public SubContainerCreatorByMethod(
DiContainer container,
Action<DiContainer, TParam1, TParam2> installMethod)
{
_installMethod = installMethod;
_container = container;
}
public DiContainer CreateSubContainer(List<TypeValuePair> args, InjectContext context)
{
Assert.IsEqual(args.Count, 2);
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
var subContainer = _container.CreateSubContainer();
_installMethod(
subContainer,
(TParam1)args[0].Value,
(TParam2)args[1].Value);
subContainer.ResolveDependencyRoots();
subContainer.FlushInjectQueue();
if (subContainer.IsValidating)
{
// The root-level Container has its ValidateValidatables method
// called explicitly - however, this is not so for sub-containers
// so call it here instead
subContainer.ValidateValidatables();
}
return subContainer;
}
}
// Three parameters
public class SubContainerCreatorByMethod<TParam1, TParam2, TParam3> : ISubContainerCreator
{
readonly Action<DiContainer, TParam1, TParam2, TParam3> _installMethod;
readonly DiContainer _container;
public SubContainerCreatorByMethod(
DiContainer container,
Action<DiContainer, TParam1, TParam2, TParam3> installMethod)
{
_installMethod = installMethod;
_container = container;
}
public DiContainer CreateSubContainer(List<TypeValuePair> args, InjectContext context)
{
Assert.IsEqual(args.Count, 3);
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
var subContainer = _container.CreateSubContainer();
_installMethod(
subContainer,
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value);
subContainer.ResolveDependencyRoots();
subContainer.FlushInjectQueue();
if (subContainer.IsValidating)
{
// The root-level Container has its ValidateValidatables method
// called explicitly - however, this is not so for sub-containers
// so call it here instead
subContainer.ValidateValidatables();
}
return subContainer;
}
}
// Four parameters
public class SubContainerCreatorByMethod<TParam1, TParam2, TParam3, TParam4> : ISubContainerCreator
{
readonly ModestTree.Util.Action<DiContainer, TParam1, TParam2, TParam3, TParam4> _installMethod;
readonly DiContainer _container;
public SubContainerCreatorByMethod(
DiContainer container,
ModestTree.Util.Action<DiContainer, TParam1, TParam2, TParam3, TParam4> installMethod)
{
_installMethod = installMethod;
_container = container;
}
public DiContainer CreateSubContainer(List<TypeValuePair> args, InjectContext context)
{
Assert.IsEqual(args.Count, 4);
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>());
var subContainer = _container.CreateSubContainer();
_installMethod(
subContainer,
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value);
subContainer.ResolveDependencyRoots();
subContainer.FlushInjectQueue();
if (subContainer.IsValidating)
{
// The root-level Container has its ValidateValidatables method
// called explicitly - however, this is not so for sub-containers
// so call it here instead
subContainer.ValidateValidatables();
}
return subContainer;
}
}
// Five parameters
public class SubContainerCreatorByMethod<TParam1, TParam2, TParam3, TParam4, TParam5> : ISubContainerCreator
{
readonly ModestTree.Util.Action<DiContainer, TParam1, TParam2, TParam3, TParam4, TParam5> _installMethod;
readonly DiContainer _container;
public SubContainerCreatorByMethod(
DiContainer container,
ModestTree.Util.Action<DiContainer, TParam1, TParam2, TParam3, TParam4, TParam5> installMethod)
{
_installMethod = installMethod;
_container = container;
}
public DiContainer CreateSubContainer(List<TypeValuePair> args, InjectContext context)
{
Assert.IsEqual(args.Count, 5);
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>());
Assert.That(args[4].Type.DerivesFromOrEqual<TParam5>());
var subContainer = _container.CreateSubContainer();
_installMethod(
subContainer,
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value,
(TParam5)args[4].Value);
subContainer.ResolveDependencyRoots();
subContainer.FlushInjectQueue();
if (subContainer.IsValidating)
{
// The root-level Container has its ValidateValidatables method
// called explicitly - however, this is not so for sub-containers
// so call it here instead
subContainer.ValidateValidatables();
}
return subContainer;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace BookstoreWeb
{
public static class TokenHelper
{
#region public methods
/// <summary>
/// Configures .Net to trust all certificates when making network calls. This is used so that calls
/// to an https SharePoint server without a valid certificate are not rejected. This should only be used during
/// testing, and should never be used in a production app.
/// </summary>
public static void TrustAllCertificates()
{
//Trust all certificates
ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName];
if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName];
}
return null;
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName];
if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName];
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (ClientCertificate != null)
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (ClientCertificate != null)
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
const string bearer = "Bearer realm=\"";
int realmIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal) + bearer.Length;
if (bearerResponseHeader.Length > realmIndex)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
private const int TokenLifetimeMinutes = 1000000;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.AddMinutes(TokenLifetimeMinutes),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(10),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
private static string EnsureTrailingSlash(string url)
{
if (!String.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
public class OAuthTokenPair
{
public string AccessToken;
public string RefreshToken;
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
/*
SharePoint-Add-in-Localization, https://github.com/officedev/SharePoint-Add-in-Localization
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityStandardAssets.Effects;
namespace UnityStandardAssets.SceneUtils
{
public class ParticleSceneControls : MonoBehaviour
{
public enum Mode
{
Activate,
Instantiate,
Trail
}
public enum AlignMode
{
Normal,
Up
}
public DemoParticleSystemList demoParticles;
public float spawnOffset = 0.5f;
public float multiply = 1;
public bool clearOnChange = false;
public Text titleText;
public Transform sceneCamera;
public Text instructionText;
public Button previousButton;
public Button nextButton;
public GraphicRaycaster graphicRaycaster;
public EventSystem eventSystem;
private ParticleSystemMultiplier m_ParticleMultiplier;
private List<Transform> m_CurrentParticleList = new List<Transform>();
private Transform m_Instance;
private static int s_SelectedIndex = 0;
private Vector3 m_CamOffsetVelocity = Vector3.zero;
private Vector3 m_LastPos;
private static DemoParticleSystem s_Selected;
private void Awake()
{
Select(s_SelectedIndex);
previousButton.onClick.AddListener(Previous);
nextButton.onClick.AddListener(Next);
}
private void OnDisable()
{
previousButton.onClick.RemoveListener (Previous);
nextButton.onClick.RemoveListener (Next);
}
private void Previous()
{
s_SelectedIndex--;
if (s_SelectedIndex == -1)
{
s_SelectedIndex = demoParticles.items.Length - 1;
}
Select(s_SelectedIndex);
}
public void Next()
{
s_SelectedIndex++;
if (s_SelectedIndex == demoParticles.items.Length)
{
s_SelectedIndex = 0;
}
Select(s_SelectedIndex);
}
private void Update()
{
#if !MOBILE_INPUT
KeyboardInput();
#endif
sceneCamera.localPosition = Vector3.SmoothDamp(sceneCamera.localPosition, Vector3.forward*-s_Selected.camOffset,
ref m_CamOffsetVelocity, 1);
if (s_Selected.mode == Mode.Activate)
{
// this is for a particle system that just needs activating, and needs no interaction (eg, duststorm)
return;
}
if (CheckForGuiCollision()) return;
bool oneShotClick = (Input.GetMouseButtonDown(0) && s_Selected.mode == Mode.Instantiate);
bool repeat = (Input.GetMouseButton(0) && s_Selected.mode == Mode.Trail);
if (oneShotClick || repeat)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var rot = Quaternion.LookRotation(hit.normal);
if (s_Selected.align == AlignMode.Up)
{
rot = Quaternion.identity;
}
var pos = hit.point + hit.normal*spawnOffset;
if ((pos - m_LastPos).magnitude > s_Selected.minDist)
{
if (s_Selected.mode != Mode.Trail || m_Instance == null)
{
m_Instance = (Transform) Instantiate(s_Selected.transform, pos, rot);
if (m_ParticleMultiplier != null)
{
m_Instance.GetComponent<ParticleSystemMultiplier>().multiplier = multiply;
}
m_CurrentParticleList.Add(m_Instance);
if (s_Selected.maxCount > 0 && m_CurrentParticleList.Count > s_Selected.maxCount)
{
if (m_CurrentParticleList[0] != null)
{
Destroy(m_CurrentParticleList[0].gameObject);
}
m_CurrentParticleList.RemoveAt(0);
}
}
else
{
m_Instance.position = pos;
m_Instance.rotation = rot;
}
if (s_Selected.mode == Mode.Trail)
{
var emission = m_Instance.transform.GetComponent<ParticleSystem>().emission;
emission.enabled = false;
m_Instance.transform.GetComponent<ParticleSystem>().Emit(1);
}
m_Instance.parent = hit.transform;
m_LastPos = pos;
}
}
}
}
#if !MOBILE_INPUT
void KeyboardInput()
{
if(Input.GetKeyDown(KeyCode.LeftArrow))
Previous();
if (Input.GetKeyDown(KeyCode.RightArrow))
Next();
}
#endif
bool CheckForGuiCollision()
{
PointerEventData eventData = new PointerEventData(eventSystem);
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;
List<RaycastResult> list = new List<RaycastResult>();
graphicRaycaster.Raycast(eventData, list);
return list.Count > 0;
}
private void Select(int i)
{
s_Selected = demoParticles.items[i];
m_Instance = null;
foreach (var otherEffect in demoParticles.items)
{
if ((otherEffect != s_Selected) && (otherEffect.mode == Mode.Activate))
{
otherEffect.transform.gameObject.SetActive(false);
}
}
if (s_Selected.mode == Mode.Activate)
{
s_Selected.transform.gameObject.SetActive(true);
}
m_ParticleMultiplier = s_Selected.transform.GetComponent<ParticleSystemMultiplier>();
multiply = 1;
if (clearOnChange)
{
while (m_CurrentParticleList.Count > 0)
{
Destroy(m_CurrentParticleList[0].gameObject);
m_CurrentParticleList.RemoveAt(0);
}
}
instructionText.text = s_Selected.instructionText;
titleText.text = s_Selected.transform.name;
}
[Serializable]
public class DemoParticleSystem
{
public Transform transform;
public Mode mode;
public AlignMode align;
public int maxCount;
public float minDist;
public int camOffset = 15;
public string instructionText;
}
[Serializable]
public class DemoParticleSystemList
{
public DemoParticleSystem[] items;
}
}
}
| |
using System;
using Gibraltar.Agent.Internal;
using Loupe.Configuration;
using Loupe.Extensibility.Data;
namespace Gibraltar.Agent
{
/// <summary>
/// Packages up session files collected on the local computer and sends them to a
/// Loupe Server or anywhere via email or file transport with no user interface. For a
/// user interface, see PackagerDialog.
/// </summary>
/// <remarks>
/// <para>
/// The packager class can be used to package up session files synchronously or
/// asynchronously and send them via email or just store the results to a single,
/// compact file without any user interface.
/// </para>
/// <para>When creating a package of sessions, the packager needs to know:</para>
/// <list type="bullet">
/// <item>
/// <strong>What sessions to include:</strong> The <see cref="SessionCriteria">SessionCriteria</see> enumeration is used to indicate how
/// to select packages. It's a flag enumeration, allowing you to specify
/// multiple values at the same time.
/// </item>
/// <item><strong>What to do with the package:</strong> It can be emailed or stored
/// as a local file for you to subsequently handle on your own.</item>
/// <item><strong>Whether to mark sessions as read:</strong> Typically you'll want
/// to include sessions only on one package so that if a user generates a new
/// package later it won't contain sessions that have been completely sent before.
/// With this option set, Loupe will mark all of the sessions that it includes
/// in the package as long as the package is created successfully. If there is a
/// problem creating the package no sessions will be marked as sent.</item>
/// </list>
/// <para><strong>Asynchronous Usage</strong></para>
/// <para>
/// The packager can function asynchronously by using the methods that end with
/// Async. To get result information for asynchronous operations you need to
/// subscribe to the <see cref="EndSend">EndSession</see> event.
/// </para>
/// <para><strong>Sending the Active Session</strong></para>
/// <para>When you specify Session Criteria that includes the ActiveSession several
/// unique things happen.</para>
/// <list type="bullet">
/// <item>To enable the session to be sent the current log file is ended and a new
/// one is started (just like if Log.EndFile was called).</item>
/// <item>The session will not be marked as read as it is still being changed.
/// Therefore, it can still be sent later after it closes when the complete session
/// will be available.</item>
/// <item>If the session has already been split into multiple files they will have
/// to be merged in memory first and then sent. Depending on the size of your
/// session data this may consume significant memory and processor time. As a
/// general rule of thumb it takes about 50 times the amount of memory as the
/// session file size because of the significant compression used when storing the
/// data.</item>
/// </list>
/// <para></para>
/// </remarks>
/// <example>
/// <code lang="CS" title="Create and Send Package Via Email" description="The following example sends all of the session files for the product the current application is running as to the email address specified in the application config file. Once packaged, sessions are marked as read and won't be automatically included in future packages.">
/// //Send an email with all of the information about the current application we haven't sent before.
/// using(Packager packager = new Packager())
/// {
/// packager.SendEmail(SessionCriteria.NewSessions, true, null);
/// }
/// </code>
/// <code lang="CS" title="Create and Send Package to File" description="The following example packages all of the session files for the product the current application is running as into a local file. Once packaged, sessions are marked as read and won't be automatically included in future packages.">
/// <![CDATA[
/// //Send a file with all of the information about the current application we haven't sent before.
/// using (Packager packager = new Packager())
/// {
/// //the file name will automatically have the appropriate extension added, so it is specified
/// //below without any file extension. Typically you will want to generate a unique, temporary
/// //file name to store the data as instead of using a fixed file name.
/// packager.SendToFile(SessionCriteria.NewSessions, true, "C:\YourAppSessionData");
/// }]]>
/// </code>
/// </example>
public sealed class Packager : IDisposable
{
private readonly Gibraltar.Data.Packager m_Packager;
private bool m_Disposed;
/// <summary>
/// Raised at the start of the packaging and sending process (after all input is collected)
/// </summary>
public event EventHandler BeginSend;
/// <summary>
/// Raised at the end of the packaging and sending process with completion status information.
/// </summary>
public event PackageSendEventHandler EndSend;
/// <summary>
/// Create a new packager for the current process.
/// </summary>
/// <example>
/// <code lang="CS" title="Create Package" description="Create a new package for the current process to send an email with all data available.">
/// //Send an email with all of the information about the current application we haven't sent before.
/// using(Packager packager = new Packager())
/// {
/// packager.SendEmail(SessionCriteria.AllSessions, true, null);
/// }
/// </code>
/// </example>
/// <remarks>Only sessions for the current product & application will be considered</remarks>
public Packager()
{
//We have to ping the log object to make sure everything has been initialized. (this might be the first thing ever done in this process with the agent)
Monitor.Log.IsLoggingActive();
m_Packager = new Gibraltar.Data.Packager();
Initialize();
}
/// <summary>
/// Create a new packager for the specified product.
/// </summary>
/// <param name="productName">The product to package sessions for.</param>
/// <remarks>All applications for the specified product will be considered.</remarks>
public Packager(string productName)
{
//We have to ping the log object to make sure everything has been initialized. (this might be the first thing ever done in this process with the agent)
Monitor.Log.IsLoggingActive();
//we aren't using our other overloads because the Packager class has its own logic for how things should override.
m_Packager = new Gibraltar.Data.Packager(productName);
Initialize();
}
/// <summary>
/// Create a new packager for the specified product & application.
/// </summary>
/// <param name="productName">The product to package sessions for.</param>
/// <param name="applicationName"> Optional. Restricts the packager to considering sessions for just this application within the specified product.</param>
/// <remarks>If the application name is null then this will consider all applications for the specified product.</remarks>
public Packager(string productName, string applicationName)
{
//We have to ping the log object to make sure everything has been initialized. (this might be the first thing ever done in this process with the agent)
Monitor.Log.IsLoggingActive();
//we aren't using our other overloads because the Packager class has its own logic for how things should override.
m_Packager = new Gibraltar.Data.Packager(productName, applicationName);
Initialize();
}
/// <summary>
/// Create a new packager for the current process.
/// </summary>
/// <param name="productName">The product to package sessions for.</param>
/// <param name="applicationName">Optional. Restricts the packager to considering sessions for just this application within the specified product.</param>
/// <param name="directory">Optional. The log file directory on disk to look in for session files</param>
/// <remarks>
/// <para>If a repository folder is specified then only session files in that folder will be considered.</para>
/// <para>If the application name is null then this will consider all applications for the specified product.</para>
/// </remarks>
public Packager(string productName, string applicationName = null, string directory = null)
{
//We have to ping the log object to make sure everything has been initialized. (this might be the first thing ever done in this process with the agent)
Monitor.Log.IsLoggingActive();
//we aren't using our other overloads because the Packager class has its own logic for how things should override.
m_Packager = new Gibraltar.Data.Packager(productName, applicationName, directory);
Initialize();
}
#region Public Properties and Methods
/// <summary>
/// The product name of the current running application this packager was initialized with.
/// </summary>
public string ProductName { get { return m_Packager.ProductName; } }
/// <summary>
/// The name of the current running application this packager was initialized with.
/// </summary>
public string ApplicationName { get { return m_Packager.ApplicationName; } }
/// <summary>
/// A caption for the resulting package
/// </summary>
public string Caption
{
get { return m_Packager.Caption; }
set { m_Packager.Caption = value; }
}
/// <summary>
/// A description for the resulting package.
/// </summary>
public string Description
{
get { return m_Packager.Description; }
set { m_Packager.Description = value; }
}
///<summary>
///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///</summary>
///<filterpriority>2</filterpriority>
public void Dispose()
{
// Call the underlying implementation
Dispose(true);
// SuppressFinalize because there won't be anything left to finalize
GC.SuppressFinalize(this);
}
/// <summary>
/// Write the completed package to the provided full file name (without extension)
/// and path. The extension will be set to glp automatically.
/// </summary>
/// <remarks>The EndSend event will be raised when the send operation completes.
/// Any provided extension will be removed and replaced with the standard Loupe package extension.</remarks>
/// <example>
/// <code lang="CS">
/// <![CDATA[
/// //Send a file with all of the information about the current application we haven't sent before.
/// using (Packager packager = new Packager())
/// {
/// //the file name will automatically have the appropriate extension added, so it is specified
/// //below without any file extension. Typically you will want to generate a unique, temporary
/// //file name to store the data as instead of using a fixed file name.
/// packager.SendToFile(SessionCriteria.NewSessions, true, "C:\YourAppSessionData");
/// }]]>
/// </code>
/// </example>
/// <param name="sessions">The set of match rules to apply to sessions to determine what to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="fullFileNamePath">The file name and path to write the final package to.</param>
/// <exception cref="GibraltarException">Thrown when generation or transmission fails, includes details on failure</exception>
/// <exception cref="ArgumentNullException">A required parameter was null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The provided file information is not a fully qualified file name and path.</exception>
public void SendToFile(SessionCriteria sessions, bool markAsRead, string fullFileNamePath)
{
m_Packager.SendToFile(sessions, markAsRead, fullFileNamePath, false);
}
/// <summary>
/// Write the completed package to the provided full file name (without extension)
/// and path. The extension will be set to glp automatically.
/// </summary>
/// <remarks>The EndSend event will be raised when the send operation completes.
/// Any provided extension will be removed and replaced with the standard Loupe package extension.</remarks>
/// <param name="sessionMatchPredicate">A delegate to evaluate sessions and determine which ones to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="fullFileNamePath">The file name and path to write the final package to.</param>
/// <exception cref="GibraltarException">Thrown when generation or transmission fails, includes details on failure</exception>
/// <exception cref="ArgumentNullException">A required parameter was null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The provided file information is not a fully qualified file name and path.</exception>
public void SendToFile(Predicate<SessionSummary> sessionMatchPredicate, bool markAsRead, string fullFileNamePath)
{
var predicateAdapter = new SessionSummaryPredicate(sessionMatchPredicate);
m_Packager.SendToFile(predicateAdapter.Predicate, markAsRead, fullFileNamePath, false);
}
/// <summary>
/// Asynchronously write the completed package to the provided full file name
/// (without extension) and path. The extension will be set to glp automatically.
/// </summary>
/// <remarks>The EndSend event will be raised when the send operation completes.
/// Any provided extension will be removed and replaced with the standard Loupe package extension.</remarks>
/// <param name="sessions">The set of match rules to apply to sessions to determine what to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="fullFileNamePath">The file name and path to write the final package to.</param>
/// <exception cref="ArgumentNullException">A required parameter was null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The provided file information is not a fully qualified file name and path.</exception>
public void SendToFileAsync(SessionCriteria sessions, bool markAsRead, string fullFileNamePath)
{
m_Packager.SendToFile(sessions, markAsRead, fullFileNamePath, true);
}
/// <summary>
/// Asynchronously write the completed package to the provided full file name
/// (without extension) and path. The extension will be set to glp automatically.
/// </summary>
/// <remarks>The EndSend event will be raised when the send operation completes.
/// Any provided extension will be removed and replaced with the standard Loupe package extension.</remarks>
/// <param name="sessionMatchPredicate">A delegate to evaluate sessions and determine which ones to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="fullFileNamePath">The file name and path to write the final package to.</param>
/// <exception cref="ArgumentNullException">A required parameter was null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The provided file information is not a fully qualified file name and path.</exception>
public void SendToFileAsync(Predicate<SessionSummary> sessionMatchPredicate, bool markAsRead, string fullFileNamePath)
{
var predicateAdapter = new SessionSummaryPredicate(sessionMatchPredicate);
m_Packager.SendToFile(predicateAdapter.Predicate, markAsRead, fullFileNamePath, true);
}
/// <summary>Send sessions to a Loupe Server using the current agent configuration</summary>
/// <remarks>The EndSend event will be raised when the send operation completes. Because sessions are
/// sent one by one, they will be individually marked as read once sent.</remarks>
/// <overloads>Send sessions to the Loupe Server</overloads>
/// <param name="sessions">The set of match rules to apply to sessions to determine what to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="serverConfiguration">Optional. The connection options to use instead of the current configured server connection</param>
/// <exception cref="GibraltarException">The server couldn't be contacted or there was a communication error.</exception>
/// <exception cref="ArgumentException">The server configuration specified is invalid.</exception>
public void SendToServer(SessionCriteria sessions, bool markAsRead, ServerConfiguration serverConfiguration = null)
{
m_Packager.SendToServer(sessions, markAsRead, false, false, serverConfiguration);
}
/// <summary>Send sessions to a Loupe Server using the current agent configuration</summary>
/// <remarks>The EndSend event will be raised when the send operation completes. Because sessions are
/// sent one by one, they will be individually marked as read once sent.</remarks>
/// <overloads>Send sessions to the Loupe Server</overloads>
/// <param name="sessionMatchPredicate">A delegate to evaluate sessions and determine which ones to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="serverConfiguration">Optional. The connection options to use instead of the current configured server connection</param>
/// <exception cref="GibraltarException">The server couldn't be contacted or there was a communication error.</exception>
/// <exception cref="ArgumentException">The server configuration specified is invalid.</exception>
public void SendToServer(Predicate<SessionSummary> sessionMatchPredicate, bool markAsRead, ServerConfiguration serverConfiguration = null)
{
var predicateAdapter = new SessionSummaryPredicate(sessionMatchPredicate);
m_Packager.SendToServer(predicateAdapter.Predicate, markAsRead, false, false, serverConfiguration);
}
/// <summary>Send sessions to a Loupe Server using the current agent configuration</summary>
/// <remarks>The EndSend event will be raised when the send operation completes. Because sessions are
/// sent one by one, they will be individually marked as read once sent.</remarks>
/// <overloads>Send sessions to the Loupe Server</overloads>
/// <param name="sessions">The set of match rules to apply to sessions to determine what to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="purgeSentSessions">True to have every included session removed from the local repository upon successful completion.</param>
/// <param name="serverConfiguration">Optional. The connection options to use instead of the current configured server connection</param>
/// <exception cref="GibraltarException">The server couldn't be contacted or there was a communication error.</exception>
/// <exception cref="ArgumentException">The server configuration specified is invalid.</exception>
public void SendToServer(SessionCriteria sessions, bool markAsRead, bool purgeSentSessions, ServerConfiguration serverConfiguration = null)
{
m_Packager.SendToServer(sessions, markAsRead, purgeSentSessions, false, serverConfiguration);
}
/// <summary>Send sessions to a Loupe Server using the current agent configuration</summary>
/// <remarks>The EndSend event will be raised when the send operation completes. Because sessions are
/// sent one by one, they will be individually marked as read once sent.</remarks>
/// <overloads>Send sessions to the Loupe Server</overloads>
/// <param name="sessionMatchPredicate">A delegate to evaluate sessions and determine which ones to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="purgeSentSessions">True to have every included session removed from the local repository upon successful completion.</param>
/// <param name="serverConfiguration">Optional. The connection options to use instead of the current configured server connection</param>
/// <exception cref="GibraltarException">The server couldn't be contacted or there was a communication error.</exception>
/// <exception cref="ArgumentException">The server configuration specified is invalid.</exception>
public void SendToServer(Predicate<SessionSummary> sessionMatchPredicate, bool markAsRead, bool purgeSentSessions, ServerConfiguration serverConfiguration = null)
{
var predicateAdapter = new SessionSummaryPredicate(sessionMatchPredicate);
m_Packager.SendToServer(predicateAdapter.Predicate, markAsRead, purgeSentSessions, false, serverConfiguration);
}
/// <summary>
/// Asynchronously send sessions to a Loupe Server using the current agent configuration
/// </summary>
/// <param name="sessions">The set of match rules to apply to sessions to determine what to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="serverConfiguration">Optional. The connection options to use instead of the current configured server connection</param>
/// <remarks>The EndSend event will be raised when the send operation completes. Because sessions are
/// sent one by one, they will be individually marked as read once sent.</remarks>
public void SendToServerAsync(SessionCriteria sessions, bool markAsRead, ServerConfiguration serverConfiguration = null)
{
m_Packager.SendToServer(sessions, markAsRead, false, true, serverConfiguration);
}
/// <summary>
/// Asynchronously send sessions to a Loupe Server using the current agent configuration
/// </summary>
/// <param name="sessionMatchPredicate">A delegate to evaluate sessions and determine which ones to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="serverConfiguration">Optional. The connection options to use instead of the current configured server connection</param>
/// <remarks>The EndSend event will be raised when the send operation completes. Because sessions are
/// sent one by one, they will be individually marked as read once sent.</remarks>
public void SendToServerAsync(Predicate<SessionSummary> sessionMatchPredicate, bool markAsRead, ServerConfiguration serverConfiguration = null)
{
var predicateAdapter = new SessionSummaryPredicate(sessionMatchPredicate);
m_Packager.SendToServer(predicateAdapter.Predicate, markAsRead, false, true, serverConfiguration);
}
/// <summary>
/// Asynchronously send sessions to a Loupe Server using the current agent configuration
/// </summary>
/// <param name="sessions">The set of match rules to apply to sessions to determine what to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="purgeSentSessions">True to have every included session removed from the local repository upon successful completion.</param>
/// <param name="serverConfiguration">Optional. The connection options to use instead of the current configured server connection</param>
/// <remarks>The EndSend event will be raised when the send operation completes. Because sessions are
/// sent one by one, they will be individually marked as read once sent.</remarks>
public void SendToServerAsync(SessionCriteria sessions, bool markAsRead, bool purgeSentSessions, ServerConfiguration serverConfiguration = null)
{
m_Packager.SendToServer(sessions, markAsRead, purgeSentSessions, true, serverConfiguration);
}
/// <summary>
/// Asynchronously send sessions to a Loupe Server using the current agent configuration
/// </summary>
/// <param name="sessionMatchPredicate">A delegate to evaluate sessions and determine which ones to send.</param>
/// <param name="markAsRead">True to have every included session marked as read upon successful completion.</param>
/// <param name="purgeSentSessions">True to have every included session removed from the local repository upon successful completion.</param>
/// <param name="serverConfiguration">Optional. The connection options to use instead of the current configured server connection</param>
/// <remarks>The EndSend event will be raised when the send operation completes. Because sessions are
/// sent one by one, they will be individually marked as read once sent.</remarks>
public void SendToServerAsync(Predicate<SessionSummary> sessionMatchPredicate, bool markAsRead, bool purgeSentSessions, ServerConfiguration serverConfiguration = null)
{
var predicateAdapter = new SessionSummaryPredicate(sessionMatchPredicate);
m_Packager.SendToServer(predicateAdapter.Predicate, markAsRead, purgeSentSessions, true, serverConfiguration);
}
#endregion
#region Private Properties and Methods
private void Initialize()
{
m_Packager.BeginSend += m_Packager_BeginSend;
m_Packager.EndSend += m_Packager_EndSend;
}
/// <summary>
/// Performs the actual releasing of managed and unmanaged resources.
/// </summary>
/// <remarks>
/// Most usage should instead call Dispose(), which will call Dispose(true) for you
/// and will suppress redundant finalization.</remarks>
/// <param name="releaseManaged">Indicates whether to release managed resources.
/// This should only be called with true, except from the finalizer which should call Dispose(false).</param>
private void Dispose(bool releaseManaged)
{
if (!m_Disposed)
{
if (releaseManaged)
{
// Free managed resources here (normal Dispose() stuff, which should itself call Dispose(true))
// Other objects may be referenced in this case
if (m_Packager != null)
{
m_Packager.Dispose();
}
}
// Free native resources here (alloc's, etc)
// May be called from within the finalizer, so don't reference other objects here
m_Disposed = true; // Make sure we don't do it more than once
}
}
/// <summary>
/// Called to raise the BeginSend event at the start of the packaging and sending process (after all input is collected)
/// </summary>
/// <remarks>If overriding this method, be sure to call Base.OnBeginSend to ensure that the event is still raised to its caller.</remarks>
private void OnBeginSend()
{
//save the delegate field in a temporary field for thread safety
EventHandler tempEvent = BeginSend;
if (tempEvent != null)
{
tempEvent(this, new EventArgs());
}
}
/// <summary>
/// Called to raise the EndSend event at the end of the packaging and sending process with completion status information.
/// </summary>
/// <remarks>If overriding this method, be sure to call Base.OnBeginSend to ensure that the event is still raised to its caller.</remarks>
private void OnEndSend(PackageSendEventArgs e)
{
//save the delegate field in a temporary field for thread safety
PackageSendEventHandler tempEvent = EndSend;
if (tempEvent != null)
{
tempEvent(this, e);
}
}
#endregion
#region Event Handlers
private void m_Packager_EndSend(object sender, Gibraltar.Data.PackageSendEventArgs args)
{
//translate the args....
PackageSendEventArgs wrapperArgs = new PackageSendEventArgs(args);
OnEndSend(wrapperArgs);
}
private void m_Packager_BeginSend(object sender, EventArgs e)
{
OnBeginSend();
}
#endregion
}
/// <summary>
/// Used to provide information on the status of a package send.
/// </summary>
/// <param name="sender">The packager object raising the event</param>
/// <param name="e">The information on the package send event</param>
public delegate void PackageSendEventHandler(object sender, PackageSendEventArgs e);
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Google.Protobuf;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
using NUnit.Framework;
using Grpc.Testing;
namespace Grpc.IntegrationTesting
{
/// <summary>
/// Helper methods to start client runners for performance testing.
/// </summary>
public class ClientRunners
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientRunners>();
// Profilers to use for clients.
static readonly BlockingCollection<BasicProfiler> profilers = new BlockingCollection<BasicProfiler>();
internal static void AddProfiler(BasicProfiler profiler)
{
GrpcPreconditions.CheckNotNull(profiler);
profilers.Add(profiler);
}
/// <summary>
/// Creates a started client runner.
/// </summary>
public static IClientRunner CreateStarted(ClientConfig config)
{
Logger.Debug("ClientConfig: {0}", config);
if (config.AsyncClientThreads != 0)
{
Logger.Warning("ClientConfig.AsyncClientThreads is not supported for C#. Ignoring the value");
}
if (config.CoreLimit != 0)
{
Logger.Warning("ClientConfig.CoreLimit is not supported for C#. Ignoring the value");
}
if (config.CoreList.Count > 0)
{
Logger.Warning("ClientConfig.CoreList is not supported for C#. Ignoring the value");
}
var channels = CreateChannels(config.ClientChannels, config.ServerTargets, config.SecurityParams, config.ChannelArgs);
return new ClientRunnerImpl(channels,
config.ClientType,
config.RpcType,
config.OutstandingRpcsPerChannel,
config.LoadParams,
config.PayloadConfig,
config.HistogramParams,
() => GetNextProfiler());
}
private static List<Channel> CreateChannels(int clientChannels, IEnumerable<string> serverTargets, SecurityParams securityParams, IEnumerable<ChannelArg> channelArguments)
{
GrpcPreconditions.CheckArgument(clientChannels > 0, "clientChannels needs to be at least 1.");
GrpcPreconditions.CheckArgument(serverTargets.Count() > 0, "at least one serverTarget needs to be specified.");
var credentials = securityParams != null ? TestCredentials.CreateSslCredentials() : ChannelCredentials.Insecure;
var channelOptions = new List<ChannelOption>();
if (securityParams != null && securityParams.ServerHostOverride != "")
{
channelOptions.Add(new ChannelOption(ChannelOptions.SslTargetNameOverride, securityParams.ServerHostOverride));
}
foreach (var channelArgument in channelArguments)
{
channelOptions.Add(channelArgument.ToChannelOption());
}
var result = new List<Channel>();
for (int i = 0; i < clientChannels; i++)
{
var target = serverTargets.ElementAt(i % serverTargets.Count());
var channel = new Channel(target, credentials, channelOptions);
result.Add(channel);
}
return result;
}
private static BasicProfiler GetNextProfiler()
{
BasicProfiler result = null;
profilers.TryTake(out result);
return result;
}
}
internal class ClientRunnerImpl : IClientRunner
{
const double SecondsToNanos = 1e9;
readonly List<Channel> channels;
readonly ClientType clientType;
readonly RpcType rpcType;
readonly PayloadConfig payloadConfig;
readonly Lazy<byte[]> cachedByteBufferRequest;
readonly ThreadLocal<Histogram> threadLocalHistogram;
readonly List<Task> runnerTasks;
readonly CancellationTokenSource stoppedCts = new CancellationTokenSource();
readonly WallClockStopwatch wallClockStopwatch = new WallClockStopwatch();
readonly AtomicCounter statsResetCount = new AtomicCounter();
public ClientRunnerImpl(List<Channel> channels, ClientType clientType, RpcType rpcType, int outstandingRpcsPerChannel, LoadParams loadParams, PayloadConfig payloadConfig, HistogramParams histogramParams, Func<BasicProfiler> profilerFactory)
{
GrpcPreconditions.CheckArgument(outstandingRpcsPerChannel > 0, "outstandingRpcsPerChannel");
GrpcPreconditions.CheckNotNull(histogramParams, "histogramParams");
this.channels = new List<Channel>(channels);
this.clientType = clientType;
this.rpcType = rpcType;
this.payloadConfig = payloadConfig;
this.cachedByteBufferRequest = new Lazy<byte[]>(() => new byte[payloadConfig.BytebufParams.ReqSize]);
this.threadLocalHistogram = new ThreadLocal<Histogram>(() => new Histogram(histogramParams.Resolution, histogramParams.MaxPossible), true);
this.runnerTasks = new List<Task>();
foreach (var channel in this.channels)
{
for (int i = 0; i < outstandingRpcsPerChannel; i++)
{
var timer = CreateTimer(loadParams, 1.0 / this.channels.Count / outstandingRpcsPerChannel);
var optionalProfiler = profilerFactory();
this.runnerTasks.Add(RunClientAsync(channel, timer, optionalProfiler));
}
}
}
public ClientStats GetStats(bool reset)
{
var histogramData = new HistogramData();
foreach (var hist in threadLocalHistogram.Values)
{
hist.GetSnapshot(histogramData, reset);
}
var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds;
if (reset)
{
statsResetCount.Increment();
}
GrpcEnvironment.Logger.Info("[ClientRunnerImpl.GetStats] GC collection counts: gen0 {0}, gen1 {1}, gen2 {2}, (histogram reset count:{3}, seconds since reset: {4})",
GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), statsResetCount.Count, secondsElapsed);
// TODO: populate user time and system time
return new ClientStats
{
Latencies = histogramData,
TimeElapsed = secondsElapsed,
TimeUser = 0,
TimeSystem = 0
};
}
public async Task StopAsync()
{
stoppedCts.Cancel();
foreach (var runnerTask in runnerTasks)
{
await runnerTask;
}
foreach (var channel in channels)
{
await channel.ShutdownAsync();
}
}
private void RunUnary(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler)
{
if (optionalProfiler != null)
{
Profilers.SetForCurrentThread(optionalProfiler);
}
bool profilerReset = false;
var client = new BenchmarkService.BenchmarkServiceClient(channel);
var request = CreateSimpleRequest();
var stopwatch = new Stopwatch();
while (!stoppedCts.Token.IsCancellationRequested)
{
// after the first stats reset, also reset the profiler.
if (optionalProfiler != null && !profilerReset && statsResetCount.Count > 0)
{
optionalProfiler.Reset();
profilerReset = true;
}
stopwatch.Restart();
client.UnaryCall(request);
stopwatch.Stop();
// spec requires data point in nanoseconds.
threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
timer.WaitForNext();
}
}
private async Task RunUnaryAsync(Channel channel, IInterarrivalTimer timer)
{
var client = new BenchmarkService.BenchmarkServiceClient(channel);
var request = CreateSimpleRequest();
var stopwatch = new Stopwatch();
while (!stoppedCts.Token.IsCancellationRequested)
{
stopwatch.Restart();
await client.UnaryCallAsync(request);
stopwatch.Stop();
// spec requires data point in nanoseconds.
threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
await timer.WaitForNextAsync();
}
}
private async Task RunStreamingPingPongAsync(Channel channel, IInterarrivalTimer timer)
{
var client = new BenchmarkService.BenchmarkServiceClient(channel);
var request = CreateSimpleRequest();
var stopwatch = new Stopwatch();
using (var call = client.StreamingCall())
{
while (!stoppedCts.Token.IsCancellationRequested)
{
stopwatch.Restart();
await call.RequestStream.WriteAsync(request);
await call.ResponseStream.MoveNext();
stopwatch.Stop();
// spec requires data point in nanoseconds.
threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
await timer.WaitForNextAsync();
}
// finish the streaming call
await call.RequestStream.CompleteAsync();
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
}
private async Task RunGenericStreamingAsync(Channel channel, IInterarrivalTimer timer)
{
var request = cachedByteBufferRequest.Value;
var stopwatch = new Stopwatch();
var callDetails = new CallInvocationDetails<byte[], byte[]>(channel, GenericService.StreamingCallMethod, new CallOptions());
using (var call = Calls.AsyncDuplexStreamingCall(callDetails))
{
while (!stoppedCts.Token.IsCancellationRequested)
{
stopwatch.Restart();
await call.RequestStream.WriteAsync(request);
await call.ResponseStream.MoveNext();
stopwatch.Stop();
// spec requires data point in nanoseconds.
threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
await timer.WaitForNextAsync();
}
// finish the streaming call
await call.RequestStream.CompleteAsync();
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
}
private Task RunClientAsync(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler)
{
if (payloadConfig.PayloadCase == PayloadConfig.PayloadOneofCase.BytebufParams)
{
GrpcPreconditions.CheckArgument(clientType == ClientType.AsyncClient, "Generic client only supports async API");
GrpcPreconditions.CheckArgument(rpcType == RpcType.Streaming, "Generic client only supports streaming calls");
return RunGenericStreamingAsync(channel, timer);
}
GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams);
if (clientType == ClientType.SyncClient)
{
GrpcPreconditions.CheckArgument(rpcType == RpcType.Unary, "Sync client can only be used for Unary calls in C#");
// create a dedicated thread for the synchronous client
return Task.Factory.StartNew(() => RunUnary(channel, timer, optionalProfiler), TaskCreationOptions.LongRunning);
}
else if (clientType == ClientType.AsyncClient)
{
switch (rpcType)
{
case RpcType.Unary:
return RunUnaryAsync(channel, timer);
case RpcType.Streaming:
return RunStreamingPingPongAsync(channel, timer);
}
}
throw new ArgumentException("Unsupported configuration.");
}
private SimpleRequest CreateSimpleRequest()
{
GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams);
return new SimpleRequest
{
Payload = CreateZerosPayload(payloadConfig.SimpleParams.ReqSize),
ResponseSize = payloadConfig.SimpleParams.RespSize
};
}
private static Payload CreateZerosPayload(int size)
{
return new Payload { Body = ByteString.CopyFrom(new byte[size]) };
}
private static IInterarrivalTimer CreateTimer(LoadParams loadParams, double loadMultiplier)
{
switch (loadParams.LoadCase)
{
case LoadParams.LoadOneofCase.ClosedLoop:
return new ClosedLoopInterarrivalTimer();
case LoadParams.LoadOneofCase.Poisson:
return new PoissonInterarrivalTimer(loadParams.Poisson.OfferedLoad * loadMultiplier);
default:
throw new ArgumentException("Unknown load type");
}
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
namespace Ecosim.EcoScript.Eval
{
/**
* Simple C-like expression parser.
*/
public class Expression
{
public Expression ()
{
fnHandlers = new List<ProcessFnHandler> ();
varHandlers = new List<ProcessVarHandler> ();
}
public void AddFnHander (ProcessFnHandler fnHandler)
{
fnHandlers.Add (fnHandler);
}
public void AddVarHandler (ProcessVarHandler varHandler)
{
varHandlers.Add (varHandler);
}
public delegate object ProcessVarHandler (string id);
public delegate object ProcessFnHandler (string id,object[] args);
private List<ProcessFnHandler> fnHandlers;
private List<ProcessVarHandler> varHandlers;
private object DoEqualityOp (object lhs, object rhs, string op, int index)
{
if ((lhs is string) && (rhs is string)) {
if (op == "==")
return ((string)lhs) == ((string)rhs);
if (op == "!=")
return ((string)lhs) != ((string)rhs);
}
if ((lhs is bool) && (rhs is bool)) {
if (op == "==")
return ((bool)lhs) == ((bool)rhs);
if (op == "!=")
return ((bool)lhs) != ((bool)rhs);
}
if ((lhs is long) && (rhs is long)) {
if (op == "==")
return ((long)lhs) == ((long)rhs);
if (op == "!=")
return ((long)lhs) != ((long)rhs);
if (op == "<=")
return ((long)lhs) <= ((long)rhs);
if (op == ">=")
return ((long)lhs) >= ((long)rhs);
if (op == "<")
return ((long)lhs) < ((long)rhs);
if (op == ">")
return ((long)lhs) > ((long)rhs);
}
if ((lhs is double) && (rhs is double)) {
if (op == "==")
return ((double)lhs) == ((double)rhs);
if (op == "!=")
return ((double)lhs) != ((double)rhs);
if (op == "<=")
return ((double)lhs) <= ((double)rhs);
if (op == ">=")
return ((double)lhs) >= ((double)rhs);
if (op == "<")
return ((double)lhs) < ((double)rhs);
if (op == ">")
return ((double)lhs) > ((double)rhs);
}
throw new EvalException ("failed to execute '" + op + "' at " + (index + 1));
}
private object DoAdditiveOp (object lhs, object rhs, string op, int index)
{
if ((lhs is string) && (rhs is string)) {
if (op == "+")
return ((string)lhs) + ((string)rhs);
}
if ((lhs is long) && (rhs is long)) {
if (op == "+")
return ((long)lhs) + ((long)rhs);
if (op == "-")
return ((long)lhs) - ((long)rhs);
}
if ((lhs is double) && (rhs is double)) {
if (op == "+")
return ((double)lhs) + ((double)rhs);
if (op == "-")
return ((double)lhs) - ((double)rhs);
}
throw new EvalException ("failed to execute '" + op + "' at " + (index + 1));
}
private object DoMultiplicativeOp (object lhs, object rhs, string op, int index)
{
if ((lhs is long) && (rhs is long)) {
if (op == "*")
return ((long)lhs) * ((long)rhs);
if (op == "/")
return ((long)lhs) / ((long)rhs);
if (op == "%")
return ((long)lhs) % ((long)rhs);
}
if ((lhs is double) && (rhs is double)) {
if (op == "*")
return ((double)lhs) * ((double)rhs);
if (op == "/")
return ((double)lhs) / ((double)rhs);
}
throw new EvalException ("failed to execute '" + op + "' at " + (index + 1));
}
private object DoUnaryOp (object lhs, string op, int index)
{
if (lhs is bool) {
if (op == "!")
return !((bool)lhs);
}
if (lhs is long) {
if (op == "-")
return -((long)lhs);
}
if (lhs is double) {
if (op == "-")
return -((double)lhs);
}
throw new EvalException ("failed to execute '" + op + "' at " + (index + 1));
}
private object GetVariableValue (Id id)
{
string idStr = id.id;
foreach (ProcessVarHandler vh in varHandlers) {
object result = vh(idStr);
if (result != null) {
return result;
}
}
throw new EvalException ("unknown identifier '" + idStr + "'");
}
private object GetFunctionCall (Id id, object[] args)
{
string idStr = id.id;
foreach (ProcessFnHandler fh in fnHandlers) {
object result = fh(idStr, args);
if (result != null) {
return result;
}
}
throw new EvalException ("unknown or incorrect call to '" + idStr + "'");
}
private object ParseVarOrFunc (Tokenizer tokenizer)
{
Id id = (Id)tokenizer.NextToken ();
Symbol peek = tokenizer.PeekToken () as Symbol;
if ((peek != null) && (peek.symbol == "(")) {
tokenizer.NextToken ();
List<object> args = new List<object> ();
peek = tokenizer.PeekToken () as Symbol;
while ((peek == null) || (peek.symbol != ")")) {
args.Add (ParseExpression (tokenizer));
peek = tokenizer.PeekToken () as Symbol;
if ((peek == null) || ((peek.symbol != ")") && (peek.symbol != ","))) {
throw new EvalException ("incorrect function call of '" + id.id + "' at " + (tokenizer.Index + 1));
}
tokenizer.NextToken ();
}
return GetFunctionCall (id, args.ToArray ());
} else {
return GetVariableValue (id);
}
}
private object ParsePrimaryExpression (Tokenizer tokenizer)
{
if (tokenizer.IsEOT ()) {
throw new EvalException ("unexpected end of line");
}
Token peek = tokenizer.PeekToken ();
if (peek is Symbol) {
Symbol peekSymbol = (Symbol)peek;
if (peekSymbol.symbol == "(") {
int index = tokenizer.Index;
tokenizer.NextToken ();
object lhs = ParseExpression (tokenizer);
peekSymbol = tokenizer.PeekToken () as Symbol;
if ((peekSymbol != null) && (peekSymbol.symbol == ")")) {
tokenizer.NextToken ();
return lhs;
}
throw new EvalException ("Expected '(' unbalanced at " + (index + 1));
} else if ((peekSymbol.symbol == "-") || (peekSymbol.symbol == "!")) {
int index = tokenizer.Index;
tokenizer.NextToken ();
return DoUnaryOp (ParsePrimaryExpression (tokenizer), peekSymbol.symbol, index);
} else {
throw new EvalException ("Unexpected '" + peekSymbol.symbol + "' at " + (tokenizer.Index + 1));
}
} else if (peek is Id) {
return ParseVarOrFunc (tokenizer);
} else if (peek is StringConstant) {
tokenizer.NextToken ();
return ((StringConstant)peek).str;
} else if (peek is LongConstant) {
tokenizer.NextToken ();
return ((LongConstant)peek).longVal;
} else if (peek is DoubleConstant) {
tokenizer.NextToken ();
return ((DoubleConstant)peek).doubleVal;
} else {
throw new EvalException ("Unexpected error at " + (tokenizer.Index + 1));
}
}
private object ParseMultiplicativeExpression (Tokenizer tokenizer)
{
object lhs = ParsePrimaryExpression (tokenizer);
while (true) {
Symbol peek = tokenizer.PeekToken () as Symbol;
if (peek != null) {
if ((peek.symbol == "*") || (peek.symbol == "/") ||
(peek.symbol == "%")) {
int index = tokenizer.Index;
tokenizer.NextToken ();
object rhs = ParsePrimaryExpression (tokenizer);
lhs = DoMultiplicativeOp (lhs, rhs, peek.symbol, index);
} else {
return lhs;
}
} else {
return lhs;
}
}
}
private object ParseAdditiveExpression (Tokenizer tokenizer)
{
object lhs = ParseMultiplicativeExpression (tokenizer);
while (true) {
Symbol peek = tokenizer.PeekToken () as Symbol;
if (peek != null) {
if ((peek.symbol == "+") || (peek.symbol == "-")) {
int index = tokenizer.Index;
tokenizer.NextToken ();
object rhs = ParseMultiplicativeExpression (tokenizer);
lhs = DoAdditiveOp (lhs, rhs, peek.symbol, index);
} else {
return lhs;
}
} else {
return lhs;
}
}
}
private object ParseEqualityExpression (Tokenizer tokenizer)
{
object lhs = ParseAdditiveExpression (tokenizer);
while (true) {
Symbol peek = tokenizer.PeekToken () as Symbol;
if (peek != null) {
if ((peek.symbol == "==") || (peek.symbol == "!=") ||
(peek.symbol == "<=") || (peek.symbol == ">=") ||
(peek.symbol == "<") || (peek.symbol == ">")) {
int index = tokenizer.Index;
tokenizer.NextToken ();
object rhs = ParseAdditiveExpression (tokenizer);
lhs = DoEqualityOp (lhs, rhs, peek.symbol, index);
} else {
return lhs;
}
} else {
return lhs;
}
}
}
private object ParseExpression (Tokenizer tokenizer)
{
return ParseEqualityExpression (tokenizer);
}
/**
* Parses expression in str and if valid, returns result.
* result can be a bool, string, long or double
* on error parsing an EvalException can be thrown.
* other exceptions can occur during execution of expression (like when dividing by 0)
*/
public object Parse (string str)
{
Tokenizer tokenizer = new Tokenizer (str);
object result = ParseExpression (tokenizer);
if (!tokenizer.IsEOT ()) {
throw new EvalException ("Unexpected garbage after expression at " + (tokenizer.Index + 1));
}
return result;
}
/**
* Parses str. str can contain embedded expressions, using the '[' ']' chars.
* e.g. "Text [1+4]!" would result in "Text 5!", special cases are "[[" resulting in "["
* and "[]" resulting in "[]". EvalExceptions can occur if expression is invalid, other
* exceptions can occur during execution of expression.
* if noExceptions is true errors in parsing won't result in exceptions thrown.
*/
public string ParseAndSubstitute (string str, bool noExceptions)
{
if (str.IndexOf ('[') < 0) {
return str; // no '[', so certainly nothing to substitute
}
Tokenizer tokenizer = new Tokenizer (str);
StringBuilder builder = new StringBuilder (str.Length + 32);
while (!tokenizer.IsEOT ()) {
char nextChar = tokenizer.NextChar ();
if (nextChar == '[') {
if (tokenizer.PeekChar () == '[') {
tokenizer.NextChar ();
builder.Append ('['); // we recognise '[[' as '['
} else if (tokenizer.PeekChar () == ']') {
tokenizer.NextChar ();
builder.Append ("[]"); // we recognise '[]' as '[]'
} else {
// we got an expression...
try {
object result = ParseExpression (tokenizer);
builder.Append (result.ToString ());
}
catch (Exception e) {
Log.LogException (e);
builder.Append ("<error>");
}
tokenizer.SkipWhiteSpace ();
if (tokenizer.PeekChar () != ']') {
if (noExceptions) {
builder.Append ("<Missing ']'>");
}
else {
throw new EvalException ("expected ']' at " + (tokenizer.Index + 1));
}
}
else {
tokenizer.NextChar ();
}
}
} else {
builder.Append (nextChar);
}
}
return builder.ToString ();
}
}
}
| |
/*
Copyright (c) 2009, hkrn All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. Redistributions in binary
form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials
provided with the distribution. Neither the name of the hkrn 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 REGENTS 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.
*/
//
// $Id: Track.cs 138 2009-08-22 13:31:42Z hikarin $
//
using System;
using System.Collections.Generic;
//using System.Windows;
namespace SlMML
{
public class Track
{
#region constants
public const int TEMPO_TRACK = 0;
public const int FIRST_TRACK = 1;
#endregion
#region constructors and destructor
public Track()
{
End = false;
m_channel = new Channel();
m_events = new List<Events.Event>(32);
m_index = 0;
m_delta = 0;
GlobalTick = 0;
m_needle = 0.0;
#if true
Duration = TimeSpan.FromMilliseconds(0);
#else
Duration = new Duration(TimeSpan.FromMilliseconds(0));
#endif
BPM = DEFAULT_BPM;
RecordGate(15.0 / 16.0);
RecordGate(0);
}
#endregion
#region public methods
public void GetSamples(ref double[] samples, int start, int end, bool update)
{
if (End)
return;
int eventCount = m_events.Count, i = start;
while (i < end)
{
bool loop = false;
double delta = 0;
do
{
loop = false;
if (m_index < eventCount)
{
Events.Event e = m_events[m_index];
delta = e.Delta * m_spt;
if (m_needle >= delta)
{
loop = true;
if (e is Events.NoteOn)
m_channel.EnableNote((Events.NoteOn)e);
else if (e is Events.NoteOff)
m_channel.DisableNote();
else if (e is Events.Note)
m_channel.NoteIndex = ((Events.Note)(e)).Index;
else if (e is Events.Tempo)
BPM = ((Events.Tempo)e).Value;
else if (e is Events.Form)
m_channel.Form = (Events.Form)e;
else if (e is Events.VCO)
m_channel.ADSRForVCO = (Events.VCO)e;
else if (e is Events.VCF)
m_channel.ADSRForVCF = (Events.VCF)e;
else if (e is Events.NoiseFrequency)
m_channel.NoiseFrequency = ((Events.NoiseFrequency)e).Value;
else if (e is Events.PWM)
m_channel.PWM = ((Events.PWM)e).Value;
else if (e is Events.Pan)
m_channel.Pan = ((Events.Pan)e).Value;
else if (e is Events.Vowel)
m_channel.FormantVowel = ((Events.Vowel)e).Value;
else if (e is Events.Detune)
m_channel.Detune = ((Events.Detune)e).Value;
else if (e is Events.LFO)
{
Events.LFO lfo = (Events.LFO)e;
double width = lfo.Width * m_spt;
lfo.Delay = (int)(lfo.Delay * m_spt);
lfo.Time = (int)(lfo.Time * width);
m_channel.SetLFO(lfo, Sample.RATE / width);
}
else if (e is Events.LPF)
m_channel.LPF = (Events.LPF)e;
else if (e is Events.VolumeMode)
m_channel.VolumeMode = ((Events.VolumeMode)e).Value;
else if (e is Events.Input)
m_channel.Input = (Events.Input)e;
else if (e is Events.Output)
m_channel.Output = (Events.Output)e;
else if (e is Events.Expression)
m_channel.Expression = ((Events.Expression)e).Value;
else if (e is Events.Ring)
m_channel.Ring = (Events.Ring)e;
else if (e is Events.Sync)
m_channel.Sync = (Events.Sync)e;
else if (e is Events.Close)
m_channel.Close();
else if (e is Events.Eot)
End = true;
m_needle -= delta;
m_index++;
}
}
}
while (loop);
int di = 0;
if (m_index < eventCount)
{
Events.Event e = m_events[m_index];
delta = e.Delta * m_spt;
di = (int)Math.Ceiling(delta - m_needle);
if (i + di >= end)
di = end - i;
m_needle += di;
if (update)
m_channel.GetSamples(ref samples, i, di, end);
i += di;
}
else
break;
}
}
public void Seek()
{
GlobalTick = 0;
}
public void Seek(int delta)
{
m_delta += delta;
GlobalTick += (uint)delta;
}
public void RecordNote(int index, int length, int velocity, bool keyOn, bool keyOff)
{
Events.Event e;
if (keyOn)
e = new Events.NoteOn() { Index = index, Velocity = velocity };
else
e = new Events.Note() { Index = index };
SetDeltaAndAddEvent(e);
if (keyOff)
{
int gate = Math.Max((int)(length * m_gate - m_gate2), 0);
Seek(gate);
e = new Events.NoteOff() { Index = index, Velocity = velocity };
SetDeltaAndAddEvent(e);
Seek(length - gate);
}
else
Seek(length);
}
public void RecordRest(int length)
{
Seek(length);
}
public void RecordRest(uint msec)
{
int length = (int)(msec * Sample.RATE / (m_spt * 1000));
Seek(length);
}
public void RecordVolume(int volume)
{
Events.Volume e = new Events.Volume() { Value = volume };
SetDeltaAndAddEvent(e);
}
public void RecordTempo(int tempo, uint globalTick)
{
Events.Tempo e = new Events.Tempo() { Value = tempo };
SetDelta(e);
RecordGlobalTick(globalTick, e);
}
public void RecordEOT()
{
Events.Eot e = new Events.Eot() { Delta = m_delta };
SetDeltaAndAddEvent(e);
}
public void RecordGate(double gate)
{
m_gate = gate;
}
public void RecordGate(int gate)
{
m_gate2 = Math.Max(gate, 0);
}
public void RecordForm(OscillatorForm form, OscillatorForm subform)
{
Events.Form e = new Events.Form() { Main = form, Sub = subform };
SetDeltaAndAddEvent(e);
}
public void RecordNoiseFrequency(int frequency)
{
Events.NoiseFrequency e = new Events.NoiseFrequency() { Value = frequency };
SetDeltaAndAddEvent(e);
}
public void RecordPWM(int pwm)
{
Events.PWM e = new Events.PWM() { Value = pwm };
SetDeltaAndAddEvent(e);
}
public void RecordPan(int pan)
{
Events.Pan e = new Events.Pan() { Value = pan };
SetDeltaAndAddEvent(e);
}
public void RecordFormantVowel(FormantVowel vowel)
{
Events.Vowel e = new Events.Vowel() { Value = vowel };
SetDeltaAndAddEvent(e);
}
public void RecordDetune(int detune)
{
Events.Detune e = new Events.Detune() { Value = detune };
SetDeltaAndAddEvent(e);
}
public void RecordLFO(OscillatorForm form, OscillatorForm subform, int depth, int width, int delay, int time, bool reverse)
{
Events.LFO e = new Events.LFO()
{
Main = form,
Sub = subform,
Depth = depth,
Width = width,
Delay = delay,
Time = time,
Reverse = reverse
};
SetDeltaAndAddEvent(e);
}
public void RecordLPF(FilterType sw, int amount, int frequency, int resonance)
{
Events.LPF e = new Events.LPF()
{
Switch = sw,
Amount = amount,
Frequency = frequency,
Resonance = resonance
};
SetDeltaAndAddEvent(e);
}
public void RecordVolumeMode(int mode)
{
Events.VolumeMode e = new Events.VolumeMode() { Value = mode };
SetDeltaAndAddEvent(e);
}
public void RecordInput(int inSens, int pipe)
{
Events.Input e = new Events.Input() { Sens = inSens, Pipe = pipe };
SetDeltaAndAddEvent(e);
}
public void RecordOutput(ChannelOutputMode mode, int pipe)
{
Events.Output e = new Events.Output() { Mode = mode, Pipe = pipe };
SetDeltaAndAddEvent(e);
}
public void RecordExpression(int expression)
{
Events.Expression e = new Events.Expression() { Value = expression };
SetDeltaAndAddEvent(e);
}
public void RecordRing(int inSens, int pipe)
{
Events.Ring e = new Events.Ring() { Sens = inSens, Pipe = pipe };
SetDeltaAndAddEvent(e);
}
public void RecordSync(ChannelOutputMode mode, int pipe)
{
Events.Sync e = new Events.Sync() { Mode = mode, Pipe = pipe };
SetDeltaAndAddEvent(e);
}
public void RecordClose()
{
Events.Close e = new Events.Close();
SetDeltaAndAddEvent(e);
}
public void RecordEnvelopeADSR(int attack, int decay, int sustain, int release, bool isVCO)
{
Events.Event e;
if (isVCO)
e = new Events.VCO()
{
Delta = m_delta,
Attack = attack,
Decay = decay,
Sustain = sustain,
Release = release
};
else
e = new Events.VCF()
{
Delta = m_delta,
Attack = attack,
Decay = decay,
Sustain = sustain,
Release = release
};
SetDeltaAndAddEvent(e);
}
public void ConductTracks(IList<Track> tracks)
{
int ni = m_events.Count;
int nj = tracks.Count;
uint globalSample = 0, globalTick = 0;
double spt = CalculateSPT(DEFAULT_BPM);
for (int i = 0; i < ni; i++)
{
Events.Event e = m_events[i];
uint delta = (uint)e.Delta;
globalTick += delta;
globalSample += (uint)(delta * spt);
Events.Tempo tempo = e as Events.Tempo;
if (tempo != null)
{
int tempoValue = tempo.Value;
for (int j = FIRST_TRACK; j < nj; j++)
{
Track track = tracks[j];
track.RecordTempo(tempoValue, globalTick);
spt = CalculateSPT(tempoValue);
}
}
}
uint maxGlobalTick = 0;
for (int j = FIRST_TRACK; j < nj; j++)
{
Track track = tracks[j];
uint trackGlobalTick = track.GlobalTick;
if (maxGlobalTick < trackGlobalTick)
maxGlobalTick = trackGlobalTick;
}
Events.Close close = new Events.Close();
RecordGlobalTick(maxGlobalTick, close);
globalSample += (uint)((maxGlobalTick - globalTick) * spt);
RecordRest((uint)3000);
RecordEOT();
globalSample += (uint)(3 * Sample.RATE);
#if true
Duration = TimeSpan.FromMilliseconds(globalSample * (1000.0 / Sample.RATE));
#else
Duration = new Duration(TimeSpan.FromMilliseconds(globalSample * (1000.0 / Sample.RATE)));
#endif
}
#endregion
#region nonpublic methods
private void RecordGlobalTick(uint globalTick, Events.Event e)
{
int eventCount = m_events.Count;
uint preGlobalTick = 0;
for (int i = 0; i < eventCount; i++)
{
Events.Event ev = m_events[i];
uint nextTick = (uint)(preGlobalTick + ev.Delta);
if (nextTick >= globalTick)
{
ev.Delta = (int)(nextTick - globalTick);
e.Delta = (int)(globalTick - preGlobalTick);
m_events.Insert(i, e);
return;
}
preGlobalTick = nextTick;
}
e.Delta = (int)(globalTick - preGlobalTick);
AddEvent(e);
}
private void SetDeltaAndAddEvent(Events.Event e)
{
SetDelta(e);
AddEvent(e);
}
private void SetDelta(Events.Event e)
{
e.Delta = m_delta;
m_delta = 0;
}
private void AddEvent(Events.Event e)
{
m_events.Add(e);
}
private double CalculateSPT(double bpm)
{
return Sample.RATE / (bpm * 96.0 / 60.0);
}
#if DEBUG
internal List<Dictionary<string, string>> Dump()
{
List<Dictionary<string, string>> r = new List<Dictionary<string, string>>();
foreach (Events.Event e in m_events)
{
Dictionary<string, string> data = new Dictionary<string, string>();
data["status"] = e.GetType().Name;
if (e is Events.NoteOn)
{
Events.NoteOn noteOn = (Events.NoteOn)e;
data["index"] = noteOn.Index.ToString();
data["velocity"] = noteOn.Velocity.ToString();
}
else if (e is Events.Note)
data["index"] = ((Events.Note)(e)).Index.ToString();
else if (e is Events.Tempo)
data["bpm"] = ((Events.Tempo)e).Value.ToString();
else if (e is Events.Form)
{
Events.Form form = (Events.Form)e;
data["form"] = ((int)form.Main).ToString();
data["subform"] = ((int)form.Sub).ToString();
}
else if (e is Events.VCO)
{
Events.VCO vco = (Events.VCO)e;
data["attack"] = vco.Attack.ToString();
data["decay"] = vco.Decay.ToString();
r.Add(data);
data = new Dictionary<string, string>();
data["status"] = "VCO";
data["sustain"] = vco.Sustain.ToString();
data["release"] = vco.Release.ToString();
}
else if (e is Events.VCF)
{
Events.VCF vcf = (Events.VCF)e;
data["attack"] = vcf.Attack.ToString();
data["decay"] = vcf.Decay.ToString();
r.Add(data);
data = new Dictionary<string, string>();
data["status"] = "VCF";
data["sustain"] = vcf.Sustain.ToString();
data["release"] = vcf.Release.ToString();
}
else if (e is Events.NoiseFrequency)
data["frequency"] = ((Events.NoiseFrequency)e).Value.ToString();
else if (e is Events.PWM)
data["pwm"] = ((Events.PWM)e).Value.ToString();
else if (e is Events.Pan)
data["pan"] = ((Events.Pan)e).Value.ToString();
else if (e is Events.Vowel)
data["formant"] = ((int)((Events.Vowel)e).Value).ToString();
else if (e is Events.Detune)
data["detune"] = ((Events.Detune)e).Value.ToString();
else if (e is Events.LFO)
{
Events.LFO lfo = (Events.LFO)e;
int rv = lfo.Reverse ? -1 : 1;
data["form"] = ((int)lfo.Main * rv).ToString();
data["subform"] = ((int)lfo.Sub).ToString();
r.Add(data);
double width = lfo.Width * m_spt;
data = new Dictionary<string, string>();
data["status"] = "LFO";
data["depth"] = lfo.Depth.ToString();
//data["width"] = (Sample.RATE / width).ToString();
r.Add(data);
data = new Dictionary<string, string>();
data["status"] = "LFO";
data["delay"] = ((lfo.Delay * m_spt)).ToString();
//data["time"] = ((lfo.Time * lfo.Width)).ToString();
}
else if (e is Events.LPF)
{
Events.LPF lpf = (Events.LPF)e;
data["switch"] = ((int)lpf.Switch).ToString();
data["amount"] = lpf.Amount.ToString();
r.Add(data);
data = new Dictionary<string, string>();
data["status"] = "LPF";
data["frequency"] = lpf.Frequency.ToString();
data["resonance"] = lpf.Resonance.ToString();
}
else if (e is Events.VolumeMode)
data["volumeMode"] = ((Events.VolumeMode)e).Value.ToString();
else if (e is Events.Input)
{
Events.Input input = (Events.Input)e;
data["sens"] = input.Sens.ToString();
data["pipe"] = input.Pipe.ToString();
}
else if (e is Events.Output)
{
Events.Output output = (Events.Output)e;
data["mode"] = ((int)output.Mode).ToString();
data["pipe"] = output.Pipe.ToString();
}
else if (e is Events.Expression)
data["expression"] = ((Events.Expression)e).Value.ToString();
else if (e is Events.Ring)
{
Events.Ring ring = (Events.Ring)e;
data["sens"] = ring.Sens.ToString();
data["pipe"] = ring.Pipe.ToString();
}
else if (e is Events.Output)
{
Events.Sync sync = (Events.Sync)e;
data["mode"] = ((int)sync.Mode).ToString();
data["pipe"] = sync.Pipe.ToString();
}
r.Add(data);
}
return r;
}
#endif
#endregion
#region public properties
public bool End
{
get;
private set;
}
public uint GlobalTick
{
get;
private set;
}
#if true
public TimeSpan Duration
{
get;
private set;
}
#else
public Duration Duration
{
get;
private set;
}
#endif
public double BPM
{
get
{
return m_bpm;
}
set
{
m_bpm = value;
m_spt = CalculateSPT(value);
}
}
public int EventCount
{
get
{
return m_events.Count;
}
}
public Dictionary<int,int> DeltasToSeek
{
get
{
Dictionary<int, int> r = new Dictionary<int, int>();
int delta = 0, i = 0;
foreach (Events.Event e in m_events)
{
r[delta] = i;
delta += e.Delta;
i++;
}
return r;
}
}
#endregion
#region member variables
public static readonly int DEFAULT_BPM = 120;
private Channel m_channel;
private List<Events.Event> m_events;
private int m_index;
private int m_delta;
private double m_bpm;
private double m_spt;
private double m_needle;
private double m_gate;
private double m_gate2;
#endregion
}
}
| |
//
// SourceWatcher.cs
//
// Authors:
// Christian Martellini <[email protected]>
// Alexander Kojevnikov <[email protected]>
//
// Copyright (C) 2009 Christian Martellini
// Copyright (C) 2009 Alexander Kojevnikov
//
// 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.Linq;
using System.Threading;
using System.Collections.Generic;
using Hyena;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Library;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Streaming;
namespace Banshee.LibraryWatcher
{
public class SourceWatcher : IDisposable
{
private readonly LibraryImportManager import_manager;
private readonly LibrarySource library;
private readonly FileSystemWatcher watcher;
private readonly ManualResetEvent handle;
private readonly Thread watch_thread;
private readonly Queue<QueueItem> queue = new Queue<QueueItem> ();
private readonly TimeSpan delay = TimeSpan.FromMilliseconds (1000);
private bool active;
private bool disposed;
private class QueueItem
{
public DateTime When;
public WatcherChangeTypes ChangeType;
public string OldFullPath;
public string FullPath;
public string MetadataHash;
}
public SourceWatcher (LibrarySource library)
{
this.library = library;
handle = new ManualResetEvent(false);
string path = library.BaseDirectoryWithSeparator;
string home = Environment.GetFolderPath (Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
if (path == home) {
throw new Exception ("Will not create LibraryWatcher for the entire home directory");
}
import_manager = ServiceManager.Get<LibraryImportManager> ();
watcher = new FileSystemWatcher (path);
watcher.IncludeSubdirectories = true;
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnChanged;
active = true;
watch_thread = new Thread (new ThreadStart (Watch));
watch_thread.Name = String.Format ("LibraryWatcher for {0}", library.Name);
watch_thread.IsBackground = true;
watch_thread.Start ();
}
#region Public Methods
public void Dispose ()
{
if (!disposed) {
active = false;
watcher.Changed -= OnChanged;
watcher.Created -= OnChanged;
watcher.Deleted -= OnChanged;
watcher.Renamed -= OnChanged;
lock (queue) {
queue.Clear ();
}
watcher.Dispose ();
disposed = true;
}
}
#endregion
#region Private Methods
private void OnChanged (object source, FileSystemEventArgs args)
{
var item = new QueueItem {
When = DateTime.Now,
ChangeType = args.ChangeType,
FullPath = args.FullPath,
OldFullPath = args is RenamedEventArgs ? ((RenamedEventArgs)args).OldFullPath : args.FullPath
};
lock (queue) {
queue.Enqueue (item);
}
handle.Set ();
if (args.ChangeType != WatcherChangeTypes.Changed) {
Hyena.Log.DebugFormat ("Watcher: {0} {1}{2}",
item.ChangeType, args is RenamedEventArgs ? item.OldFullPath + " => " : "", item.FullPath);
}
}
private void Watch ()
{
watcher.EnableRaisingEvents = true;
while (active) {
WatcherChangeTypes change_types = 0;
while (queue.Count > 0) {
QueueItem item;
lock (queue) {
item = queue.Dequeue ();
}
int sleep = (int) (item.When + delay - DateTime.Now).TotalMilliseconds;
if (sleep > 0) {
Hyena.Log.DebugFormat ("Watcher: sleeping {0}ms", sleep);
Thread.Sleep (sleep);
}
if (item.ChangeType == WatcherChangeTypes.Changed) {
UpdateTrack (item.FullPath);
} else if (item.ChangeType == WatcherChangeTypes.Created) {
AddTrack (item.FullPath);
} else if (item.ChangeType == WatcherChangeTypes.Deleted) {
RemoveTrack (item.FullPath);
} else if (item.ChangeType == WatcherChangeTypes.Renamed) {
RenameTrack (item.OldFullPath, item.FullPath);
}
change_types |= item.ChangeType;
}
if ((change_types & WatcherChangeTypes.Deleted) > 0) {
library.NotifyTracksDeleted ();
}
if ((change_types & (WatcherChangeTypes.Renamed |
WatcherChangeTypes.Created | WatcherChangeTypes.Changed)) > 0) {
library.NotifyTracksChanged ();
}
handle.WaitOne ();
handle.Reset ();
}
}
private void UpdateTrack (string track)
{
using (var reader = ServiceManager.DbConnection.Query (
DatabaseTrackInfo.Provider.CreateFetchCommand (
"CoreTracks.PrimarySourceID = ? AND CoreTracks.Uri = ? LIMIT 1"), library.DbId, new SafeUri (track).AbsoluteUri)) {
if (reader.Read ()) {
var track_info = DatabaseTrackInfo.Provider.Load (reader);
if (Banshee.IO.File.GetModifiedTime (track_info.Uri) > track_info.FileModifiedStamp) {
using (var file = StreamTagger.ProcessUri (track_info.Uri)) {
StreamTagger.TrackInfoMerge (track_info, file, false);
}
track_info.LastSyncedStamp = DateTime.Now;
track_info.Save (false);
}
}
}
}
private void AddTrack (string track)
{
import_manager.ImportTrack (track);
// Trigger file rename.
string uri = new SafeUri(track).AbsoluteUri;
HyenaSqliteCommand command = new HyenaSqliteCommand (@"
UPDATE CoreTracks
SET DateUpdatedStamp = LastSyncedStamp + 1
WHERE Uri = ?", uri);
ServiceManager.DbConnection.Execute (command);
}
private void RemoveTrack (string track)
{
string uri = new SafeUri(track).AbsoluteUri;
const string hash_sql = @"SELECT TrackID, MetadataHash FROM CoreTracks WHERE Uri = ? LIMIT 1";
int track_id = 0;
string hash = null;
using (var reader = new HyenaDataReader (ServiceManager.DbConnection.Query (hash_sql, uri))) {
if (reader.Read ()) {
track_id = reader.Get<int> (0);
hash = reader.Get<string> (1);
}
}
if (hash != null) {
lock (queue) {
var item = queue.FirstOrDefault (
i => i.ChangeType == WatcherChangeTypes.Created && GetMetadataHash (i) == hash);
if (item != null) {
item.ChangeType = WatcherChangeTypes.Renamed;
item.OldFullPath = track;
return;
}
}
}
const string delete_sql = @"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri)
SELECT ?, TrackID, Uri FROM CoreTracks WHERE TrackID IN ({0})
;
DELETE FROM CoreTracks WHERE TrackID IN ({0})";
// If track_id is 0, it's a directory.
HyenaSqliteCommand delete_command;
if (track_id > 0) {
delete_command = new HyenaSqliteCommand (String.Format (delete_sql,
"?"), DateTime.Now, track_id, track_id);
} else {
string pattern = StringUtil.EscapeLike (uri) + "/_%";
delete_command = new HyenaSqliteCommand (String.Format (delete_sql,
@"SELECT TrackID FROM CoreTracks WHERE Uri LIKE ? ESCAPE '\'"), DateTime.Now, pattern, pattern);
}
ServiceManager.DbConnection.Execute (delete_command);
}
private void RenameTrack(string oldFullPath, string fullPath)
{
if (oldFullPath == fullPath) {
// FIXME: bug in Mono, see bnc#322330
return;
}
string old_uri = new SafeUri (oldFullPath).AbsoluteUri;
string new_uri = new SafeUri (fullPath).AbsoluteUri;
string pattern = StringUtil.EscapeLike (old_uri) + "%";
HyenaSqliteCommand rename_command = new HyenaSqliteCommand (@"
UPDATE CoreTracks
SET Uri = REPLACE(Uri, ?, ?), DateUpdatedStamp = ?
WHERE Uri LIKE ? ESCAPE '\'",
old_uri, new_uri, DateTime.Now, pattern);
ServiceManager.DbConnection.Execute (rename_command);
}
private string GetMetadataHash (QueueItem item)
{
if (item.ChangeType == WatcherChangeTypes.Created && item.MetadataHash == null) {
var uri = new SafeUri (item.FullPath);
if (DatabaseImportManager.IsWhiteListedFile (item.FullPath) && Banshee.IO.File.Exists (uri)) {
var track = new TrackInfo ();
using (var file = StreamTagger.ProcessUri (uri)) {
StreamTagger.TrackInfoMerge (track, file);
}
item.MetadataHash = track.MetadataHash;
}
}
return item.MetadataHash;
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.OpenSsl
{
/// <remarks>General purpose writer for OpenSSL PEM objects.</remarks>
public class PemWriter
{
private readonly TextWriter writer;
public TextWriter Writer
{
get { return writer; }
}
/// <param name="writer">The TextWriter object to write the output to.</param>
public PemWriter(
TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
this.writer = writer;
}
public void WriteObject(
object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
string type;
byte[] encoding;
if (obj is X509Certificate)
{
// TODO Should we prefer "X509 CERTIFICATE" here?
type = "CERTIFICATE";
try
{
encoding = ((X509Certificate)obj).GetEncoded();
}
catch (CertificateEncodingException e)
{
throw new IOException("Cannot Encode object: " + e.ToString());
}
}
else if (obj is X509Crl)
{
type = "X509 CRL";
try
{
encoding = ((X509Crl)obj).GetEncoded();
}
catch (CrlException e)
{
throw new IOException("Cannot Encode object: " + e.ToString());
}
}
else if (obj is AsymmetricCipherKeyPair)
{
WriteObject(((AsymmetricCipherKeyPair)obj).Private);
return;
}
else if (obj is AsymmetricKeyParameter)
{
AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj;
if (akp.IsPrivate)
{
string keyType;
encoding = EncodePrivateKey(akp, out keyType);
type = keyType + " PRIVATE KEY";
}
else
{
type = "PUBLIC KEY";
encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded();
}
}
else if (obj is IX509AttributeCertificate)
{
type = "ATTRIBUTE CERTIFICATE";
encoding = ((X509V2AttributeCertificate)obj).GetEncoded();
}
else if (obj is Pkcs10CertificationRequest)
{
type = "CERTIFICATE REQUEST";
encoding = ((Pkcs10CertificationRequest)obj).GetEncoded();
}
else if (obj is Asn1.Cms.ContentInfo)
{
type = "PKCS7";
encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded();
}
else
{
throw new ArgumentException("Object type not supported: " + obj.GetType().FullName, "obj");
}
WritePemBlock(type, encoding);
}
public void WriteObject(
object obj,
string algorithm,
char[] password,
SecureRandom random)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (algorithm == null)
throw new ArgumentNullException("algorithm");
if (password == null)
throw new ArgumentNullException("password");
if (random == null)
throw new ArgumentNullException("random");
if (obj is AsymmetricCipherKeyPair)
{
WriteObject(((AsymmetricCipherKeyPair) obj).Private, algorithm, password, random);
return;
}
string type = null;
byte[] keyData = null;
if (obj is AsymmetricKeyParameter)
{
AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj;
if (akp.IsPrivate)
{
string keyType;
keyData = EncodePrivateKey(akp, out keyType);
type = keyType + " PRIVATE KEY";
}
}
if (type == null || keyData == null)
{
// TODO Support other types?
throw new ArgumentException("Object type not supported: " + obj.GetType().FullName, "obj");
}
string dekAlgName = algorithm.ToUpper(CultureInfo.InvariantCulture);
// Note: For backward compatibility
if (dekAlgName == "DESEDE")
{
dekAlgName = "DES-EDE3-CBC";
}
int ivLength = dekAlgName.StartsWith("AES-") ? 16 : 8;
byte[] iv = new byte[ivLength];
random.NextBytes(iv);
byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv);
byte[] hexIV = Hex.Encode(iv);
WritePemBlock(type, encData,
"Proc-Type: 4,ENCRYPTED",
"DEK-Info: " + dekAlgName + "," + Encoding.ASCII.GetString(hexIV, 0, hexIV.Length));
}
private byte[] EncodePrivateKey(
AsymmetricKeyParameter akp,
out string keyType)
{
PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp);
DerObjectIdentifier oid = info.AlgorithmID.ObjectID;
if (oid.Equals(X9ObjectIdentifiers.IdDsa))
{
keyType = "DSA";
DsaParameter p = DsaParameter.GetInstance(info.AlgorithmID.Parameters);
BigInteger x = ((DsaPrivateKeyParameters) akp).X;
BigInteger y = p.G.ModPow(x, p.P);
// TODO Create an ASN1 object somewhere for this?
return new DerSequence(
new DerInteger(0),
new DerInteger(p.P),
new DerInteger(p.Q),
new DerInteger(p.G),
new DerInteger(y),
new DerInteger(x)).GetEncoded();
}
if (oid.Equals(PkcsObjectIdentifiers.RsaEncryption))
{
keyType = "RSA";
}
else if (oid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)
|| oid.Equals(X9ObjectIdentifiers.IdECPublicKey))
{
keyType = "EC";
}
else
{
throw new ArgumentException("Cannot handle private key of type: " + akp.GetType().FullName, "akp");
}
return info.PrivateKey.GetEncoded();
}
private void WritePemBlock(
string type,
byte[] data,
params string[] fields)
{
WriteHeader(type);
if (fields.Length > 0)
{
foreach (string field in fields)
{
writer.WriteLine(field);
}
writer.WriteLine();
}
WriteBytes(Base64.Encode(data));
WriteFooter(type);
}
private void WriteHeader(
string type)
{
writer.WriteLine("-----BEGIN " + type + "-----");
}
private void WriteFooter(
string type)
{
writer.WriteLine("-----END " + type + "-----");
}
private const int LineLength = 64;
private void WriteBytes(
byte[] bytes)
{
int pos = 0;
int remaining = bytes.Length;
char[] buf = new char[LineLength];
while (remaining > LineLength)
{
Encoding.ASCII.GetChars(bytes, pos, LineLength, buf, 0);
writer.WriteLine(buf);
pos += LineLength;
remaining -= LineLength;
}
Encoding.ASCII.GetChars(bytes, pos, remaining, buf, 0);
writer.WriteLine(buf, 0, remaining);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System.Reflection;
using System.Collections;
using System.Xml.Schema;
using System;
using System.Text;
using System.ComponentModel;
using System.Xml;
using System.CodeDom.Compiler;
using IComparer = System.Collections.Generic.IComparer<object>;
// These classes represent a mapping between classes and a particular XML format.
// There are two class of mapping information: accessors (such as elements and
// attributes), and mappings (which specify the type of an accessor).
internal abstract class Accessor
{
private string _name;
private object _defaultValue = null;
private string _ns;
private TypeMapping _mapping;
private bool _any;
private string _anyNs;
private bool _topLevelInSchema;
private XmlSchemaForm _form = XmlSchemaForm.None;
internal Accessor() { }
internal TypeMapping Mapping
{
get { return _mapping; }
set { _mapping = value; }
}
internal object Default
{
get { return _defaultValue; }
set { _defaultValue = value; }
}
internal virtual string Name
{
get { return _name == null ? string.Empty : _name; }
set { _name = value; }
}
internal bool Any
{
get { return _any; }
set { _any = value; }
}
internal string AnyNamespaces
{
get { return _anyNs; }
set { _anyNs = value; }
}
internal string Namespace
{
get { return _ns; }
set { _ns = value; }
}
internal XmlSchemaForm Form
{
get { return _form; }
set { _form = value; }
}
internal bool IsTopLevelInSchema
{
get { return _topLevelInSchema; }
set { _topLevelInSchema = value; }
}
internal static string EscapeQName(string name)
{
if (name == null || name.Length == 0) return name;
int colon = name.LastIndexOf(':');
if (colon < 0)
return XmlConvert.EncodeLocalName(name);
else
{
if (colon == 0 || colon == name.Length - 1)
throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name), "name");
return new XmlQualifiedName(XmlConvert.EncodeLocalName(name.Substring(colon + 1)), XmlConvert.EncodeLocalName(name.Substring(0, colon))).ToString();
}
}
internal static string UnescapeName(string name)
{
return XmlConvert.DecodeName(name);
}
}
internal class ElementAccessor : Accessor
{
private bool _nullable;
private bool _unbounded = false;
internal bool IsSoap
{
get { return false; }
}
internal bool IsNullable
{
get { return _nullable; }
set { _nullable = value; }
}
internal bool IsUnbounded
{
get { return _unbounded; }
set { _unbounded = value; }
}
internal ElementAccessor Clone()
{
ElementAccessor newAccessor = new ElementAccessor();
newAccessor._nullable = _nullable;
newAccessor.IsTopLevelInSchema = this.IsTopLevelInSchema;
newAccessor.Form = this.Form;
newAccessor.Name = this.Name;
newAccessor.Default = this.Default;
newAccessor.Namespace = this.Namespace;
newAccessor.Mapping = this.Mapping;
newAccessor.Any = this.Any;
return newAccessor;
}
}
internal class ChoiceIdentifierAccessor : Accessor
{
private string _memberName;
private string[] _memberIds;
private MemberInfo _memberInfo;
internal string MemberName
{
get { return _memberName; }
set { _memberName = value; }
}
internal string[] MemberIds
{
get { return _memberIds; }
set { _memberIds = value; }
}
internal MemberInfo MemberInfo
{
get { return _memberInfo; }
set { _memberInfo = value; }
}
}
internal class TextAccessor : Accessor
{
}
internal class XmlnsAccessor : Accessor
{
}
internal class AttributeAccessor : Accessor
{
private bool _isSpecial;
private bool _isList;
internal bool IsSpecialXmlNamespace
{
get { return _isSpecial; }
}
internal bool IsList
{
get { return _isList; }
set { _isList = value; }
}
internal void CheckSpecial()
{
int colon = Name.LastIndexOf(':');
if (colon >= 0)
{
if (!Name.StartsWith("xml:", StringComparison.Ordinal))
{
throw new InvalidOperationException(SR.Format(SR.Xml_InvalidNameChars, Name));
}
Name = Name.Substring("xml:".Length);
Namespace = XmlReservedNs.NsXml;
_isSpecial = true;
}
else
{
if (Namespace == XmlReservedNs.NsXml)
{
_isSpecial = true;
}
else
{
_isSpecial = false;
}
}
if (_isSpecial)
{
Form = XmlSchemaForm.Qualified;
}
}
}
internal abstract class Mapping
{
internal Mapping() { }
protected Mapping(Mapping mapping)
{
}
internal bool IsSoap
{
get { return false; }
}
}
internal abstract class TypeMapping : Mapping
{
private TypeDesc _typeDesc;
private string _typeNs;
private string _typeName;
private bool _includeInSchema = true;
internal string Namespace
{
get { return _typeNs; }
set { _typeNs = value; }
}
internal string TypeName
{
get { return _typeName; }
set { _typeName = value; }
}
internal TypeDesc TypeDesc
{
get { return _typeDesc; }
set { _typeDesc = value; }
}
internal bool IncludeInSchema
{
get { return _includeInSchema; }
set { _includeInSchema = value; }
}
internal virtual bool IsList
{
get { return false; }
set { }
}
internal bool IsAnonymousType
{
get { return _typeName == null || _typeName.Length == 0; }
}
internal virtual string DefaultElementName
{
get { return IsAnonymousType ? XmlConvert.EncodeLocalName(_typeDesc.Name) : _typeName; }
}
}
internal class PrimitiveMapping : TypeMapping
{
private bool _isList;
internal override bool IsList
{
get { return _isList; }
set { _isList = value; }
}
}
internal class NullableMapping : TypeMapping
{
private TypeMapping _baseMapping;
internal TypeMapping BaseMapping
{
get { return _baseMapping; }
set { _baseMapping = value; }
}
internal override string DefaultElementName
{
get { return BaseMapping.DefaultElementName; }
}
}
internal class ArrayMapping : TypeMapping
{
private ElementAccessor[] _elements;
private ElementAccessor[] _sortedElements;
private ArrayMapping _next;
internal ElementAccessor[] Elements
{
get { return _elements; }
set { _elements = value; _sortedElements = null; }
}
internal ElementAccessor[] ElementsSortedByDerivation
{
get
{
if (_sortedElements != null)
return _sortedElements;
if (_elements == null)
return null;
_sortedElements = new ElementAccessor[_elements.Length];
Array.Copy(_elements, 0, _sortedElements, 0, _elements.Length);
AccessorMapping.SortMostToLeastDerived(_sortedElements);
return _sortedElements;
}
}
internal ArrayMapping Next
{
get { return _next; }
set { _next = value; }
}
}
internal class EnumMapping : PrimitiveMapping
{
private ConstantMapping[] _constants;
private bool _isFlags;
internal bool IsFlags
{
get { return _isFlags; }
set { _isFlags = value; }
}
internal ConstantMapping[] Constants
{
get { return _constants; }
set { _constants = value; }
}
}
internal class ConstantMapping : Mapping
{
private string _xmlName;
private string _name;
private long _value;
internal string XmlName
{
get { return _xmlName == null ? string.Empty : _xmlName; }
set { _xmlName = value; }
}
internal string Name
{
get { return _name == null ? string.Empty : _name; }
set { _name = value; }
}
internal long Value
{
get { return _value; }
set { _value = value; }
}
}
internal class StructMapping : TypeMapping, INameScope
{
private MemberMapping[] _members;
private StructMapping _baseMapping;
private StructMapping _derivedMappings;
private StructMapping _nextDerivedMapping;
private MemberMapping _xmlnsMember = null;
private bool _hasSimpleContent;
private bool _isSequence;
private NameTable _elements;
private NameTable _attributes;
internal StructMapping BaseMapping
{
get { return _baseMapping; }
set
{
_baseMapping = value;
if (!IsAnonymousType && _baseMapping != null)
{
_nextDerivedMapping = _baseMapping._derivedMappings;
_baseMapping._derivedMappings = this;
}
if (value._isSequence && !_isSequence)
{
_isSequence = true;
if (_baseMapping.IsSequence)
{
for (StructMapping derived = _derivedMappings; derived != null; derived = derived.NextDerivedMapping)
{
derived.SetSequence();
}
}
}
}
}
internal StructMapping DerivedMappings
{
get { return _derivedMappings; }
}
internal bool IsFullyInitialized
{
get { return _baseMapping != null && Members != null; }
}
internal NameTable LocalElements
{
get
{
if (_elements == null)
_elements = new NameTable();
return _elements;
}
}
internal NameTable LocalAttributes
{
get
{
if (_attributes == null)
_attributes = new NameTable();
return _attributes;
}
}
object INameScope.this[string name, string ns]
{
get
{
object named = LocalElements[name, ns];
if (named != null)
return named;
if (_baseMapping != null)
return ((INameScope)_baseMapping)[name, ns];
return null;
}
set
{
LocalElements[name, ns] = value;
}
}
internal StructMapping NextDerivedMapping
{
get { return _nextDerivedMapping; }
}
internal bool HasSimpleContent
{
get { return _hasSimpleContent; }
}
internal bool HasXmlnsMember
{
get
{
StructMapping mapping = this;
while (mapping != null)
{
if (mapping.XmlnsMember != null)
return true;
mapping = mapping.BaseMapping;
}
return false;
}
}
internal MemberMapping[] Members
{
get { return _members; }
set { _members = value; }
}
internal MemberMapping XmlnsMember
{
get { return _xmlnsMember; }
set { _xmlnsMember = value; }
}
internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapping declaringMapping, string parent)
{
declaringMapping = null;
if (BaseMapping != null)
{
MemberMapping baseMember = BaseMapping.FindDeclaringMapping(member, out declaringMapping, parent);
if (baseMember != null) return baseMember;
}
if (_members == null) return null;
for (int i = 0; i < _members.Length; i++)
{
if (_members[i].Name == member.Name)
{
if (_members[i].TypeDesc != member.TypeDesc)
throw new InvalidOperationException(SR.Format(SR.XmlHiddenMember, parent, member.Name, member.TypeDesc.FullName, this.TypeName, _members[i].Name, _members[i].TypeDesc.FullName));
else if (!_members[i].Match(member))
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlOverride, parent, member.Name, this.TypeName, _members[i].Name));
}
declaringMapping = this;
return _members[i];
}
}
return null;
}
internal bool Declares(MemberMapping member, string parent)
{
StructMapping m;
return (FindDeclaringMapping(member, out m, parent) != null);
}
internal void SetContentModel(TextAccessor text, bool hasElements)
{
if (BaseMapping == null || BaseMapping.TypeDesc.IsRoot)
{
_hasSimpleContent = !hasElements && text != null && !text.Mapping.IsList;
}
else if (BaseMapping.HasSimpleContent)
{
if (text != null || hasElements)
{
// we can only extent a simleContent type with attributes
throw new InvalidOperationException(SR.Format(SR.XmlIllegalSimpleContentExtension, TypeDesc.FullName, BaseMapping.TypeDesc.FullName));
}
else
{
_hasSimpleContent = true;
}
}
else
{
_hasSimpleContent = false;
}
if (!_hasSimpleContent && text != null && !text.Mapping.TypeDesc.CanBeTextValue)
{
throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, TypeDesc.FullName, text.Name, text.Mapping.TypeDesc.FullName));
}
}
internal bool HasExplicitSequence()
{
if (_members != null)
{
for (int i = 0; i < _members.Length; i++)
{
if (_members[i].IsParticle && _members[i].IsSequence)
{
return true;
}
}
}
return (_baseMapping != null && _baseMapping.HasExplicitSequence());
}
internal void SetSequence()
{
if (TypeDesc.IsRoot)
return;
StructMapping start = this;
// find first mapping that does not have the sequence set
while (start.BaseMapping != null && !start.BaseMapping.IsSequence && !start.BaseMapping.TypeDesc.IsRoot)
start = start.BaseMapping;
start.IsSequence = true;
for (StructMapping derived = start.DerivedMappings; derived != null; derived = derived.NextDerivedMapping)
{
derived.SetSequence();
}
}
internal bool IsSequence
{
get { return _isSequence && !TypeDesc.IsRoot; }
set { _isSequence = value; }
}
}
internal abstract class AccessorMapping : Mapping
{
private TypeDesc _typeDesc;
private AttributeAccessor _attribute;
private ElementAccessor[] _elements;
private ElementAccessor[] _sortedElements;
private TextAccessor _text;
private ChoiceIdentifierAccessor _choiceIdentifier;
private XmlnsAccessor _xmlns;
private bool _ignore;
internal AccessorMapping()
{ }
protected AccessorMapping(AccessorMapping mapping)
: base(mapping)
{
_typeDesc = mapping._typeDesc;
_attribute = mapping._attribute;
_elements = mapping._elements;
_sortedElements = mapping._sortedElements;
_text = mapping._text;
_choiceIdentifier = mapping._choiceIdentifier;
_xmlns = mapping._xmlns;
_ignore = mapping._ignore;
}
internal bool IsAttribute
{
get { return _attribute != null; }
}
internal bool IsText
{
get { return _text != null && (_elements == null || _elements.Length == 0); }
}
internal bool IsParticle
{
get { return (_elements != null && _elements.Length > 0); }
}
internal TypeDesc TypeDesc
{
get { return _typeDesc; }
set { _typeDesc = value; }
}
internal AttributeAccessor Attribute
{
get { return _attribute; }
set { _attribute = value; }
}
internal ElementAccessor[] Elements
{
get { return _elements; }
set { _elements = value; _sortedElements = null; }
}
internal static void SortMostToLeastDerived(ElementAccessor[] elements)
{
Array.Sort(elements, new AccessorComparer());
}
internal class AccessorComparer : IComparer
{
public int Compare(object o1, object o2)
{
if (o1 == o2)
return 0;
Accessor a1 = (Accessor)o1;
Accessor a2 = (Accessor)o2;
int w1 = a1.Mapping.TypeDesc.Weight;
int w2 = a2.Mapping.TypeDesc.Weight;
if (w1 == w2)
return 0;
if (w1 < w2)
return 1;
return -1;
}
}
internal ElementAccessor[] ElementsSortedByDerivation
{
get
{
if (_sortedElements != null)
return _sortedElements;
if (_elements == null)
return null;
_sortedElements = new ElementAccessor[_elements.Length];
Array.Copy(_elements, 0, _sortedElements, 0, _elements.Length);
SortMostToLeastDerived(_sortedElements);
return _sortedElements;
}
}
internal TextAccessor Text
{
get { return _text; }
set { _text = value; }
}
internal ChoiceIdentifierAccessor ChoiceIdentifier
{
get { return _choiceIdentifier; }
set { _choiceIdentifier = value; }
}
internal XmlnsAccessor Xmlns
{
get { return _xmlns; }
set { _xmlns = value; }
}
internal bool Ignore
{
get { return _ignore; }
set { _ignore = value; }
}
internal Accessor Accessor
{
get
{
if (_xmlns != null) return _xmlns;
if (_attribute != null) return _attribute;
if (_elements != null && _elements.Length > 0) return _elements[0];
return _text;
}
}
internal static bool ElementsMatch(ElementAccessor[] a, ElementAccessor[] b)
{
if (a == null)
{
if (b == null)
return true;
return false;
}
if (b == null)
return false;
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
{
if (a[i].Name != b[i].Name || a[i].Namespace != b[i].Namespace || a[i].Form != b[i].Form || a[i].IsNullable != b[i].IsNullable)
return false;
}
return true;
}
internal bool Match(AccessorMapping mapping)
{
if (Elements != null && Elements.Length > 0)
{
if (!ElementsMatch(Elements, mapping.Elements))
{
return false;
}
if (Text == null)
{
return (mapping.Text == null);
}
}
if (Attribute != null)
{
if (mapping.Attribute == null)
return false;
return (Attribute.Name == mapping.Attribute.Name && Attribute.Namespace == mapping.Attribute.Namespace && Attribute.Form == mapping.Attribute.Form);
}
if (Text != null)
{
return (mapping.Text != null);
}
return (mapping.Accessor == null);
}
}
internal class MemberMappingComparer : IComparer
{
public int Compare(object o1, object o2)
{
MemberMapping m1 = (MemberMapping)o1;
MemberMapping m2 = (MemberMapping)o2;
bool m1Text = m1.IsText;
if (m1Text)
{
if (m2.IsText)
return 0;
return 1;
}
else if (m2.IsText)
return -1;
if (m1.SequenceId < 0 && m2.SequenceId < 0)
return 0;
if (m1.SequenceId < 0)
return 1;
if (m2.SequenceId < 0)
return -1;
if (m1.SequenceId < m2.SequenceId)
return -1;
if (m1.SequenceId > m2.SequenceId)
return 1;
return 0;
}
}
internal class MemberMapping : AccessorMapping
{
private string _name;
private bool _checkShouldPersist;
private SpecifiedAccessor _checkSpecified;
private bool _isReturnValue;
private bool _readOnly = false;
private int _sequenceId = -1;
private MemberInfo _memberInfo;
private MemberInfo _checkSpecifiedMemberInfo;
private MethodInfo _checkShouldPersistMethodInfo;
internal MemberMapping() { }
private MemberMapping(MemberMapping mapping)
: base(mapping)
{
_name = mapping._name;
_checkShouldPersist = mapping._checkShouldPersist;
_checkSpecified = mapping._checkSpecified;
_isReturnValue = mapping._isReturnValue;
_readOnly = mapping._readOnly;
_sequenceId = mapping._sequenceId;
_memberInfo = mapping._memberInfo;
_checkSpecifiedMemberInfo = mapping._checkSpecifiedMemberInfo;
_checkShouldPersistMethodInfo = mapping._checkShouldPersistMethodInfo;
}
internal bool CheckShouldPersist
{
get { return _checkShouldPersist; }
set { _checkShouldPersist = value; }
}
internal SpecifiedAccessor CheckSpecified
{
get { return _checkSpecified; }
set { _checkSpecified = value; }
}
internal string Name
{
get { return _name == null ? string.Empty : _name; }
set { _name = value; }
}
internal MemberInfo MemberInfo
{
get { return _memberInfo; }
set { _memberInfo = value; }
}
internal MemberInfo CheckSpecifiedMemberInfo
{
get { return _checkSpecifiedMemberInfo; }
set { _checkSpecifiedMemberInfo = value; }
}
internal MethodInfo CheckShouldPersistMethodInfo
{
get { return _checkShouldPersistMethodInfo; }
set { _checkShouldPersistMethodInfo = value; }
}
internal bool IsReturnValue
{
get { return _isReturnValue; }
set { _isReturnValue = value; }
}
internal bool ReadOnly
{
get { return _readOnly; }
set { _readOnly = value; }
}
internal bool IsSequence
{
get { return _sequenceId >= 0; }
}
internal int SequenceId
{
get { return _sequenceId; }
set { _sequenceId = value; }
}
private string GetNullableType(TypeDesc td)
{
// SOAP encoded arrays not mapped to Nullable<T> since they always derive from soapenc:Array
if (td.IsMappedType || (!td.IsValueType && (Elements[0].IsSoap || td.ArrayElementTypeDesc == null)))
return td.FullName;
if (td.ArrayElementTypeDesc != null)
{
return GetNullableType(td.ArrayElementTypeDesc) + "[]";
}
return "System.Nullable`1[" + td.FullName + "]";
}
internal MemberMapping Clone()
{
return new MemberMapping(this);
}
}
internal class MembersMapping : TypeMapping
{
private MemberMapping[] _members;
private bool _hasWrapperElement = true;
private bool _writeAccessors = true;
private MemberMapping _xmlnsMember = null;
internal MemberMapping[] Members
{
get { return _members; }
set { _members = value; }
}
internal MemberMapping XmlnsMember
{
get { return _xmlnsMember; }
set { _xmlnsMember = value; }
}
internal bool HasWrapperElement
{
get { return _hasWrapperElement; }
set { _hasWrapperElement = value; }
}
internal bool WriteAccessors
{
get { return _writeAccessors; }
}
}
internal class SpecialMapping : TypeMapping
{
}
internal class SerializableMapping : SpecialMapping
{
private Type _type;
private bool _needSchema = true;
// new implementation of the IXmlSerializable
private MethodInfo _getSchemaMethod;
private XmlQualifiedName _xsiType;
private XmlSchemaSet _schemas;
private bool _any;
private SerializableMapping _derivedMappings;
private SerializableMapping _nextDerivedMapping;
internal SerializableMapping() { }
internal SerializableMapping(MethodInfo getSchemaMethod, bool any, string ns)
{
_getSchemaMethod = getSchemaMethod;
_any = any;
this.Namespace = ns;
_needSchema = getSchemaMethod != null;
}
internal bool IsAny
{
get
{
if (_any)
return true;
if (_getSchemaMethod == null)
return false;
if (_needSchema && typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType))
return false;
RetrieveSerializableSchema();
return _any;
}
}
internal SerializableMapping DerivedMappings
{
get
{
return _derivedMappings;
}
}
internal SerializableMapping NextDerivedMapping
{
get
{
return _nextDerivedMapping;
}
}
internal Type Type
{
get { return _type; }
set { _type = value; }
}
internal XmlQualifiedName XsiType
{
get
{
if (!_needSchema)
return _xsiType;
if (_getSchemaMethod == null)
return null;
if (typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType))
return null;
RetrieveSerializableSchema();
return _xsiType;
}
}
private void RetrieveSerializableSchema()
{
if (_needSchema)
{
_needSchema = false;
if (_getSchemaMethod != null)
{
// get the type info
object typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas });
_xsiType = XmlQualifiedName.Empty;
if (typeInfo != null)
{
if (typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType))
{
throw Globals.NotSupported("No XmlSchemaType in SL");
}
else if (typeof(XmlQualifiedName).IsAssignableFrom(_getSchemaMethod.ReturnType))
{
_xsiType = (XmlQualifiedName)typeInfo;
if (_xsiType.IsEmpty)
{
throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaEmptyTypeName, _type.FullName, _getSchemaMethod.Name));
}
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodReturnType, _type.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName));
}
}
else
{
_any = true;
}
}
}
}
}
}
| |
using System;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using log4net;
using PacketDotNet.Utils;
namespace PacketDotNet.LLDP
{
/// <summary>
/// A Chassis ID TLV
/// </summary>
public class ChassisID : TLV
{
#if DEBUG
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#else
// NOTE: No need to warn about lack of use, the compiler won't
// put any calls to 'log' here but we need 'log' to exist to compile
#pragma warning disable 0169, 0649
private static readonly ILogInactive log;
#pragma warning restore 0169, 0649
#endif
/// <summary>
/// Length of the sub type field in bytes
/// </summary>
private const int SubTypeLength = 1;
#region Constructors
/// <summary>
/// Creates a Chassis ID TLV by parsing a byte[]
/// </summary>
/// <param name="bytes">
/// </param>
/// <param name="offset">
/// The Chassis ID TLV's offset from the
/// origin of the LLDP
/// </param>
public ChassisID(byte[] bytes, int offset) : base(bytes, offset) { log.Debug(""); }
/// <summary>
/// Creates a Chassis ID TLV and sets it value
/// </summary>
/// <param name="subType">
/// The ChassisID subtype
/// </param>
/// <param name="subTypeValue">
/// The subtype's value
/// </param>
public ChassisID(ChassisSubTypes subType, object subTypeValue)
{
log.DebugFormat("subType {0}", subType);
this.EmptyTLVDataInit();
this.Type = TLVTypes.ChassisID;
this.SubType = subType;
// method will resize the tlv
this.SubTypeValue = subTypeValue;
}
/// <summary>
/// Create a ChassisID given a mac address
/// </summary>
/// <param name="MACAddress">
/// A <see cref="PhysicalAddress" />
/// </param>
public ChassisID(PhysicalAddress MACAddress)
{
log.DebugFormat("MACAddress {0}", MACAddress);
this.EmptyTLVDataInit();
this.Type = TLVTypes.ChassisID;
this.SubType = ChassisSubTypes.MACAddress;
this.SubTypeValue = MACAddress;
}
/// <summary>
/// Create a ChassisID given an interface name
/// http://tools.ietf.org/search/rfc2863 page 38
/// </summary>
/// <param name="InterfaceName">
/// A <see cref="System.String" />
/// </param>
public ChassisID(string InterfaceName)
{
log.DebugFormat("InterfaceName {0}", InterfaceName);
this.EmptyTLVDataInit();
this.Type = TLVTypes.ChassisID;
this.SubType = ChassisSubTypes.InterfaceName;
this.SetSubTypeValue(InterfaceName);
}
#endregion
#region Properties
/// <value>
/// The type of the TLV subtype
/// </value>
public ChassisSubTypes SubType
{
get { return (ChassisSubTypes) this.tlvData.Bytes[this.ValueOffset]; }
set
{
// set the subtype
this.tlvData.Bytes[this.ValueOffset] = (byte) value;
}
}
/// <value>
/// The TLV subtype value
/// </value>
public object SubTypeValue
{
get { return this.GetSubTypeValue(); }
set { this.SetSubTypeValue(value); }
}
/// <summary>
/// If SubType is ChassisComponent
/// </summary>
public byte[] ChassisComponent
{
get { return (byte[]) this.GetSubTypeValue(); }
set
{
this.SubType = ChassisSubTypes.ChassisComponent;
this.SetSubTypeValue(value);
}
}
/// <summary>
/// If SubType is InterfaceName the interface name
/// </summary>
public string InterfaceName
{
get { return (string) this.GetSubTypeValue(); }
set
{
this.SubType = ChassisSubTypes.InterfaceName;
this.SetSubTypeValue(value);
}
}
/// <summary>
/// If SubType is MACAddress the mac address
/// </summary>
public PhysicalAddress MACAddress
{
get { return (PhysicalAddress) this.GetSubTypeValue(); }
set
{
this.SubType = ChassisSubTypes.MACAddress;
this.SetSubTypeValue(value);
}
}
/// <summary>
/// If SubType is NetworkAddress the network address
/// </summary>
public NetworkAddress NetworkAddress
{
get { return (NetworkAddress) this.GetSubTypeValue(); }
set
{
this.SubType = ChassisSubTypes.NetworkAddress;
this.SetSubTypeValue(value);
}
}
/// <summary>
/// If SubType is PortComponent
/// </summary>
public byte[] PortComponent
{
get { return (byte[]) this.GetSubTypeValue(); }
set
{
this.SubType = ChassisSubTypes.PortComponent;
this.SetSubTypeValue(value);
}
}
/// <summary>
/// If SubType is InterfaceAlias
/// </summary>
public byte[] InterfaceAlias
{
get { return (byte[]) this.GetSubTypeValue(); }
set
{
this.SubType = ChassisSubTypes.InterfaceAlias;
this.SetSubTypeValue(value);
}
}
#endregion
#region Methods
/// <summary>
/// Helper method to reduce duplication in type specific constructors
/// </summary>
private void EmptyTLVDataInit()
{
var length = TLVTypeLength.TypeLengthLength + SubTypeLength;
var bytes = new byte[length];
var offset = 0;
this.tlvData = new ByteArraySegment(bytes, offset, length);
}
private object GetSubTypeValue()
{
byte[] val;
var dataOffset = this.ValueOffset + SubTypeLength;
var dataLength = this.Length - SubTypeLength;
switch(this.SubType)
{
case ChassisSubTypes.ChassisComponent:
case ChassisSubTypes.InterfaceAlias:
case ChassisSubTypes.LocallyAssigned:
case ChassisSubTypes.PortComponent:
val = new byte[dataLength];
Array.Copy(this.tlvData.Bytes, dataOffset, val, 0, dataLength);
return val;
case ChassisSubTypes.NetworkAddress:
return new NetworkAddress(this.tlvData.Bytes, dataOffset, dataLength);
case ChassisSubTypes.MACAddress:
val = new byte[dataLength];
Array.Copy(this.tlvData.Bytes, dataOffset, val, 0, dataLength);
return new PhysicalAddress(val);
case ChassisSubTypes.InterfaceName:
return Encoding.ASCII.GetString(this.tlvData.Bytes, dataOffset, dataLength);
default:
throw new ArgumentOutOfRangeException();
}
}
private void SetSubTypeValue(object val)
{
byte[] valBytes;
// make sure we have the correct type
switch(this.SubType)
{
case ChassisSubTypes.ChassisComponent:
case ChassisSubTypes.InterfaceAlias:
case ChassisSubTypes.LocallyAssigned:
case ChassisSubTypes.PortComponent:
if(!(val is byte[])) { throw new ArgumentOutOfRangeException("expected byte[] for type"); }
valBytes = (byte[]) val;
this.SetSubTypeValue(valBytes);
break;
case ChassisSubTypes.NetworkAddress:
if(!(val is NetworkAddress)) { throw new ArgumentOutOfRangeException("expected NetworkAddress instance for NetworkAddress"); }
valBytes = ((NetworkAddress) val).Bytes;
this.SetSubTypeValue(valBytes);
break;
case ChassisSubTypes.InterfaceName:
if(!(val is string)) { throw new ArgumentOutOfRangeException("expected string for InterfaceName"); }
var interfaceName = (string) val;
valBytes = Encoding.ASCII.GetBytes(interfaceName);
this.SetSubTypeValue(valBytes);
break;
case ChassisSubTypes.MACAddress:
if(!(val is PhysicalAddress)) { throw new ArgumentOutOfRangeException("expected PhysicalAddress for MACAddress"); }
var physicalAddress = (PhysicalAddress) val;
this.SetSubTypeValue(physicalAddress.GetAddressBytes());
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void SetSubTypeValue(byte[] subTypeValue)
{
// is the length different than the current length?
if(subTypeValue.Length != this.Length)
{
var headerLength = TLVTypeLength.TypeLengthLength + SubTypeLength;
var newTlvMemory = new byte[headerLength + subTypeValue.Length];
// copy the header data over
Array.Copy(this.tlvData.Bytes, this.tlvData.Offset, newTlvMemory, 0, headerLength);
// update the tlv memory pointer, offset and length
this.tlvData = new ByteArraySegment(newTlvMemory, 0, newTlvMemory.Length);
}
Array.Copy(subTypeValue, 0, this.tlvData.Bytes, this.ValueOffset + SubTypeLength, subTypeValue.Length);
}
/// <summary>
/// Convert this Chassis ID TLV to a string.
/// </summary>
/// <returns>
/// A human readable string
/// </returns>
public override string ToString() { return string.Format("[ChassisID: SubType={0}, SubTypeValue={1}]", this.SubType, this.SubTypeValue); }
#endregion
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace Revit.SDK.Samples.CreateBeamsColumnsBraces.CS
{
/// <summary>
/// UI
/// </summary>
public class CreateBeamsColumnsBracesForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button OKButton;
private System.Windows.Forms.TextBox XTextBox;
private System.Windows.Forms.TextBox DistanceTextBox;
private System.Windows.Forms.TextBox YTextBox;
private System.Windows.Forms.ComboBox columnComboBox;
private System.Windows.Forms.ComboBox beamComboBox;
private System.Windows.Forms.ComboBox braceComboBox;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.TextBox floornumberTextBox;
private System.Windows.Forms.Label columnLabel;
private System.Windows.Forms.Label beamLabel;
private System.Windows.Forms.Label braceLabel;
private System.Windows.Forms.Label DistanceLabel;
private System.Windows.Forms.Label YLabel;
private System.Windows.Forms.Label XLabel;
private System.Windows.Forms.Label floornumberLabel;
private System.Windows.Forms.Label unitLabel;
// To store the datas
Command m_dataBuffer = null;
/// <summary>
/// constructor
/// </summary>
/// <param name="dataBuffer">the revit datas</param>
public CreateBeamsColumnsBracesForm(Command dataBuffer)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_dataBuffer = dataBuffer;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#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.OKButton = new System.Windows.Forms.Button();
this.XTextBox = new System.Windows.Forms.TextBox();
this.YTextBox = new System.Windows.Forms.TextBox();
this.DistanceTextBox = new System.Windows.Forms.TextBox();
this.columnComboBox = new System.Windows.Forms.ComboBox();
this.beamComboBox = new System.Windows.Forms.ComboBox();
this.braceComboBox = new System.Windows.Forms.ComboBox();
this.columnLabel = new System.Windows.Forms.Label();
this.beamLabel = new System.Windows.Forms.Label();
this.braceLabel = new System.Windows.Forms.Label();
this.floornumberTextBox = new System.Windows.Forms.TextBox();
this.DistanceLabel = new System.Windows.Forms.Label();
this.YLabel = new System.Windows.Forms.Label();
this.XLabel = new System.Windows.Forms.Label();
this.floornumberLabel = new System.Windows.Forms.Label();
this.cancelButton = new System.Windows.Forms.Button();
this.unitLabel = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// OKButton
//
this.OKButton.Location = new System.Drawing.Point(296, 208);
this.OKButton.Name = "OKButton";
this.OKButton.TabIndex = 8;
this.OKButton.Text = "&OK";
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// XTextBox
//
this.XTextBox.Location = new System.Drawing.Point(16, 96);
this.XTextBox.Name = "XTextBox";
this.XTextBox.Size = new System.Drawing.Size(136, 20);
this.XTextBox.TabIndex = 2;
this.XTextBox.Text = "";
this.XTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.XTextBox_Validating);
//
// YTextBox
//
this.YTextBox.Location = new System.Drawing.Point(16, 152);
this.YTextBox.Name = "YTextBox";
this.YTextBox.Size = new System.Drawing.Size(136, 20);
this.YTextBox.TabIndex = 3;
this.YTextBox.Text = "";
this.YTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.YTextBox_Validating);
//
// DistanceTextBox
//
this.DistanceTextBox.Location = new System.Drawing.Point(16, 40);
this.DistanceTextBox.Name = "DistanceTextBox";
this.DistanceTextBox.Size = new System.Drawing.Size(112, 20);
this.DistanceTextBox.TabIndex = 1;
this.DistanceTextBox.Text = "";
this.DistanceTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.DistanceTextBox_Validating);
//
// columnComboBox
//
this.columnComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.columnComboBox.Location = new System.Drawing.Point(240, 40);
this.columnComboBox.Name = "columnComboBox";
this.columnComboBox.Size = new System.Drawing.Size(288, 21);
this.columnComboBox.TabIndex = 5;
//
// beamComboBox
//
this.beamComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.beamComboBox.Location = new System.Drawing.Point(240, 96);
this.beamComboBox.Name = "beamComboBox";
this.beamComboBox.Size = new System.Drawing.Size(288, 21);
this.beamComboBox.TabIndex = 6;
//
// braceComboBox
//
this.braceComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.braceComboBox.Location = new System.Drawing.Point(240, 152);
this.braceComboBox.Name = "braceComboBox";
this.braceComboBox.Size = new System.Drawing.Size(288, 21);
this.braceComboBox.TabIndex = 7;
//
// columnLabel
//
this.columnLabel.Location = new System.Drawing.Point(240, 16);
this.columnLabel.Name = "columnLabel";
this.columnLabel.Size = new System.Drawing.Size(120, 23);
this.columnLabel.TabIndex = 10;
this.columnLabel.Text = "Type of Columns:";
//
// beamLabel
//
this.beamLabel.Location = new System.Drawing.Point(240, 72);
this.beamLabel.Name = "beamLabel";
this.beamLabel.Size = new System.Drawing.Size(120, 23);
this.beamLabel.TabIndex = 11;
this.beamLabel.Text = "Type of Beams:";
//
// braceLabel
//
this.braceLabel.Location = new System.Drawing.Point(240, 128);
this.braceLabel.Name = "braceLabel";
this.braceLabel.Size = new System.Drawing.Size(120, 23);
this.braceLabel.TabIndex = 12;
this.braceLabel.Text = "Type of Braces:";
//
// floornumberTextBox
//
this.floornumberTextBox.Location = new System.Drawing.Point(16, 208);
this.floornumberTextBox.Name = "floornumberTextBox";
this.floornumberTextBox.Size = new System.Drawing.Size(112, 20);
this.floornumberTextBox.TabIndex = 4;
this.floornumberTextBox.Text = "";
this.floornumberTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.floornumberTextBox_Validating);
//
// DistanceLabel
//
this.DistanceLabel.Location = new System.Drawing.Point(16, 16);
this.DistanceLabel.Name = "DistanceLabel";
this.DistanceLabel.Size = new System.Drawing.Size(152, 23);
this.DistanceLabel.TabIndex = 14;
this.DistanceLabel.Text = "Distance between Columns:";
//
// YLabel
//
this.YLabel.Location = new System.Drawing.Point(16, 128);
this.YLabel.Name = "YLabel";
this.YLabel.Size = new System.Drawing.Size(200, 23);
this.YLabel.TabIndex = 15;
this.YLabel.Text = "Number of Columns in the Y Direction:";
//
// XLabel
//
this.XLabel.Location = new System.Drawing.Point(16, 72);
this.XLabel.Name = "XLabel";
this.XLabel.Size = new System.Drawing.Size(200, 23);
this.XLabel.TabIndex = 16;
this.XLabel.Text = "Number of Columns in the X Direction:";
//
// floornumberLabel
//
this.floornumberLabel.Location = new System.Drawing.Point(16, 184);
this.floornumberLabel.Name = "floornumberLabel";
this.floornumberLabel.Size = new System.Drawing.Size(144, 23);
this.floornumberLabel.TabIndex = 17;
this.floornumberLabel.Text = "Number of Floors:";
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(392, 208);
this.cancelButton.Name = "cancelButton";
this.cancelButton.TabIndex = 9;
this.cancelButton.Text = "&Cancel";
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// unitLabel
//
this.unitLabel.Location = new System.Drawing.Point(136, 42);
this.unitLabel.Name = "unitLabel";
this.unitLabel.Size = new System.Drawing.Size(32, 23);
this.unitLabel.TabIndex = 18;
this.unitLabel.Text = "feet";
//
// CreateBeamsColumnsBracesForm
//
this.AcceptButton = this.OKButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(546, 246);
this.Controls.Add(this.unitLabel);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.floornumberLabel);
this.Controls.Add(this.XLabel);
this.Controls.Add(this.YLabel);
this.Controls.Add(this.DistanceLabel);
this.Controls.Add(this.floornumberTextBox);
this.Controls.Add(this.DistanceTextBox);
this.Controls.Add(this.YTextBox);
this.Controls.Add(this.XTextBox);
this.Controls.Add(this.braceLabel);
this.Controls.Add(this.beamLabel);
this.Controls.Add(this.columnLabel);
this.Controls.Add(this.braceComboBox);
this.Controls.Add(this.beamComboBox);
this.Controls.Add(this.columnComboBox);
this.Controls.Add(this.OKButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "CreateBeamsColumnsBracesForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Create Beams Columns and Braces";
this.Load += new System.EventHandler(this.CreateBeamsColumnsBracesForm_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Refresh the text box for the default datas
/// </summary>
private void TextBoxRefresh()
{
this.XTextBox.Text = "2";
this.YTextBox.Text = "2";
this.DistanceTextBox.Text = "20.0";
this.floornumberTextBox.Text = "1";
}
private void CreateBeamsColumnsBracesForm_Load(object sender, System.EventArgs e)
{
this.TextBoxRefresh();
bool notLoadSymbol = false;
if (0 == m_dataBuffer.ColumnMaps.Count)
{
MessageBox.Show("No Structural Columns family is loaded in the project, please load one firstly.", "Revit");
notLoadSymbol = true;
}
if (0 == m_dataBuffer.BeamMaps.Count)
{
MessageBox.Show("No Structural Framing family is loaded in the project, please load one firstly.", "Revit");
notLoadSymbol = true;
}
if (notLoadSymbol)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
return;
}
this.columnComboBox.DataSource = m_dataBuffer.ColumnMaps;
this.columnComboBox.DisplayMember = "SymbolName";
this.columnComboBox.ValueMember = "ElementType";
this.beamComboBox.DataSource = m_dataBuffer.BeamMaps;
this.beamComboBox.DisplayMember = "SymbolName";
this.beamComboBox.ValueMember = "ElementType";
this.braceComboBox.DataSource = m_dataBuffer.BraceMaps;
this.braceComboBox.DisplayMember = "SymbolName";
this.braceComboBox.ValueMember = "ElementType";
}
/// <summary>
/// accept use's input and create columns, beams and braces
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OKButton_Click(object sender, System.EventArgs e)
{
//check whether the input is correct and create elements
try
{
int xNumber = int.Parse(this.XTextBox.Text);
int yNumber = int.Parse(this.YTextBox.Text);
double distance = double.Parse(this.DistanceTextBox.Text);
object columnType = columnComboBox.SelectedValue;
object beamType = beamComboBox.SelectedValue;
object braceType = braceComboBox.SelectedValue;
int floorNumber = int.Parse(floornumberTextBox.Text);
m_dataBuffer.CreateMatrix(xNumber, yNumber,distance);
m_dataBuffer.AddInstance(columnType, beamType, braceType, floorNumber);
this.DialogResult = DialogResult.OK;
this.Close();
}
catch(Exception)
{
MessageBox.Show("Please input datas correctly.","Revit");
}
}
/// <summary>
/// cancel the command
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cancelButton_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
/// <summary>
/// Verify the distance
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DistanceTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
double distance = 0.1;
try
{
distance = double.Parse(this.DistanceTextBox.Text);
}
catch(Exception)
{
MessageBox.Show("Please enter a value larger than 5 and less than 30000.","Revit");
this.DistanceTextBox.Text = "";
this.DistanceTextBox.Focus();
return;
}
if (distance <= 5)
{
MessageBox.Show("Please enter a value larger than 5.","Revit");
this.DistanceTextBox.Text = "";
this.DistanceTextBox.Focus();
return;
}
if (distance > 30000)
{
MessageBox.Show("Please enter a value less than 30000.", "Revit");
this.DistanceTextBox.Text = "";
this.DistanceTextBox.Focus();
return;
}
}
/// <summary>
/// Verify the number of X direction
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void XTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
int xNumber = 1;
try
{
xNumber = int.Parse(this.XTextBox.Text);
}
catch(Exception)
{
MessageBox.Show("Please input an integer for X direction between 1 to 20.","Revit");
this.XTextBox.Text = "";
}
if (xNumber < 1 || xNumber > 20)
{
MessageBox.Show("Please input an integer for X direction between 1 to 20.","Revit");
this.XTextBox.Text = "";
}
}
/// <summary>
/// Verify the number of Y direction
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void YTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
int yNumber = 1;
try
{
yNumber = int.Parse(this.YTextBox.Text);
}
catch(Exception)
{
MessageBox.Show("Please input an integer for Y direction between 1 to 20.","Revit");
this.YTextBox.Text = "";
}
if (yNumber < 1 || yNumber > 20)
{
MessageBox.Show("Please input an integer for Y direction between 1 to 20.","Revit");
this.YTextBox.Text = "";
}
}
/// <summary>
/// Verify the number of floors
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void floornumberTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
int floorNumber = 1;
try
{
floorNumber = int.Parse(floornumberTextBox.Text);
}
catch(Exception)
{
MessageBox.Show("Please input an integer for the number of floors between 1 to 10.","Revit");
this.floornumberTextBox.Text = "";
}
if (floorNumber < 1 || floorNumber > 10)
{
MessageBox.Show("Please input an integer for the number of floors between 1 to 10.","Revit");
this.floornumberTextBox.Text = "";
}
}
}
}
| |
using Signum.Engine.Files;
using Signum.Engine.Authorization;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Engine.Processes;
using Signum.Entities.Files;
using Signum.Entities.Processes;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Signum.Entities.Printing;
using Signum.Entities;
using System.IO;
using Signum.Engine.Scheduler;
using Signum.Entities.Basics;
namespace Signum.Engine.Printing
{
public static class PrintingLogic
{
public static int DeleteFilesAfter = 24 * 60; //Minutes
public static Action<PrintLineEntity> Print = e => throw new NotImplementedException("PrintingLogic.Print is not defined");
[AutoExpressionField]
public static IQueryable<PrintLineEntity> Lines(this PrintPackageEntity e) =>
As.Expression(() => Database.Query<PrintLineEntity>().Where(a => a.Package.Is(e)));
public static FileTypeSymbol? TestFileType;
public static void Start(SchemaBuilder sb, FileTypeSymbol? testFileType = null)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
TestFileType = testFileType;
sb.Include<PrintLineEntity>()
.WithQuery(() => p => new
{
Entity = p,
p.CreationDate,
p.File,
p.State,
p.Package,
p.PrintedOn,
p.Referred,
});
sb.Include<PrintPackageEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name
});
ProcessLogic.AssertStarted(sb);
ProcessLogic.Register(PrintPackageProcess.PrintPackage, new PrintPackageAlgorithm());
PermissionAuthLogic.RegisterPermissions(PrintPermission.ViewPrintPanel);
PrintLineGraph.Register();
SimpleTaskLogic.Register(PrintTask.RemoveOldFiles, (ScheduledTaskContext ctx) =>
{
var lines = Database.Query<PrintLineEntity>().Where(a => a.State == PrintLineState.Printed).Where(b => b.CreationDate <= DateTime.Now.AddMinutes(-DeleteFilesAfter));
foreach (var line in lines)
{
try
{
using (Transaction tr = new Transaction())
{
line.File.DeleteFileOnCommit();
line.State = PrintLineState.PrintedAndDeleted;
using (OperationLogic.AllowSave<PackageLineEntity>())
line.Save();
tr.Commit();
}
}
catch (Exception e)
{
e.LogException();
}
}
return null;
});
}
}
public class PrintPackageAlgorithm : IProcessAlgorithm
{
public void Execute(ExecutingProcess executingProcess)
{
PrintPackageEntity package = (PrintPackageEntity)executingProcess.Data!;
executingProcess.ForEachLine(package.Lines().Where(a => a.State != PrintLineState.Printed), line =>
{
PrintLineGraph.Print(line);
});
}
}
public static PrintLineEntity CreateLine(Entity referred, FileTypeSymbol fileType, string fileName, byte[] content)
{
return CreateLine(referred, new FilePathEmbedded(fileType, fileName, content));
}
public static PrintLineEntity CreateLine(Entity referred, FilePathEmbedded file)
{
return new PrintLineEntity
{
Referred = referred.ToLite(),
State = PrintLineState.ReadyToPrint,
File = file,
}.Save();
}
public static ProcessEntity? CreateProcess(FileTypeSymbol? fileType = null)
{
using (Transaction tr = new Transaction())
{
var query = Database.Query<PrintLineEntity>()
.Where(a => a.State == PrintLineState.ReadyToPrint);
if (fileType != null)
query = query.Where(a => a.File.FileType == fileType);
if (query.Count() == 0)
return null;
var package = new PrintPackageEntity()
{
Name = fileType?.ToString() + " (" + query.Count() + ")"
}.Save();
query.UnsafeUpdate()
.Set(a => a.Package, a => package.ToLite())
.Set(a => a.State, a => PrintLineState.Enqueued)
.Execute();
var result = ProcessLogic.Create(PrintPackageProcess.PrintPackage, package).Save();
return tr.Commit(result);
}
}
public static List<PrintStat> GetReadyToPrintStats()
{
return Database.Query<PrintLineEntity>()
.Where(a => a.State == PrintLineState.ReadyToPrint)
.GroupBy(a => a.File.FileType)
.Select(gr => new PrintStat(gr.Key,gr.Count()))
.ToList();
}
public static void CancelPrinting(Entity entity, FileTypeSymbol fileType)
{
var list = ReadyToPrint(entity, fileType).ToList();
list.ForEach(a =>
{
a.State = PrintLineState.Cancelled;
a.File.DeleteFileOnCommit();
});
list.SaveList();
}
public static FileContent SavePrintLine(this FileContent file, Entity entity, FileTypeSymbol fileTypeForPrinting)
{
CancelPrinting(entity, fileTypeForPrinting);
CreateLine(entity, fileTypeForPrinting, Path.GetFileName(file.FileName)!, file.Bytes);
return file;
}
public static IQueryable<PrintLineEntity> ReadyToPrint(Entity entity, FileTypeSymbol fileType)
{
return Database.Query<PrintLineEntity>().Where(a => a.Referred.Is(entity) && a.File.FileType == fileType && a.State == PrintLineState.ReadyToPrint);
}
}
public class PrintStat
{
public FileTypeSymbol fileType;
public int count;
public PrintStat(FileTypeSymbol fileType, int count)
{
this.fileType = fileType;
this.count = count;
}
}
public class PrintLineGraph : Graph<PrintLineEntity, PrintLineState>
{
public static void Register()
{
GetState = e => e.State;
new Construct(PrintLineOperation.CreateTest)
{
ToStates = { PrintLineState.NewTest },
Construct = (args) => new PrintLineEntity
{
State = PrintLineState.NewTest,
TestFileType = PrintingLogic.TestFileType!,
}
}.Register();
new Execute(PrintLineOperation.SaveTest)
{
CanBeNew = true,
CanBeModified = true,
FromStates = { PrintLineState.NewTest },
ToStates = { PrintLineState.ReadyToPrint },
Execute = (e, _) => { e.State = PrintLineState.ReadyToPrint; }
}.Register();
new Execute(PrintLineOperation.Print)
{
FromStates = {PrintLineState.ReadyToPrint},
ToStates = {PrintLineState.Printed, PrintLineState.Error},
Execute = (e, _) =>
{
Print(e);
}
}.Register();
new Execute(PrintLineOperation.Retry)
{
FromStates = {PrintLineState.Error, PrintLineState.Cancelled},
ToStates = {PrintLineState.ReadyToPrint },
Execute = (e, _) =>
{
e.State = PrintLineState.ReadyToPrint;
e.Package = null;
}
}.Register();
new Execute(PrintLineOperation.Cancel)
{
FromStates = { PrintLineState.ReadyToPrint, PrintLineState.Error },
ToStates = { PrintLineState.Cancelled },
Execute = (e, _) =>
{
e.State = PrintLineState.Cancelled;
e.Package = null;
e.PrintedOn = null;
e.File.DeleteFileOnCommit();
}
}.Register();
}
public static void Print(PrintLineEntity line)
{
using (OperationLogic.AllowSave<PrintLineEntity>())
{
try
{
PrintingLogic.Print?.Invoke(line);
line.State = PrintLineState.Printed;
line.PrintedOn = TimeZoneManager.Now;
line.Save();
}
catch (Exception ex)
{
if (Transaction.InTestTransaction) //Transaction.IsTestTransaction
throw;
var exLog = ex.LogException().ToLite();
try
{
using (Transaction tr = Transaction.ForceNew())
{
line.State = PrintLineState.Error;
line.Save();
tr.Commit();
}
}
catch { }
throw;
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ValidatedMobileControlConverter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.Design.MobileControls.Converters
{
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.Design.MobileControls.Adapters;
using System.Web.UI.MobileControls;
[
System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
internal class ValidatedMobileControlConverter: StringConverter
{
private Form GetContainingForm(MobileControl mc)
{
return FindContainer(mc, typeof(Form)) as Form;
}
private StyleSheet GetContainingStyleSheet(MobileControl mc)
{
return FindContainer(mc, typeof(StyleSheet)) as StyleSheet;
}
private Control FindContainer(MobileControl mc, Type containerType)
{
for (Control control = mc; control != null; control = control.Parent)
{
if (containerType.IsAssignableFrom(control.GetType()))
{
return control;
}
}
return null;
}
protected virtual Object [] GetValidatableControls(Object instance)
{
System.Web.UI.MobileControls.BaseValidator thisValidator = null;
if (instance is Array)
{
Array controlList = (Array)instance;
Debug.Assert(controlList.Length > 0);
thisValidator = (BaseValidator) controlList.GetValue(0);
Form firstForm = GetContainingForm(thisValidator);
for (int i = 1; i < controlList.Length; i++)
{
BaseValidator validator = (BaseValidator)controlList.GetValue(i);
if (GetContainingForm(validator) != firstForm)
{
return null;
}
}
}
if (instance is System.Web.UI.MobileControls.BaseValidator)
{
thisValidator = (System.Web.UI.MobileControls.BaseValidator) instance;
}
else if (instance is ChoicePropertyFilter)
{
IDeviceSpecificDesigner designer =
((ChoicePropertyFilter)instance).Designer;
thisValidator = designer.UnderlyingObject
as System.Web.UI.MobileControls.BaseValidator;
}
if (thisValidator == null)
{
Debug.Fail("Unsupported object passed in");
return null;
}
ArrayList controlArray = new ArrayList();
if (GetContainingStyleSheet(thisValidator) != null)
{
ISite site = thisValidator.Site;
IContainer container = null;
if (site != null)
{
container = site.Container;
Debug.Assert(container != null);
foreach(IComponent component in container.Components)
{
Control control = component as Control;
if (control != null && CanBeValidated(control))
{
controlArray.Add(control.ID);
}
}
}
}
else
{
Form parentForm = GetContainingForm(thisValidator);
if (parentForm != null)
{
ExtractValidatableControls(parentForm, controlArray);
}
else
{
return null;
}
}
controlArray.Sort();
return controlArray.ToArray();
}
private void ExtractValidatableControls(Control parent, ArrayList controlArray)
{
foreach (Control control in parent.Controls)
{
if (CanBeValidated(control))
{
controlArray.Add(control.ID);
}
if (!(control is Form))
{
ExtractValidatableControls(control, controlArray);
}
}
}
private bool CanBeValidated(Control control)
{
// Control must have an ID
if (control.ID == null || control.ID.Length == 0)
{
return false;
}
// Control must have a ValidationProperty attribute
ValidationPropertyAttribute valProp =
(ValidationPropertyAttribute)
TypeDescriptor.GetAttributes(control)[typeof(ValidationPropertyAttribute)];
if (null != valProp && null != valProp.Name)
{
return true;
}
return false;
}
/// <summary>
/// <para>
/// Returns a collection of standard values retrieved from the context specified
/// by the specified type descriptor.
/// </para>
/// </summary>
/// <param name='context'>
/// A type descriptor that specifies the location of the context to convert from.
/// </param>
/// <returns>
/// <para>
/// A StandardValuesCollection that represents the standard values collected from
/// the specified context.
/// </para>
/// </returns>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
if (context == null || context.Instance == null)
{
return null;
}
Object [] objValues = GetValidatableControls(context.Instance);
if (objValues != null)
{
return new StandardValuesCollection(objValues);
}
else
{
return null;
}
}
/// <summary>
/// <para>
/// Gets whether
/// or not the context specified contains exclusive standard values.
/// </para>
/// </summary>
/// <param name='context'>
/// A type descriptor that indicates the context to convert from.
/// </param>
/// <returns>
/// <para>
/// <see langword='true'/> if the specified context contains exclusive standard
/// values, otherwise <see langword='false'/>.
/// </para>
/// </returns>
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
/// <summary>
/// <para>
/// Gets whether or not the specified context contains supported standard
/// values.
/// </para>
/// </summary>
/// <param name='context'>
/// A type descriptor that indicates the context to convert from.
/// </param>
/// <returns>
/// <para>
/// <see langword='true'/> if the specified context conatins supported standard
/// values, otherwise <see langword='false'/>.
/// </para>
/// </returns>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Contact Feed
///<para>SObject Name: ContactFeed</para>
///<para>Custom Object: False</para>
///</summary>
public class SfContactFeed : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ContactFeed"; }
}
///<summary>
/// Feed Item ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
[Updateable(false), Createable(false)]
public string ParentId { get; set; }
///<summary>
/// ReferenceTo: Contact
/// <para>RelationshipName: Parent</para>
///</summary>
[JsonProperty(PropertyName = "parent")]
[Updateable(false), Createable(false)]
public SfContact Parent { get; set; }
///<summary>
/// Feed Item Type
/// <para>Name: Type</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "type")]
[Updateable(false), Createable(false)]
public string Type { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Comment Count
/// <para>Name: CommentCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "commentCount")]
[Updateable(false), Createable(false)]
public int? CommentCount { get; set; }
///<summary>
/// Like Count
/// <para>Name: LikeCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "likeCount")]
[Updateable(false), Createable(false)]
public int? LikeCount { get; set; }
///<summary>
/// Title
/// <para>Name: Title</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "title")]
[Updateable(false), Createable(false)]
public string Title { get; set; }
///<summary>
/// Body
/// <para>Name: Body</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "body")]
[Updateable(false), Createable(false)]
public string Body { get; set; }
///<summary>
/// Link Url
/// <para>Name: LinkUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "linkUrl")]
[Updateable(false), Createable(false)]
public string LinkUrl { get; set; }
///<summary>
/// Is Rich Text
/// <para>Name: IsRichText</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRichText")]
[Updateable(false), Createable(false)]
public bool? IsRichText { get; set; }
///<summary>
/// Related Record ID
/// <para>Name: RelatedRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedRecordId")]
[Updateable(false), Createable(false)]
public string RelatedRecordId { get; set; }
///<summary>
/// InsertedBy ID
/// <para>Name: InsertedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "insertedById")]
[Updateable(false), Createable(false)]
public string InsertedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: InsertedBy</para>
///</summary>
[JsonProperty(PropertyName = "insertedBy")]
[Updateable(false), Createable(false)]
public SfUser InsertedBy { get; set; }
///<summary>
/// Best Comment ID
/// <para>Name: BestCommentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestCommentId")]
[Updateable(false), Createable(false)]
public string BestCommentId { get; set; }
///<summary>
/// ReferenceTo: FeedComment
/// <para>RelationshipName: BestComment</para>
///</summary>
[JsonProperty(PropertyName = "bestComment")]
[Updateable(false), Createable(false)]
public SfFeedComment BestComment { get; set; }
}
}
| |
// 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.
// The RegexReplacement class represents a substitution string for
// use when using regexes to search/replace, etc. It's logically
// a sequence intermixed (1) constant strings and (2) group numbers.
using System.Collections;
using System.Collections.Generic;
namespace System.Text.RegularExpressions
{
internal sealed class RegexReplacement
{
// Constants for special insertion patterns
private const int Specials = 4;
public const int LeftPortion = -1;
public const int RightPortion = -2;
public const int LastGroup = -3;
public const int WholeString = -4;
private readonly List<string> _strings; // table of string constants
private readonly List<int> _rules; // negative -> group #, positive -> string #
/// <summary>
/// Since RegexReplacement shares the same parser as Regex,
/// the constructor takes a RegexNode which is a concatenation
/// of constant strings and backreferences.
/// </summary>
public RegexReplacement(string rep, RegexNode concat, Hashtable _caps)
{
if (concat.Type() != RegexNode.Concatenate)
throw new ArgumentException(SR.ReplacementError);
Span<char> buffer = stackalloc char[256];
ValueStringBuilder vsb = new ValueStringBuilder(buffer);
List<string> strings = new List<string>();
List<int> rules = new List<int>();
for (int i = 0; i < concat.ChildCount(); i++)
{
RegexNode child = concat.Child(i);
switch (child.Type())
{
case RegexNode.Multi:
vsb.Append(child.Str);
break;
case RegexNode.One:
vsb.Append(child.Ch);
break;
case RegexNode.Ref:
if (vsb.Length > 0)
{
rules.Add(strings.Count);
strings.Add(vsb.ToString());
vsb.Length = 0;
}
int slot = child.M;
if (_caps != null && slot >= 0)
slot = (int)_caps[slot];
rules.Add(-Specials - 1 - slot);
break;
default:
throw new ArgumentException(SR.ReplacementError);
}
}
if (vsb.Length > 0)
{
rules.Add(strings.Count);
strings.Add(vsb.ToString());
}
Pattern = rep;
_strings = strings;
_rules = rules;
}
/// <summary>
/// Either returns a weakly cached RegexReplacement helper or creates one and caches it.
/// </summary>
/// <returns></returns>
public static RegexReplacement GetOrCreate(WeakReference<RegexReplacement> replRef, string replacement, Hashtable caps,
int capsize, Hashtable capnames, RegexOptions roptions)
{
RegexReplacement repl;
if (!replRef.TryGetTarget(out repl) || !repl.Pattern.Equals(replacement))
{
repl = RegexParser.ParseReplacement(replacement, roptions, caps, capsize, capnames);
replRef.SetTarget(repl);
}
return repl;
}
/// <summary>
/// The original pattern string
/// </summary>
public string Pattern { get; }
/// <summary>
/// Given a Match, emits into the StringBuilder the evaluated
/// substitution pattern.
/// </summary>
public void ReplacementImpl(ref ValueStringBuilder vsb, Match match)
{
for (int i = 0; i < _rules.Count; i++)
{
int r = _rules[i];
if (r >= 0) // string lookup
vsb.Append(_strings[r]);
else if (r < -Specials) // group lookup
vsb.Append(match.GroupToStringImpl(-Specials - 1 - r));
else
{
switch (-Specials - 1 - r)
{ // special insertion patterns
case LeftPortion:
vsb.Append(match.GetLeftSubstring());
break;
case RightPortion:
vsb.Append(match.GetRightSubstring());
break;
case LastGroup:
vsb.Append(match.LastGroupToStringImpl());
break;
case WholeString:
vsb.Append(match.Text);
break;
}
}
}
}
/// <summary>
/// Given a Match, emits into the ValueStringBuilder the evaluated
/// Right-to-Left substitution pattern.
/// </summary>
public void ReplacementImplRTL(ref ValueStringBuilder vsb, Match match)
{
for (int i = _rules.Count - 1; i >= 0; i--)
{
int r = _rules[i];
if (r >= 0) // string lookup
vsb.AppendReversed(_strings[r]);
else if (r < -Specials) // group lookup
vsb.AppendReversed(match.GroupToStringImpl(-Specials - 1 - r));
else
{
switch (-Specials - 1 - r)
{ // special insertion patterns
case LeftPortion:
vsb.AppendReversed(match.GetLeftSubstring());
break;
case RightPortion:
vsb.AppendReversed(match.GetRightSubstring());
break;
case LastGroup:
vsb.AppendReversed(match.LastGroupToStringImpl());
break;
case WholeString:
vsb.AppendReversed(match.Text);
break;
}
}
}
}
// Three very similar algorithms appear below: replace (pattern),
// replace (evaluator), and split.
/// <summary>
/// Replaces all occurrences of the regex in the string with the
/// replacement pattern.
///
/// Note that the special case of no matches is handled on its own:
/// with no matches, the input string is returned unchanged.
/// The right-to-left case is split out because StringBuilder
/// doesn't handle right-to-left string building directly very well.
/// </summary>
public string Replace(Regex regex, string input, int count, int startat)
{
if (count < -1)
throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall);
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
if (count == 0)
return input;
Match match = regex.Match(input, startat);
if (!match.Success)
{
return input;
}
else
{
Span<char> charInitSpan = stackalloc char[256];
var vsb = new ValueStringBuilder(charInitSpan);
if (!regex.RightToLeft)
{
int prevat = 0;
do
{
if (match.Index != prevat)
vsb.Append(input.AsSpan(prevat, match.Index - prevat));
prevat = match.Index + match.Length;
ReplacementImpl(ref vsb, match);
if (--count == 0)
break;
match = match.NextMatch();
} while (match.Success);
if (prevat < input.Length)
vsb.Append(input.AsSpan(prevat, input.Length - prevat));
}
else
{
// In right to left mode append all the inputs in reversed order to avoid an extra dynamic data structure
// and to be able to work with Spans. A final reverse of the transformed reversed input string generates
// the desired output. Similar to Tower of Hanoi.
int prevat = input.Length;
do
{
if (match.Index + match.Length != prevat)
vsb.AppendReversed(input.AsSpan(match.Index + match.Length, prevat - match.Index - match.Length));
prevat = match.Index;
ReplacementImplRTL(ref vsb, match);
if (--count == 0)
break;
match = match.NextMatch();
} while (match.Success);
if (prevat > 0)
vsb.AppendReversed(input.AsSpan(0, prevat));
vsb.Reverse();
}
return vsb.ToString();
}
}
}
}
| |
/*
Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace QS.Fx.Value
{
[QS.Fx.Printing.Printable("PropertyVersion", QS.Fx.Printing.PrintingStyle.Expanded, QS.Fx.Printing.SelectionOption.Explicit)]
[QS.Fx.Reflection.ValueClass(QS.Fx.Reflection.ValueClasses._s_propertyversion)]
[QS.Fx.Serialization.ClassID(QS.ClassID.PropertyVersion)]
public sealed class PropertyVersion : QS.Fx.Serialization.ISerializable, QS.Fx.Value.Classes.IPropertyVersion
{
#region Constructor
public PropertyVersion
(
QS.Fx.Base.Incarnation incarnation,
QS.Fx.Base.Index index
)
{
if ((incarnation == null) || (index == null))
throw new ArgumentException();
this.incarnation = incarnation;
this.index = index;
}
public PropertyVersion
(
ulong incarnation,
uint index
)
{
this.incarnation = new QS.Fx.Base.Incarnation(incarnation);
this.index = new QS.Fx.Base.Index(index);
}
public PropertyVersion()
{
}
#endregion
#region Fields
[QS.Fx.Base.Inspectable]
[QS.Fx.Printing.Printable("incarnation")]
private QS.Fx.Base.Incarnation incarnation;
[QS.Fx.Base.Inspectable]
[QS.Fx.Printing.Printable("index")]
private QS.Fx.Base.Index index;
#endregion
#region Accessors
public QS.Fx.Base.Incarnation Incarnation
{
get { return this.incarnation; }
}
public QS.Fx.Base.Index Index
{
get { return this.index; }
}
#endregion
#region QS.Fx.Value.Classes.IPropertyVersion Members
QS.Fx.Base.Incarnation QS.Fx.Value.Classes.IPropertyVersion.Incarnation
{
get { return this.incarnation; }
}
QS.Fx.Base.Index QS.Fx.Value.Classes.IPropertyVersion.Index
{
get { return this.index; }
}
#endregion
#region ISerializable Members
unsafe QS.Fx.Serialization.SerializableInfo QS.Fx.Serialization.ISerializable.SerializableInfo
{
get
{
QS.Fx.Serialization.SerializableInfo info = new QS.Fx.Serialization.SerializableInfo((ushort) QS.ClassID.PropertyVersion, 0);
info.AddAnother(this.incarnation.SerializableInfo);
info.AddAnother(this.index.SerializableInfo);
return info;
}
}
unsafe void QS.Fx.Serialization.ISerializable.SerializeTo(ref QS.Fx.Base.ConsumableBlock header, ref IList<QS.Fx.Base.Block> data)
{
this.incarnation.SerializeTo(ref header, ref data);
this.index.SerializeTo(ref header, ref data);
}
unsafe void QS.Fx.Serialization.ISerializable.DeserializeFrom(ref QS.Fx.Base.ConsumableBlock header, ref QS.Fx.Base.ConsumableBlock data)
{
this.incarnation = new QS.Fx.Base.Incarnation();
this.incarnation.DeserializeFrom(ref header, ref data);
this.index = new QS.Fx.Base.Index();
this.index.DeserializeFrom(ref header, ref data);
}
#endregion
#region IComparable<IPropertyVersion> Members
int IComparable<QS.Fx.Value.Classes.IPropertyVersion>.CompareTo(QS.Fx.Value.Classes.IPropertyVersion other)
{
int result = this.incarnation.CompareTo(other.Incarnation);
if (result == 0)
result = this.index.CompareTo(other.Index);
return result;
}
#endregion
#region IEquatable<QS.Fx.Value.Classes.IPropertyVersion> Members
bool IEquatable<QS.Fx.Value.Classes.IPropertyVersion>.Equals(QS.Fx.Value.Classes.IPropertyVersion other)
{
return this.incarnation.Equals(other.Incarnation) && this.index.Equals(other.Index);
}
#endregion
#region IComparable Members
int IComparable.CompareTo(object obj)
{
QS.Fx.Value.Classes.IPropertyVersion other = obj as QS.Fx.Value.Classes.IPropertyVersion;
if (other != null)
return ((IComparable<QS.Fx.Value.Classes.IPropertyVersion>) this).CompareTo(other);
else
throw new ArgumentException();
}
#endregion
#region Overridden from System.Object
public override bool Equals(object obj)
{
QS.Fx.Value.Classes.IPropertyVersion other = obj as QS.Fx.Value.Classes.IPropertyVersion;
if (other != null)
return ((IEquatable<QS.Fx.Value.Classes.IPropertyVersion>) this).Equals(other);
else
return false;
}
public override int GetHashCode()
{
return this.incarnation.GetHashCode() ^ this.index.GetHashCode();
}
public override string ToString()
{
StringBuilder ss = new StringBuilder();
ss.Append(this.incarnation.ToString());
ss.Append(":");
ss.Append(this.index.ToString());
return ss.ToString();
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Collections;
/// <summary>
/// CreateInstance Method (Type, Int32)
/// </summary>
public class ArrayCreateInstance1
{
const int c_MaxValue = 10;
const int c_MinValue = 0;
public static int Main()
{
ArrayCreateInstance1 ArrayCreateInstance1 = new ArrayCreateInstance1();
TestLibrary.TestFramework.BeginTestCase("ArrayCreateInstance1");
if (ArrayCreateInstance1.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: create a one-dimensional Array with int type.");
try
{
Array myArray = Array.CreateInstance(typeof(int), c_MaxValue);
int[] myIntArray = new int[c_MaxValue];
int generator = 0;
for (int i = 0; i < c_MaxValue; i++)
{
generator = TestLibrary.Generator.GetInt32(-55);
myArray.SetValue(generator, i);
myIntArray[i] = generator;
}
int index = c_MinValue;
for (IEnumerator itr = myArray.GetEnumerator(); itr.MoveNext(); )
{
object current = itr.Current;
if (!current.Equals(myIntArray[index]))
{
TestLibrary.TestFramework.LogError("001", "Create error.");
retVal = false;
break;
}
index++;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: create a one-dimensional Array with string type.");
try
{
Array myArray = Array.CreateInstance(typeof(string), c_MaxValue);
string[] myStringArray = new string[c_MaxValue];
string generator = string.Empty;
for (int i = 0; i < c_MaxValue; i++)
{
generator = TestLibrary.Generator.GetString(-55, true, c_MinValue, c_MaxValue);
myArray.SetValue(generator, i);
myStringArray[i] = generator;
}
int index = c_MinValue;
for (IEnumerator itr = myArray.GetEnumerator(); itr.MoveNext(); )
{
object current = itr.Current;
if (!current.Equals(myStringArray[index]))
{
TestLibrary.TestFramework.LogError("003", "Create error.");
retVal = false;
break;
}
index++;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: create a one-dimensional Array with user define type.");
try
{
Array myArray = Array.CreateInstance(typeof(Temperature), c_MaxValue);
Temperature[] myTemperatureArray = new Temperature[c_MaxValue];
Temperature generator = null;
for (int i = 0; i < c_MaxValue; i++)
{
generator = new Temperature();
generator.Value = i * 4;
myArray.SetValue(generator, i);
myTemperatureArray[i] = generator;
}
int index = c_MinValue;
for (IEnumerator itr = myArray.GetEnumerator(); itr.MoveNext(); )
{
object current = itr.Current;
if (!current.Equals(myTemperatureArray[index]))
{
TestLibrary.TestFramework.LogError("005", "Create error.");
retVal = false;
break;
}
index++;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: create a one-dimensional Array with user define Generic type.");
try
{
Array myArray = Array.CreateInstance(typeof(TestClass1<int>), c_MaxValue);
TestClass1<int>[] myTemperatureArray = new TestClass1<int>[c_MaxValue];
TestClass1<int> generator = null;
for (int i = 0; i < c_MaxValue; i++)
{
generator = new TestClass1<int>();
generator.Value = i * 4;
myArray.SetValue(generator, i);
myTemperatureArray[i] = generator;
}
int index = c_MinValue;
for (IEnumerator itr = myArray.GetEnumerator(); itr.MoveNext(); )
{
object current = itr.Current;
if (!current.Equals(myTemperatureArray[index]))
{
TestLibrary.TestFramework.LogError("007", "Create error.");
retVal = false;
break;
}
index++;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: elementType is a null reference .");
try
{
Array myArray = Array.CreateInstance(null, c_MaxValue);
TestLibrary.TestFramework.LogError("009", "elementType is a null reference should not be created.");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: elementType is not supported. Void is not supported.");
try
{
Array myArray = Array.CreateInstance(typeof(void), c_MaxValue);
TestLibrary.TestFramework.LogError("011", "Void should not be supported.");
retVal = false;
}
catch (NotSupportedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: elementType is an open generic type.");
try
{
Array myArray = Array.CreateInstance(typeof(TestClass1<>), c_MaxValue);
TestLibrary.TestFramework.LogError("013", "elementType is an open generic type.");
retVal = false;
}
catch (NotSupportedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
// Returns true if the expected result is right
// Returns false if the expected result is wrong
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: length is less than zero.");
try
{
Array myArray = Array.CreateInstance(typeof(int), c_MinValue -1);
TestLibrary.TestFramework.LogError("015", "length is less than zero.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
//create Temperature for provding test method and test target.
public class Temperature : System.Collections.IComparer
{
// The value holder
protected int m_value;
public int Value
{
get
{
return m_value;
}
set
{
m_value = value;
}
}
#region IComparer Members
public int Compare(object x, object y)
{
if (x is Temperature)
{
Temperature temp = (Temperature)x;
return ((Temperature)y).m_value.CompareTo(temp.m_value);
}
throw new Exception("The method parameter x is not expected.");
}
#endregion
}
public class TestClass1<T>
{
// The value holder
protected int m_value;
public int Value
{
get
{
return m_value;
}
set
{
m_value = value;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Threading;
using JetBrains.Annotations;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using SolidworksAddinFramework.Events;
using SolidworksAddinFramework.OpenGl;
using SolidWorks.Interop.sldworks;
using Weingartner.WeinCad.Interfaces;
using Weingartner.WeinCad.Interfaces.Drawing;
namespace SolidworksAddinFramework
{
public class OpenGlRenderer : IDisposable
{
public static ConcurrentDictionary<IModelDoc2, OpenGlRenderer> Lookup =
new ConcurrentDictionary<IModelDoc2, OpenGlRenderer>();
private static int _isInitialized;
public static IDisposable Setup(SldWorks swApp)
{
if (swApp == null)
throw new ArgumentNullException(nameof(swApp));
if (Interlocked.CompareExchange(ref _isInitialized, 1, 0) == 1) return Disposable.Empty;
var d0 = swApp
.DoWithOpenDoc(modelDoc =>
{
if (!modelDoc.Visible)
return Disposable.Empty;
var modelView = (ModelView) modelDoc.GetFirstModelView();
Lookup.GetOrAdd(modelDoc, mv => new OpenGlRenderer(modelView ));
return Disposable.Create(() =>
{
OpenGlRenderer openGlRenderer;
if (Lookup.TryRemove(modelDoc, out openGlRenderer))
{
openGlRenderer.Dispose();
}
});
});
var d1 = Disposable.Create(() =>
{
foreach (var modelView in Lookup.Keys)
{
OpenGlRenderer openGlRenderer;
Lookup.TryRemove(modelView, out openGlRenderer);
openGlRenderer.Dispose();
}
Debug.Assert(Lookup.IsEmpty);
});
return new CompositeDisposable(d0, d1);
}
public static IDisposable DisplayUndoable(IRenderer renderer, IModelDoc2 doc, int layer = 0)
{
if (renderer == null)
throw new ArgumentNullException(nameof(renderer));
if (doc == null)
throw new ArgumentNullException(nameof(doc));
OpenGlRenderer openGlRenderer;
if (Lookup.TryGetValue(doc, out openGlRenderer))
{
return openGlRenderer.DisplayUndoableImpl(renderer, doc, layer);
}
throw new Exception("Can't render OpenGL content, because the model view wasn't setup properly.");
}
private readonly ModelView _MView;
private readonly IDisposable _Disposable;
private OpenGlRenderer(ModelView mv)
{
if (mv == null)
throw new ArgumentNullException(nameof(mv));
_GlDoubleBuffer = new GLDoubleBuffer(mv);
_Scheduler = DispatcherScheduler.Current;
_MView = mv;
DoSetup();
_Disposable = _MView.BufferSwapNotifyObservable().Subscribe(args =>
{
var time = DateTime.Now;
var layers =
_GlDoubleBuffer.Front.GroupBy(o => o.Value.Item1)
.OrderBy(o => o.Key)
.Select(o => new {Index = o.Key, Renderables = o.Select(q => q.Value.Item2).ToList()})
.ToList();
foreach (var layer in layers)
{
// Clear the depth buffer after each subsequent layer. This
// will ensure that they are drawn on top of each other.
if(layer.Index!=0)
GL.Clear(ClearBufferMask.DepthBufferBit);
foreach (var r in layer.Renderables)
r.Render(time, _DrawContext);
}
});
_DrawContext = new OpenGLDrawContext();
}
private readonly GLDoubleBuffer _GlDoubleBuffer;
private readonly IScheduler _Scheduler;
private readonly IDrawContext _DrawContext;
private IDisposable DisplayUndoableImpl(IRenderer renderer, IModelDoc2 doc, int layer)
{
if (renderer == null)
throw new ArgumentNullException(nameof(renderer));
if (doc == null)
throw new ArgumentNullException(nameof(doc));
_GlDoubleBuffer.Update(b => b.SetItem(renderer, Tuple.Create(layer, renderer)));
Redraw(doc);
var s = renderer.NeedsRedraw.Subscribe(v => Redraw(doc));
var d = Disposable.Create(() =>
{
s.Dispose();
_GlDoubleBuffer.Update(btr =>
{
if (btr.ContainsKey(renderer))
{
return btr.Remove(renderer);
}
else
{
return btr;
}
});
Redraw(doc);
});
var t = Thread.CurrentThread;
return Disposable.Create
(() =>
{
Debug.Assert(Thread.CurrentThread == t);
d.Dispose();
});
}
private static void Redraw(IModelDoc2 doc)
{
if (doc == null)
throw new ArgumentNullException(nameof(doc));
((IReadOnlyDictionary<IModelDoc2, OpenGlRenderer>)Lookup)
.TryGetValue(doc)
.IfSome(renderer =>
{
var activeView = (IModelView) doc.ActiveView;
if (renderer._GlDoubleBuffer.FrontIsActive && renderer._GlDoubleBuffer.RedrawEnabled)
activeView.GraphicsRedraw(null);
});
}
public static IDisposable DisableRedraw(IModelDoc2 doc)
{
if (doc == null)
throw new ArgumentNullException(nameof(doc));
return ((IReadOnlyDictionary<IModelDoc2, OpenGlRenderer>)Lookup)
.TryGetValue(doc)
.Match(renderer =>
{
var activeView = (IModelView) doc.ActiveView;
renderer._GlDoubleBuffer.RedrawEnabled = false;
return Disposable.Create(() =>
{
renderer._GlDoubleBuffer.RedrawEnabled = true;
});
},
() => { throw new Exception("Unable to get renderer"); });
}
private void DoSetup()
{
////_MView.InitializeShading();
//var windowHandle = (IntPtr) _MView.GetViewHWndx64();
_MView.UpdateAllGraphicsLayers = true;
_MView.InitializeShading();
//Toolkit.Init();
//var windowInfo = Utilities.CreateWindowsWindowInfo(windowHandle);
////var context = new GraphicsContext(GraphicsMode.Default, windowInfo);
//var contextHandle = new ContextHandle(windowHandle);
//var context = new GraphicsContext(contextHandle, Wgl.GetProcAddress, () => contextHandle);
//context.MakeCurrent(windowInfo);
//context.LoadAll();
// TODO some resources are not disposed here.
// Really we should call `var tk = Toolkit.Init();` here (that's what `GLControl.ctor` does)
// and then dispose `tk`.
using (var ctrl = new GLControl())
using (ctrl.CreateGraphics())
{
}
//Toolkit.Init();
//IGraphicsContext context = new GraphicsContext(
// new ContextHandle(windowHandle),null );
//context.LoadAll();
}
public void Dispose()
{
_Disposable.Dispose();
}
private IDisposable DeferRedraw(Func<GLDoubleBuffer, IDisposable> action)
{
var d = action(_GlDoubleBuffer);
var t = Thread.CurrentThread;
return Disposable.Create
(() =>
{
Debug.Assert(Thread.CurrentThread == t);
d.Dispose();
});
}
private static IDisposable DeferRedraw([NotNull] IModelDoc2 doc, [NotNull] Func<GLDoubleBuffer, IDisposable> action)
{
if (doc == null) throw new ArgumentNullException(nameof(doc));
if (action == null) throw new ArgumentNullException(nameof(action));
return ((IReadOnlyDictionary<IModelDoc2, OpenGlRenderer>) Lookup)
.TryGetValue(doc)
.Match(
v => v.DeferRedraw(action),
() => Disposable.Empty
);
}
public static IDisposable DeferRedraw(IModelDoc2 doc, [NotNull] Func<IDisposable> fn)
{
if (fn == null) throw new ArgumentNullException(nameof(fn));
Func<GLDoubleBuffer, IDisposable> getDisposable = p => p.RunWithBackBuffer(fn);
return DeferRedraw(doc, getDisposable);
}
public static IDisposable DeferRedraw(IModelDoc2 doc)
{
return DeferRedraw(doc, b => b.SwitchToBackBufferTemporarily());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Authenticated.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.