context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// This code was generated by a tool. Please modify with caution. // using System; namespace TLS { public enum ContentTypeEnum { tls_change_cipher_spec=20,tls_alert=21,tls_handshake=22,tls_application_data=23 }; public class ContentType { public ContentTypeEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(ContentTypeEnum), value)) { this.value = (ContentTypeEnum)value; } return num_bytes; } } public enum ConnectionEndEnum { tls_server=1,tls_client=2 }; public class ConnectionEnd { public ConnectionEndEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(ConnectionEndEnum), value)) { this.value = (ConnectionEndEnum)value; } return num_bytes; } } public enum PRFAlgorithmEnum { tls_tls_prf_sha256=1 }; public class PRFAlgorithm { public PRFAlgorithmEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(PRFAlgorithmEnum), value)) { this.value = (PRFAlgorithmEnum)value; } return num_bytes; } } public enum BulkCipherAlgorithmEnum { tls_null=1,tls_rc4=2,tls_three_des=3,tls_aes=4 }; public class BulkCipherAlgorithm { public BulkCipherAlgorithmEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(BulkCipherAlgorithmEnum), value)) { this.value = (BulkCipherAlgorithmEnum)value; } return num_bytes; } } public enum CipherTypeEnum { tls_stream=1,tls_block=2,tls_aead=3 }; public class CipherType { public CipherTypeEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(CipherTypeEnum), value)) { this.value = (CipherTypeEnum)value; } return num_bytes; } } public enum MACAlgorithmEnum { tls_null=1,tls_hmac_md5=2,tls_hmac_sha1=3,tls_hmac_sha256=4,tls_hmac_sha384=5,tls_hmac_sha512=6 }; public class MACAlgorithm { public MACAlgorithmEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(MACAlgorithmEnum), value)) { this.value = (MACAlgorithmEnum)value; } return num_bytes; } } public enum Enum_0Enum { tls_change_cipher_spec=1 }; public class Enum_0 { public Enum_0Enum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(Enum_0Enum), value)) { this.value = (Enum_0Enum)value; } return num_bytes; } } public enum AlertLevelEnum { tls_warning=1,tls_fatal=2 }; public class AlertLevel { public AlertLevelEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(AlertLevelEnum), value)) { this.value = (AlertLevelEnum)value; } return num_bytes; } } public enum AlertDescriptionEnum { tls_close_notify=0,tls_unexpected_message=10,tls_bad_record_mac=20,tls_decryption_failed_RESERVED=21,tls_record_overflow=22,tls_decompression_failure=30,tls_handshake_failure=40,tls_no_certificate_RESERVED=41,tls_bad_certificate=42,tls_unsupported_certificate=43,tls_certificate_revoked=44,tls_certificate_expired=45,tls_certificate_unknown=46,tls_illegal_parameter=47,tls_unknown_ca=48,tls_access_denied=49,tls_decode_error=50,tls_decrypt_error=51,tls_export_restriction_RESERVED=60,tls_protocol_version=70,tls_insufficient_security=71,tls_internal_error=80,tls_user_canceled=90,tls_no_renegotiation=100,tls_unsupported_extension=110 }; public class AlertDescription { public AlertDescriptionEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(AlertDescriptionEnum), value)) { this.value = (AlertDescriptionEnum)value; } return num_bytes; } } public enum HandshakeTypeEnum { tls_hello_request=0,tls_client_hello=1,tls_server_hello=2,tls_certificate=11,tls_server_key_exchange=12,tls_certificate_request=13,tls_server_hello_done=14,tls_certificate_verify=15,tls_client_key_exchange=16,tls_finished=20 }; public class HandshakeType { public HandshakeTypeEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(HandshakeTypeEnum), value)) { this.value = (HandshakeTypeEnum)value; } return num_bytes; } } public enum CompressionMethodEnum { tls_null=0 }; public class CompressionMethod { public CompressionMethodEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(CompressionMethodEnum), value)) { this.value = (CompressionMethodEnum)value; } return num_bytes; } } public enum ExtensionTypeEnum { tls_signature_algorithms=13 }; public class ExtensionType { public ExtensionTypeEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(ExtensionTypeEnum), value)) { this.value = (ExtensionTypeEnum)value; } return num_bytes; } } public enum HashAlgorithmEnum { tls_none=0,tls_md5=1,tls_sha1=2,tls_sha224=3,tls_sha256=4,tls_sha384=5,tls_sha512=6 }; public class HashAlgorithm { public HashAlgorithmEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(HashAlgorithmEnum), value)) { this.value = (HashAlgorithmEnum)value; } return num_bytes; } } public enum SignatureAlgorithmEnum { tls_anonymous=0,tls_rsa=1,tls_dsa=2,tls_ecdsa=3 }; public class SignatureAlgorithm { public SignatureAlgorithmEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(SignatureAlgorithmEnum), value)) { this.value = (SignatureAlgorithmEnum)value; } return num_bytes; } } public enum KeyExchangeAlgorithmEnum { tls_dhe_dss=1,tls_dhe_rsa=2,tls_dh_anon=3,tls_rsa=4,tls_dh_dss=5,tls_dh_rsa=6 }; public class KeyExchangeAlgorithm { public KeyExchangeAlgorithmEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(KeyExchangeAlgorithmEnum), value)) { this.value = (KeyExchangeAlgorithmEnum)value; } return num_bytes; } } public enum ClientCertificateTypeEnum { tls_rsa_sign=1,tls_dss_sign=2,tls_rsa_fixed_dh=3,tls_dss_fixed_dh=4,tls_rsa_ephemeral_dh_RESERVED=5,tls_dss_ephemeral_dh_RESERVED=6,tls_fortezza_dms_RESERVED=20 }; public class ClientCertificateType { public ClientCertificateTypeEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(ClientCertificateTypeEnum), value)) { this.value = (ClientCertificateTypeEnum)value; } return num_bytes; } } public enum PublicValueEncodingEnum { tls_implicit=1,tls_explicit=2 }; public class PublicValueEncoding { public PublicValueEncodingEnum value; public int num_bytes = 1; public int Load(byte[] buffer,long offset) { long value; BufferTools.ReadNumberFromBuffer(buffer,offset,num_bytes,out value); if(Enum.IsDefined(typeof(PublicValueEncodingEnum), value)) { this.value = (PublicValueEncodingEnum)value; } return num_bytes; } } public class ProtocolVersion { public uint8 major = new uint8(); public uint8 minor = new uint8(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = major.Load(buffer,new_offset); new_offset = minor.Load(buffer,new_offset); return new_offset; } } public class TLSPlaintext { public ContentType type = new ContentType(); public ProtocolVersion version = new ProtocolVersion(); public uint16 length = new uint16(); public opaque fragment = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = type.Load(buffer,new_offset); new_offset = version.Load(buffer,new_offset); new_offset = length.Load(buffer,new_offset); new_offset = fragment.Load(buffer,new_offset); return new_offset; } } public class TLSCompressed { public ContentType type = new ContentType(); public ProtocolVersion version = new ProtocolVersion(); public uint16 length = new uint16(); public opaque fragment = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = type.Load(buffer,new_offset); new_offset = version.Load(buffer,new_offset); new_offset = length.Load(buffer,new_offset); new_offset = fragment.Load(buffer,new_offset); return new_offset; } } public class SecurityParameters { public ConnectionEnd entity = new ConnectionEnd(); public PRFAlgorithm prf_algorithm = new PRFAlgorithm(); public BulkCipherAlgorithm bulk_cipher_algorithm = new BulkCipherAlgorithm(); public CipherType cipher_type = new CipherType(); public uint8 enc_key_length = new uint8(); public uint8 block_length = new uint8(); public uint8 fixed_iv_length = new uint8(); public uint8 record_iv_length = new uint8(); public MACAlgorithm mac_algorithm = new MACAlgorithm(); public uint8 mac_length = new uint8(); public uint8 mac_key_length = new uint8(); public CompressionMethod compression_algorithm = new CompressionMethod(); public opaque master_secret = new opaque(); public opaque client_random = new opaque(); public opaque server_random = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = entity.Load(buffer,new_offset); new_offset = prf_algorithm.Load(buffer,new_offset); new_offset = bulk_cipher_algorithm.Load(buffer,new_offset); new_offset = cipher_type.Load(buffer,new_offset); new_offset = enc_key_length.Load(buffer,new_offset); new_offset = block_length.Load(buffer,new_offset); new_offset = fixed_iv_length.Load(buffer,new_offset); new_offset = record_iv_length.Load(buffer,new_offset); new_offset = mac_algorithm.Load(buffer,new_offset); new_offset = mac_length.Load(buffer,new_offset); new_offset = mac_key_length.Load(buffer,new_offset); new_offset = compression_algorithm.Load(buffer,new_offset); new_offset = master_secret.Load(buffer,new_offset); new_offset = client_random.Load(buffer,new_offset); new_offset = server_random.Load(buffer,new_offset); return new_offset; } } public class TLSCiphertext { public ContentType type = new ContentType(); public ProtocolVersion version = new ProtocolVersion(); public uint16 length = new uint16(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = type.Load(buffer,new_offset); new_offset = version.Load(buffer,new_offset); new_offset = length.Load(buffer,new_offset); return new_offset; } } public class GenericStreamCipher { public opaque content = new opaque(); public opaque MAC = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = content.Load(buffer,new_offset); new_offset = MAC.Load(buffer,new_offset); return new_offset; } } public class Struct_0 { public opaque content = new opaque(); public opaque MAC = new opaque(); public uint8 padding = new uint8(); public uint8 padding_length = new uint8(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = content.Load(buffer,new_offset); new_offset = MAC.Load(buffer,new_offset); new_offset = padding.Load(buffer,new_offset); new_offset = padding_length.Load(buffer,new_offset); return new_offset; } } public class GenericBlockCipher { public opaque IV = new opaque(); public Struct_0 Struct_0_instance = new Struct_0(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = IV.Load(buffer,new_offset); new_offset = Struct_0_instance.Load(buffer,new_offset); return new_offset; } } public class Struct_1 { public opaque content = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = content.Load(buffer,new_offset); return new_offset; } } public class GenericAEADCipher { public opaque nonce_explicit = new opaque(); public Struct_1 Struct_1_instance = new Struct_1(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = nonce_explicit.Load(buffer,new_offset); new_offset = Struct_1_instance.Load(buffer,new_offset); return new_offset; } } public class ChangeCipherSpec { public Enum_0 type = new Enum_0(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = type.Load(buffer,new_offset); return new_offset; } } public class Alert { public AlertLevel level = new AlertLevel(); public AlertDescription description = new AlertDescription(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = level.Load(buffer,new_offset); new_offset = description.Load(buffer,new_offset); return new_offset; } } public class Handshake { public HandshakeType msg_type = new HandshakeType(); public uint24 length = new uint24(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = msg_type.Load(buffer,new_offset); new_offset = length.Load(buffer,new_offset); return new_offset; } } public class HelloRequest { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class Random { public uint32 gmt_unix_time = new uint32(); public opaque random_bytes = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = gmt_unix_time.Load(buffer,new_offset); new_offset = random_bytes.Load(buffer,new_offset); return new_offset; } } public class SessionID { public opaque data = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = data.Load(buffer,new_offset); return new_offset; } } public class CipherSuite { public uint8 data = new uint8(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = data.Load(buffer,new_offset); return new_offset; } } public class Struct_2 { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class ClientHello { public ProtocolVersion client_version = new ProtocolVersion(); public Random random = new Random(); public SessionID session_id = new SessionID(); public CipherSuite cipher_suites = new CipherSuite(); public CompressionMethod compression_methods = new CompressionMethod(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = client_version.Load(buffer,new_offset); new_offset = random.Load(buffer,new_offset); new_offset = session_id.Load(buffer,new_offset); new_offset = cipher_suites.Load(buffer,new_offset); new_offset = compression_methods.Load(buffer,new_offset); return new_offset; } } public class Struct_3 { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class ServerHello { public ProtocolVersion server_version = new ProtocolVersion(); public Random random = new Random(); public SessionID session_id = new SessionID(); public CipherSuite cipher_suite = new CipherSuite(); public CompressionMethod compression_method = new CompressionMethod(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = server_version.Load(buffer,new_offset); new_offset = random.Load(buffer,new_offset); new_offset = session_id.Load(buffer,new_offset); new_offset = cipher_suite.Load(buffer,new_offset); new_offset = compression_method.Load(buffer,new_offset); return new_offset; } } public class Extension { public ExtensionType extension_type = new ExtensionType(); public opaque extension_data = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = extension_type.Load(buffer,new_offset); new_offset = extension_data.Load(buffer,new_offset); return new_offset; } } public class SignatureAndHashAlgorithm { public HashAlgorithm hash = new HashAlgorithm(); public SignatureAlgorithm signature = new SignatureAlgorithm(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = hash.Load(buffer,new_offset); new_offset = signature.Load(buffer,new_offset); return new_offset; } } public class supported_signature_algorithms { public SignatureAndHashAlgorithm data = new SignatureAndHashAlgorithm(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = data.Load(buffer,new_offset); return new_offset; } } public class ASN1Cert { public opaque data = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = data.Load(buffer,new_offset); return new_offset; } } public class Certificate { public ASN1Cert certificate_list = new ASN1Cert(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = certificate_list.Load(buffer,new_offset); return new_offset; } } public class ServerDHParams { public opaque dh_p = new opaque(); public opaque dh_g = new opaque(); public opaque dh_Ys = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = dh_p.Load(buffer,new_offset); new_offset = dh_g.Load(buffer,new_offset); new_offset = dh_Ys.Load(buffer,new_offset); return new_offset; } } public class Struct_4 { public opaque client_random = new opaque(); public opaque server_random = new opaque(); public ServerDHParams paramsx = new ServerDHParams(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = client_random.Load(buffer,new_offset); new_offset = server_random.Load(buffer,new_offset); new_offset = paramsx.Load(buffer,new_offset); return new_offset; } } public class Struct_5 { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class ServerKeyExchange { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class DistinguishedName { public opaque data = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = data.Load(buffer,new_offset); return new_offset; } } public class CertificateRequest { public ClientCertificateType certificate_types = new ClientCertificateType(); public DistinguishedName certificate_authorities = new DistinguishedName(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = certificate_types.Load(buffer,new_offset); new_offset = certificate_authorities.Load(buffer,new_offset); return new_offset; } } public class ServerHelloDone { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class ClientKeyExchange { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class PreMasterSecret { public ProtocolVersion client_version = new ProtocolVersion(); public opaque random = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = client_version.Load(buffer,new_offset); new_offset = random.Load(buffer,new_offset); return new_offset; } } public class EncryptedPreMasterSecret { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class Struct_6 { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class ClientDiffieHellmanPublic { public long Load(byte[] buffer,long offset) { long new_offset = offset; return new_offset; } } public class Struct_7 { public opaque handshake_messages = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = handshake_messages.Load(buffer,new_offset); return new_offset; } } public class CertificateVerify { public Struct_7 Struct_7_instance = new Struct_7(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = Struct_7_instance.Load(buffer,new_offset); return new_offset; } } public class Finished { public opaque verify_data = new opaque(); public long Load(byte[] buffer,long offset) { long new_offset = offset; new_offset = verify_data.Load(buffer,new_offset); return new_offset; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using System.IO; using ParquetSharp.Event; using ParquetSharp.External; using ParquetSharp.Format; using Thrift; using Thrift.Protocol; using Thrift.Transport; using static ParquetSharp.Event.Consumers; using static ParquetSharp.Event.TypedConsumer; namespace ParquetSharp { /** * Utility to read/write metadata * We use the TCompactProtocol to serialize metadata * * @author Julien Le Dem * */ public static class Util { const short VERSION = 1; const short SCHEMA = 2; const short NUM_ROWS = 3; const short ROW_GROUPS = 4; const short KEY_VALUE_METADATA = 5; const short CREATED_BY = 6; public static void writePageHeader(PageHeader pageHeader, OutputStream to) { write(pageHeader, to); } public static PageHeader readPageHeader(InputStream from) { return read(from, new PageHeader()); } public static void writeFileMetaData(FileMetaData fileMetadata, OutputStream to) { write(fileMetadata, to); } public static FileMetaData readFileMetaData(InputStream from) { return read(from, new FileMetaData()); } /** * reads the meta data from the stream * @param from the stream to read the metadata from * @param skipRowGroups whether row groups should be skipped * @return the resulting metadata */ public static FileMetaData readFileMetaData(InputStream from, bool skipRowGroups) { FileMetaData md = new FileMetaData(); if (skipRowGroups) { readFileMetaData(from, new DefaultFileMetaDataConsumer(md), skipRowGroups); } else { read(from, md); } return md; } /** * To read metadata in a streaming fashion. * * @author Julien Le Dem * */ public abstract class FileMetaDataConsumer { abstract public void setVersion(int version); abstract public void setSchema(List<SchemaElement> schema); abstract public void setNumRows(long numRows); abstract public void addRowGroup(RowGroup rowGroup); abstract public void addKeyValueMetaData(KeyValue kv); abstract public void setCreatedBy(string createdBy); } /** * Simple default consumer that sets the fields * * @author Julien Le Dem * */ public sealed class DefaultFileMetaDataConsumer : FileMetaDataConsumer { private readonly FileMetaData md; public DefaultFileMetaDataConsumer(FileMetaData md) { this.md = md; } public override void setVersion(int version) { md.Version = version; } public override void setSchema(List<SchemaElement> schema) { md.Schema = schema; } public override void setNumRows(long numRows) { md.Num_rows = numRows; } public override void setCreatedBy(string createdBy) { md.Created_by = createdBy; } public override void addRowGroup(RowGroup rowGroup) { md.Row_groups.Add(rowGroup); } public override void addKeyValueMetaData(KeyValue kv) { md.Key_value_metadata.Add(kv); } } public static void readFileMetaData(InputStream from, FileMetaDataConsumer consumer) { readFileMetaData(from, consumer, false); } public static void readFileMetaData(InputStream from, FileMetaDataConsumer consumer, bool skipRowGroups) { try { DelegatingFieldConsumer eventConsumer = fieldConsumer() .onField(VERSION, new VersionConsumer(consumer)) .onField(SCHEMA, listOf(typeof(SchemaElement), new SchemaConsumer(consumer))) .onField(NUM_ROWS, new NumRowsConsumer(consumer)) .onField(KEY_VALUE_METADATA, listElementsOf(@struct(typeof(KeyValue), new KeyValueConsumer(consumer)))) .onField(CREATED_BY, new CreatedByConsumer(consumer)); if (!skipRowGroups) { eventConsumer = eventConsumer.onField(ROW_GROUPS, listElementsOf(@struct(typeof(RowGroup), new RowGroupConsumer(consumer)))); } new EventBasedThriftReader(protocol(from)).readStruct(eventConsumer); } catch (TException e) { throw new IOException("can not read FileMetaData: " + e.Message, e); } } private static TProtocol protocol(OutputStream to) { // TODO: return protocol(new TStreamTransport(to, to)); } private static TProtocol protocol(InputStream from) { // TODO: return protocol(new TStreamTransport(from, from)); } private static InterningProtocol protocol(TStreamTransport t) { return new InterningProtocol(new TCompactProtocol(t)); } private static T read<T>(InputStream from, T tbase) where T : TBase { try { tbase.Read(protocol(from)); return tbase; } catch (TException e) { throw new IOException("can not read " + typeof(T).Name + ": " + e.Message, e); } } private static void write<T>(T tbase, OutputStream to) where T : TBase { try { tbase.Write(protocol(to)); } catch (TException e) { throw new IOException("can not write " + tbase, e); } } class VersionConsumer : I32Consumer { readonly FileMetaDataConsumer consumer; public VersionConsumer(FileMetaDataConsumer consumer) { this.consumer = consumer; } public override void consume(int value) { consumer.setVersion(value); } } class SchemaConsumer : Consumer<List<SchemaElement>> { readonly FileMetaDataConsumer consumer; public SchemaConsumer(FileMetaDataConsumer consumer) { this.consumer = consumer; } public void consume(List<SchemaElement> value) { consumer.setSchema(value); } } class NumRowsConsumer : I64Consumer { readonly FileMetaDataConsumer consumer; public NumRowsConsumer(FileMetaDataConsumer consumer) { this.consumer = consumer; } public override void consume(long value) { consumer.setNumRows(value); } } class KeyValueConsumer : Consumer<KeyValue> { readonly FileMetaDataConsumer consumer; public KeyValueConsumer(FileMetaDataConsumer consumer) { this.consumer = consumer; } public void consume(KeyValue value) { consumer.addKeyValueMetaData(value); } } class CreatedByConsumer : StringConsumer { readonly FileMetaDataConsumer consumer; public CreatedByConsumer(FileMetaDataConsumer consumer) { this.consumer = consumer; } public override void consume(string value) { consumer.setCreatedBy(value); } } class RowGroupConsumer : Consumer<RowGroup> { readonly FileMetaDataConsumer consumer; public RowGroupConsumer(FileMetaDataConsumer consumer) { this.consumer = consumer; } public void consume(RowGroup value) { consumer.addRowGroup(value); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ArrayExpansionTests : CSharpResultProviderTestBase { [Fact] public void Array() { var rootExpr = "new[] { 1, 2, 3 }"; var value = CreateDkmClrValue(new[] { 1, 2, 3 }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3]}", "int[]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "(new[] { 1, 2, 3 })[0]"), EvalResult("[1]", "2", "int", "(new[] { 1, 2, 3 })[1]"), EvalResult("[2]", "3", "int", "(new[] { 1, 2, 3 })[2]")); } [Fact] public void ZeroLengthArray() { var rootExpr = "new object[0]"; var value = CreateDkmClrValue(new object[0]); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{object[0]}", "object[]", rootExpr)); DkmEvaluationResultEnumContext enumContext; var children = GetChildren(evalResult, 100, null, out enumContext); Verify(children); var items = GetItems(enumContext, 0, enumContext.Count); Verify(items); } [Fact] public void NestedArray() { var rootExpr = "new int[][] { new[] { 1, 2 }, new[] { 3 } }"; var value = CreateDkmClrValue(new int[][] { new[] { 1, 2 }, new[] { 3 } }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2][]}", "int[][]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "{int[2]}", "int[]", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0]", DkmEvaluationResultFlags.Expandable), EvalResult("[1]", "{int[1]}", "int[]", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[1]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[0]), EvalResult("[0]", "1", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0][0]"), EvalResult("[1]", "2", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[0][1]")); Verify(GetChildren(children[1]), EvalResult("[0]", "3", "int", "(new int[][] { new[] { 1, 2 }, new[] { 3 } })[1][0]")); } [Fact] public void MultiDimensionalArray() { var rootExpr = "new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }"; var value = CreateDkmClrValue(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3, 2]}", "int[,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0, 0]", "1", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[0, 0]"), EvalResult("[0, 1]", "2", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[0, 1]"), EvalResult("[1, 0]", "3", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[1, 0]"), EvalResult("[1, 1]", "4", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[1, 1]"), EvalResult("[2, 0]", "5", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[2, 0]"), EvalResult("[2, 1]", "6", "int", "(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } })[2, 1]")); } [Fact] public void ZeroLengthMultiDimensionalArray() { var rootExpr = "new int[2, 3, 0]"; var value = CreateDkmClrValue(new int[2, 3, 0]); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2, 3, 0]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[2, 0, 3]"; value = CreateDkmClrValue(new int[2, 0, 3]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[2, 0, 3]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[0, 2, 3]"; value = CreateDkmClrValue(new int[0, 2, 3]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[0, 2, 3]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); rootExpr = "new int[0, 0, 0]"; value = CreateDkmClrValue(new int[0, 0, 0]); evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[0, 0, 0]}", "int[,,]", rootExpr)); Verify(GetChildren(evalResult)); } [Fact] public void NullArray() { var rootExpr = "new int[][,,] { null, new int[2, 3, 4] }"; var evalResult = FormatResult(rootExpr, CreateDkmClrValue(new int[][,,] { null, new int[2, 3, 4] })); Verify(evalResult, EvalResult(rootExpr, "{int[2][,,]}", "int[][,,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "null", "int[,,]", "(new int[][,,] { null, new int[2, 3, 4] })[0]"), EvalResult("[1]", "{int[2, 3, 4]}", "int[,,]", "(new int[][,,] { null, new int[2, 3, 4] })[1]", DkmEvaluationResultFlags.Expandable)); } [Fact] public void BaseType() { var source = @"class C { object o = new int[] { 1, 2 }; System.Array a = new object[] { null }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var rootExpr = "new C()"; var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("a", "{object[1]}", "System.Array {object[]}", "(new C()).a", DkmEvaluationResultFlags.Expandable), EvalResult("o", "{int[2]}", "object {int[]}", "(new C()).o", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[0]), EvalResult("[0]", "null", "object", "((object[])(new C()).a)[0]")); Verify(GetChildren(children[1]), EvalResult("[0]", "1", "int", "((int[])(new C()).o)[0]"), EvalResult("[1]", "2", "int", "((int[])(new C()).o)[1]")); } [WorkItem(933845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933845")] [Fact] public void BaseElementType() { var source = @"class A { internal object F; } class B : A { internal B(object f) { F = f; } internal object P { get { return this.F; } } }"; var assembly = GetAssembly(source); var typeB = assembly.GetType("B"); var value = CreateDkmClrValue(new object[] { 1, typeB.Instantiate(2) }); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{object[2]}", "object[]", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "object {int}", "o[0]"), EvalResult("[1]", "{B}", "object {B}", "o[1]", DkmEvaluationResultFlags.Expandable)); children = GetChildren(children[1]); Verify(children, EvalResult("F", "2", "object {int}", "((A)o[1]).F"), EvalResult("P", "2", "object {int}", "((B)o[1]).P", DkmEvaluationResultFlags.ReadOnly)); } [WorkItem(1022157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1022157")] [Fact] public void Covariance() { var source = @"interface I { } class A { object F = 1; } class B : A, I { } class C { object[] F = new[] { new A() }; A[] G = new[] { new B() }; I[] H = new[] { new B() }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{A[1]}", "object[] {A[]}", "o.F", DkmEvaluationResultFlags.Expandable), EvalResult("G", "{B[1]}", "A[] {B[]}", "o.G", DkmEvaluationResultFlags.Expandable), EvalResult("H", "{B[1]}", "I[] {B[]}", "o.H", DkmEvaluationResultFlags.Expandable)); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult("[0]", "{A}", "object {A}", "((A[])o.F)[0]", DkmEvaluationResultFlags.Expandable)); moreChildren = GetChildren(moreChildren[0]); Verify(moreChildren, EvalResult("F", "1", "object {int}", "((A)((A[])o.F)[0]).F")); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult("[0]", "{B}", "A {B}", "((B[])o.G)[0]", DkmEvaluationResultFlags.Expandable)); moreChildren = GetChildren(children[2]); Verify(moreChildren, EvalResult("[0]", "{B}", "I {B}", "((B[])o.H)[0]", DkmEvaluationResultFlags.Expandable)); } [WorkItem(1001844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1001844")] [Fact] public void Interface() { var source = @"class C { char[] F = new char[] { '1' }; System.Collections.IEnumerable G = new char[] { '2' }; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(Activator.CreateInstance(type)); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "{char[1]}", "char[]", "o.F", DkmEvaluationResultFlags.Expandable), EvalResult("G", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o.G", DkmEvaluationResultFlags.Expandable)); var moreChildren = GetChildren(children[0]); Verify(moreChildren, EvalResult("[0]", "49 '1'", "char", "o.F[0]", editableValue: "'1'")); moreChildren = GetChildren(children[1]); Verify(moreChildren, EvalResult("[0]", "50 '2'", "char", "((char[])o.G)[0]", editableValue: "'2'")); } [Fact] public void NonZeroLowerBounds() { var rootExpr = "arrayExpr"; var array = (int[,])System.Array.CreateInstance(typeof(int), new[] { 2, 3 }, new[] { 3, 4 }); array[3, 4] = 1; array[3, 5] = 2; array[3, 6] = 3; array[4, 4] = 4; array[4, 5] = 5; array[4, 6] = 6; var value = CreateDkmClrValue(array); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{int[3..4, 4..6]}", "int[,]", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[3, 4]", "1", "int", "arrayExpr[3, 4]"), EvalResult("[3, 5]", "2", "int", "arrayExpr[3, 5]"), EvalResult("[3, 6]", "3", "int", "arrayExpr[3, 6]"), EvalResult("[4, 4]", "4", "int", "arrayExpr[4, 4]"), EvalResult("[4, 5]", "5", "int", "arrayExpr[4, 5]"), EvalResult("[4, 6]", "6", "int", "arrayExpr[4, 6]")); } /// <summary> /// Expansion should be lazy so that the IDE can /// reduce overhead by expanding a subset of rows. /// </summary> [Fact] public void LazyExpansion() { var rootExpr = "new byte[10, 1000, 1000]"; var parenthesizedExpr = string.Format("({0})", rootExpr); var value = CreateDkmClrValue(new byte[10, 1000, 1000]); // Array with 10M elements var evalResults = new DkmEvaluationResult[100]; // 100 distinct evaluations of the array for (int i = 0; i < evalResults.Length; i++) { var evalResult = FormatResult(rootExpr, value); evalResults[i] = evalResult; // Expand a subset. int offset = i * 100 * 1000; DkmEvaluationResultEnumContext enumContext; GetChildren(evalResult, 0, null, out enumContext); var items = GetItems(enumContext, offset, 2); var indices1 = string.Format("{0}, {1}, {2}", offset / 1000000, (offset % 1000000) / 1000, 0); var indices2 = string.Format("{0}, {1}, {2}", (offset + 1) / 1000000, ((offset + 1) % 1000000) / 1000, 1); Verify(items, EvalResult(string.Format("[{0}]", indices1), "0", "byte", string.Format("{0}[{1}]", parenthesizedExpr, indices1)), EvalResult(string.Format("[{0}]", indices2), "0", "byte", string.Format("{0}[{1}]", parenthesizedExpr, indices2))); } } } }
/** * Kronometer - Makes the KSP clock easily editable * Copyright (c) 2017 Sigma88, Thomas P. * Licensed under the Terms of the MIT License */ using System; using System.Collections.Generic; using Kopernicus.ConfigParser.Attributes; using Kopernicus.ConfigParser.BuiltinTypeParsers; using Kopernicus.ConfigParser.Enumerations; namespace Kronometer { /// <summary> /// Loads the settings that control Kronometer /// </summary> [RequireConfigType(ConfigType.Node)] public class SettingsLoader { // Whether to calculate the length of a day based on the orbital parameters of the home body [ParserTarget("useHomeDay")] public NumericParser<bool> useHomeDay = new NumericParser<bool>(false); // Calculates the length of a year based on the orbit of the home body [ParserTarget("useHomeYear")] public NumericParser<bool> useHomeYear = new NumericParser<bool>(false); // Automatically adds leap years if the day length and year length dont fit [ParserTarget("useLeapYears")] public NumericParser<bool> useLeapYears = new NumericParser<bool>(false); // Load Custom Time [ParserTarget("CustomTime", AllowMerge = true, Optional = true)] public ClockLoader Clock = new ClockLoader(); // Load Custom Months [ParserTargetCollection("Months", AllowMerge = true)] public List<Month> calendar = new List<Month>(); // This defines after how many months the number displayed will reset back to 1 // This needs to load after the list of months public Int32 resetMonthNum { get; set; } [ParserTarget("resetMonthNumAfterMonths")] private NumericParser<int> resetMonthNumLoader { set { if (value > 0) resetMonthNum = value; else if (calendar.Count > 0) resetMonthNum = calendar.Count; else resetMonthNum = 1; } } // This defines after how many years the actual months will reset back to the first month public Int32 resetMonths = 1; [ParserTarget("resetMonthsAfterYears")] private NumericParser<int> resetMonthsLoader { set { if (value > 0) resetMonths = value; } } // Load Custom Display [ParserTarget("DisplayDate", AllowMerge = true, Optional = true)] public CustomDisplay Display = new CustomDisplay(); } /// <summary> /// Loader for time units names, symbols, and durations /// </summary> [RequireConfigType(ConfigType.Node)] public class ClockLoader { [ParserTarget("Second", AllowMerge = true)] public TimeUnits second = new TimeUnits("Second", "Seconds", "s", 1); [ParserTarget("Minute", AllowMerge = true)] public TimeUnits minute = new TimeUnits("Minute", "Minutes", "m", 60); [ParserTarget("Hour", AllowMerge = true)] public TimeUnits hour = new TimeUnits("Hour", "Hours", "h", 3600); [ParserTarget("Day", AllowMerge = true)] public TimeUnits day = new TimeUnits("Day", "Days", "d", 3600 * (GameSettings.KERBIN_TIME ? 6 : 24)); [ParserTarget("Year", AllowMerge = true)] public TimeUnits year = new TimeUnits("Year", "Years", "y", 3600 * (GameSettings.KERBIN_TIME ? 6 * 426 : 24 * 365)); } /// <summary> /// Class to handle time units easily /// </summary> [RequireConfigType(ConfigType.Node)] public class TimeUnits { [ParserTarget("singular")] public string singular; [ParserTarget("plural")] public string plural; [ParserTarget("symbol")] public string symbol; [ParserTarget("value")] public NumericParser<double> value; [ParserTarget("roundToNearestInt")] public NumericParser<bool> round; public TimeUnits(string singular, string plural, string symbol, double value, bool round = false) { this.singular = singular; this.plural = plural; this.symbol = symbol; this.value = round ? Math.Round(value, 0) : value; this.round = round; } } /// <summary> /// Loader for custom dates /// </summary> [RequireConfigType(ConfigType.Node)] public class CustomDisplay { [ParserTarget("PrintDate", AllowMerge = true)] public DisplayLoader CustomPrintDate = new DisplayLoader(0, 1, 1, "<Y1> <Y>, <D1> <D>", " - <H><H0><M><M0>", ", <S><S0>"); [ParserTarget("PrintDateNew", AllowMerge = true)] public DisplayLoader CustomPrintDateNew = new DisplayLoader(0, 1, 1, "<Y1> <Y>, <D1> <D>", " - <H:D2>:<M:D2>:<S:D2>", ""); [ParserTarget("PrintDateCompact", AllowMerge = true)] public DisplayLoader CustomPrintDateCompact = new DisplayLoader(0, 1, 1, "<Y0><Y>, <D0><D:00>", ", <H>:<M:00>", ":<S:00>"); } /// <summary> /// Loader for custom date display formats /// </summary> [RequireConfigType(ConfigType.Node)] public class DisplayLoader { [ParserTarget("offsetTime")] public NumericParser<double> offsetTime; [ParserTarget("offsetYear")] public NumericParser<int> offsetYear; [ParserTarget("offsetDay")] public NumericParser<int> offsetDay; [ParserTarget("displayDate")] public string displayDate; [ParserTarget("displayTime")] public string displayTime; [ParserTarget("displaySeconds")] public string displaySeconds; public DisplayLoader(double offsetTime, int offsetYear, int offsetDay, string displayDate, string displayTime, string displaySeconds) { this.offsetTime = offsetTime; this.offsetYear = offsetYear; this.offsetDay = offsetDay; this.displayDate = displayDate; this.displayTime = displayTime; this.displaySeconds = displaySeconds; } } /// <summary> /// Small class to handle months /// </summary> [RequireConfigType(ConfigType.Node)] public class Month { [ParserTarget("name")] public string name = ""; [ParserTarget("symbol")] public string symbol = ""; [ParserTarget("days")] public NumericParser<int> days = 0; public Int32 Number(List<Month> calendar, Int32 resetMonthNum) { if (calendar.Contains(this)) return (calendar.IndexOf(this) % resetMonthNum) + 1; return 0; } public Month() { name = ""; symbol = ""; days = 0; } public Month(string name, string symbol, int days) { this.name = name; this.symbol = symbol; this.days = days; } } }
using System; using System.Globalization; using System.IO; using System.Text; using System.Xml; using System.Reflection; using System.Threading; using NUnit.Framework; using CookComputing.XmlRpc; namespace ntest { [TestFixture] public class OptionalSerializeTest { struct ChildStruct { public int x; public ChildStruct(int num) { x = num; } } struct Struct0 { public XmlRpcInt xi; public XmlRpcBoolean xb; public XmlRpcDouble xd; public XmlRpcDateTime xdt; #if !FX1_0 public int? nxi; public bool? nxb; public double? nxd; public DateTime? nxdt; public ChildStruct? nxstr; #endif } struct Struct1 { public int mi; public string ms; public bool mb; public double md; public DateTime mdt; public byte[] mb64; public int[] ma; public XmlRpcInt xi; public XmlRpcBoolean xb; public XmlRpcDouble xd; public XmlRpcDateTime xdt; public XmlRpcStruct xstr; #if !FX1_0 public int? nxi; public bool? nxb; public double? nxd; public DateTime? nxdt; public ChildStruct? nxstr; #endif } [XmlRpcMissingMapping(MappingAction.Error)] struct Struct2 { public int mi; public string ms; public bool mb; public double md; public DateTime mdt; public byte[] mb64; public int[] ma; public XmlRpcInt xi; public XmlRpcBoolean xb; public XmlRpcDouble xd; public XmlRpcDateTime xdt; public XmlRpcStruct xstr; #if !FX1_0 public int? nxi; public bool? nxb; public double? nxd; public DateTime? nxdt; public ChildStruct? nxstr; #endif } struct Struct3 { [XmlRpcMissingMapping(MappingAction.Error)] public int mi; [XmlRpcMissingMapping(MappingAction.Error)] public string ms; [XmlRpcMissingMapping(MappingAction.Error)] public bool mb; [XmlRpcMissingMapping(MappingAction.Error)] public double md; [XmlRpcMissingMapping(MappingAction.Error)] public DateTime mdt; [XmlRpcMissingMapping(MappingAction.Error)] public byte[] mb64; [XmlRpcMissingMapping(MappingAction.Error)] public int[] ma; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcInt xi; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcBoolean xb; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcDouble xd; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcDateTime xdt; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcStruct xstr; #if !FX1_0 [XmlRpcMissingMapping(MappingAction.Error)] public int? nxi; [XmlRpcMissingMapping(MappingAction.Error)] public bool? nxb; [XmlRpcMissingMapping(MappingAction.Error)] public double? nxd; [XmlRpcMissingMapping(MappingAction.Error)] public DateTime? nxdt; [XmlRpcMissingMapping(MappingAction.Error)] public ChildStruct? nxstr; #endif } [XmlRpcMissingMapping(MappingAction.Ignore)] struct Struct4 { [XmlRpcMissingMapping(MappingAction.Error)] public int mi; [XmlRpcMissingMapping(MappingAction.Error)] public string ms; [XmlRpcMissingMapping(MappingAction.Error)] public bool mb; [XmlRpcMissingMapping(MappingAction.Error)] public double md; [XmlRpcMissingMapping(MappingAction.Error)] public DateTime mdt; [XmlRpcMissingMapping(MappingAction.Error)] public byte[] mb64; [XmlRpcMissingMapping(MappingAction.Error)] public int[] ma; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcInt xi; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcBoolean xb; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcDouble xd; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcDateTime xdt; [XmlRpcMissingMapping(MappingAction.Error)] public XmlRpcStruct xstr; #if !FX1_0 [XmlRpcMissingMapping(MappingAction.Error)] public int? nxi; [XmlRpcMissingMapping(MappingAction.Error)] public bool? nxb; [XmlRpcMissingMapping(MappingAction.Error)] public double? nxd; [XmlRpcMissingMapping(MappingAction.Error)] public DateTime? nxdt; [XmlRpcMissingMapping(MappingAction.Error)] public ChildStruct? nxstr; #endif } [XmlRpcMissingMapping(MappingAction.Ignore)] struct Struct5 { public int mi; public string ms; public bool mb; public double md; public DateTime mdt; public byte[] mb64; public int[] ma; public XmlRpcInt xi; public XmlRpcBoolean xb; public XmlRpcDouble xd; public XmlRpcDateTime xdt; public XmlRpcStruct xstr; #if !FX1_0 public int? nxi; public bool? nxb; public double? nxd; public DateTime? nxdt; public ChildStruct? nxstr; #endif } struct Struct6 { [XmlRpcMissingMapping(MappingAction.Ignore)] public int mi; [XmlRpcMissingMapping(MappingAction.Ignore)] public string ms; [XmlRpcMissingMapping(MappingAction.Ignore)] public bool mb; [XmlRpcMissingMapping(MappingAction.Ignore)] public double md; [XmlRpcMissingMapping(MappingAction.Ignore)] public DateTime mdt; [XmlRpcMissingMapping(MappingAction.Ignore)] public byte[] mb64; [XmlRpcMissingMapping(MappingAction.Ignore)] public int[] ma; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcInt xi; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcBoolean xb; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcDouble xd; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcDateTime xdt; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcStruct xstr; #if !FX1_0 [XmlRpcMissingMapping(MappingAction.Ignore)] public int? nxi; [XmlRpcMissingMapping(MappingAction.Ignore)] public bool? nxb; [XmlRpcMissingMapping(MappingAction.Ignore)] public double? nxd; [XmlRpcMissingMapping(MappingAction.Ignore)] public DateTime? nxdt; [XmlRpcMissingMapping(MappingAction.Ignore)] public ChildStruct? nxstr; #endif } [XmlRpcMissingMapping(MappingAction.Error)] struct Struct7 { [XmlRpcMissingMapping(MappingAction.Ignore)] public int mi; [XmlRpcMissingMapping(MappingAction.Ignore)] public string ms; [XmlRpcMissingMapping(MappingAction.Ignore)] public bool mb; [XmlRpcMissingMapping(MappingAction.Ignore)] public double md; [XmlRpcMissingMapping(MappingAction.Ignore)] public DateTime mdt; [XmlRpcMissingMapping(MappingAction.Ignore)] public byte[] mb64; [XmlRpcMissingMapping(MappingAction.Ignore)] public int[] ma; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcInt xi; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcBoolean xb; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcDouble xd; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcDateTime xdt; [XmlRpcMissingMapping(MappingAction.Ignore)] public XmlRpcStruct xstr; #if !FX1_0 [XmlRpcMissingMapping(MappingAction.Ignore)] public int? nxi; [XmlRpcMissingMapping(MappingAction.Ignore)] public bool? nxb; [XmlRpcMissingMapping(MappingAction.Ignore)] public double? nxd; [XmlRpcMissingMapping(MappingAction.Ignore)] public DateTime? nxdt; [XmlRpcMissingMapping(MappingAction.Ignore)] public ChildStruct? nxstr; #endif } //-------------------------------------------------------------------------/ [Test] public void Struct0_AllExist() { Struct0 strout = new Struct0(); strout.xi = 1234; strout.xb = true; strout.xd = 1234.567; strout.xdt = new DateTime(2006, 8, 9, 10, 11, 13); #if !FX1_0 strout.nxi = 5678; strout.nxb = true; strout.nxd = 2345.678; strout.nxdt = new DateTime(2007, 9, 10, 11, 12, 14); strout.nxstr = new ChildStruct(567); #endif XmlDocument xdoc = Utils.Serialize("Struct0_AllExist", strout, Encoding.UTF8, MappingAction.Error); Type parsedType, parsedArrayType; object obj = Utils.Parse(xdoc, typeof(Struct0), MappingAction.Error, out parsedType, out parsedArrayType); Assert.IsInstanceOfType(typeof(Struct0), obj); Struct0 strin = (Struct0)obj; Assert.AreEqual(strout.xi, strin.xi); Assert.AreEqual(strout.xb, strin.xb); Assert.AreEqual(strout.xd, strin.xd); Assert.AreEqual(strout.xdt, strin.xdt); #if !FX1_0 Assert.AreEqual(strout.nxi, strin.nxi); Assert.AreEqual(strout.nxb, strin.nxb); Assert.AreEqual(strout.nxd, strin.nxd); Assert.AreEqual(strout.nxdt, strin.nxdt); Assert.AreEqual(((ChildStruct)strout.nxstr).x, ((ChildStruct)strin.nxstr).x); #endif } //-------------------------------------------------------------------------/ [Test] [ExpectedException(typeof(XmlRpcMappingSerializeException))] public void Struct1_AllMissing_ErrorDefault() { XmlDocument xdoc = Utils.Serialize("Struct1_AllMissing_ErrorDefault", new Struct1(), Encoding.UTF8, MappingAction.Error); } [Test] public void Struct1_AllMissing_IgnoreDefault() { XmlDocument xdoc = Utils.Serialize("Struct1_AllMissing_IgnoreDefault", new Struct1(), Encoding.UTF8, MappingAction.Ignore); } //-------------------------------------------------------------------------/ [Test] [ExpectedException(typeof(XmlRpcMappingSerializeException))] public void Struct2_AllMissing_ErrorError() { XmlDocument xdoc = Utils.Serialize( "Struct2_AllMissing_ErrorError", new Struct2(), Encoding.UTF8, MappingAction.Error); } [Test] [ExpectedException(typeof(XmlRpcMappingSerializeException))] public void Struct2_AllMissing_IgnoreError() { XmlDocument xdoc = Utils.Serialize( "Struct2_AllMissing_IgnoreError", new Struct2(), Encoding.UTF8, MappingAction.Ignore); } //-------------------------------------------------------------------------/ [Test] [ExpectedException(typeof(XmlRpcMappingSerializeException))] public void Struct3_AllMissing_ErrorDefaultError() { XmlDocument xdoc = Utils.Serialize( "Struct3_AllMissing_ErrorDefaultError", new Struct3(), Encoding.UTF8, MappingAction.Error); } [Test] [ExpectedException(typeof(XmlRpcMappingSerializeException))] public void Struct3_AllMissing_IgnoreDefaultError() { XmlDocument xdoc = Utils.Serialize( "Struct3_AllMissing_IgnoreDefaultError", new Struct3(), Encoding.UTF8, MappingAction.Ignore); } //-------------------------------------------------------------------------/ [Test] [ExpectedException(typeof(XmlRpcMappingSerializeException))] public void Struct4_AllMissing_ErrorIgnoreError() { XmlDocument xdoc = Utils.Serialize( "Struct4_AllMissing_ErrorIgnoreError", new Struct4(), Encoding.UTF8, MappingAction.Error); } [Test] [ExpectedException(typeof(XmlRpcMappingSerializeException))] public void Struct4_AllMissing_IgnoreIgnoreError() { XmlDocument xdoc = Utils.Serialize( "Struct4_AllMissing_IgnoreIgnoreError", new Struct4(), Encoding.UTF8, MappingAction.Ignore); } //-------------------------------------------------------------------------/ [Test] public void Struct5_AllMissing_ErrorIgnoreDefault() { XmlDocument xdoc = Utils.Serialize( "Struct5_AllMissing_ErrorIgnoreDefault", new Struct5(), Encoding.UTF8, MappingAction.Error); } [Test] public void Struct5_AllMissing_IgnoreIgnoreDefault() { XmlDocument xdoc = Utils.Serialize( "Struct5_AllMissing_IgnoreIgnoreDefault", new Struct5(), Encoding.UTF8, MappingAction.Ignore); } //-------------------------------------------------------------------------/ [Test] public void Struct6_AllMissing_ErrorDefaultIgnore() { XmlDocument xdoc = Utils.Serialize( "Struct6_AllMissing_ErrorDefaultIgnore", new Struct6(), Encoding.UTF8, MappingAction.Error); } [Test] public void Struct6_AllMissing_IgnoreDefaultIgnore() { XmlDocument xdoc = Utils.Serialize( "Struct6_AllMissing_IgnoreDefaultIgnore", new Struct6(), Encoding.UTF8, MappingAction.Ignore); } //-------------------------------------------------------------------------/ [Test] public void Struct7_AllMissing_ErrorErrorIgnore() { XmlDocument xdoc = Utils.Serialize( "Struct7_AllMissing_ErrorErrorIgnore", new Struct7(), Encoding.UTF8, MappingAction.Error); } [Test] public void Struct7_AllMissing_IgnoreErrorIgnore() { XmlDocument xdoc = Utils.Serialize( "Struct7_AllMissing_IgnoreErrorIgnore", new Struct7(), Encoding.UTF8, MappingAction.Ignore); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; namespace System.Data.SqlClient.ManualTesting.Tests { /// <summary> /// Generates random values for SQL Server testing, such as DateTime and Money. Instances of this class are not thread safe! /// </summary> public sealed class SqlRandomizer : Randomizer { /// <summary> /// default limit for allocation size /// </summary> public const int DefaultMaxDataSize = 0x10000; // 1Mb /// <summary> /// must be set exactly once during construction only since it is part of random state /// </summary> private int _maxDataSize; /// <summary> /// when creating random buffers, this value is used to decide how much of random buffer /// will be true random data. The true random data is filled in the beginning and rest of the /// buffer repeats the same information /// </summary> private const int RepeatThreshold = 32; public SqlRandomizer() : this(CreateSeed(), DefaultMaxDataSize) { } // do not add code here public SqlRandomizer(int seed) : this(seed, DefaultMaxDataSize) { } // do not add code here public SqlRandomizer(int seed, int maxDataSize) : base(seed) { _maxDataSize = maxDataSize; } public SqlRandomizer(State state) : base(state) { // Deserialize will read _maxDataSize too } protected override int BinaryStateSize { get { return base.BinaryStateSize + 4; // 4 bytes for _maxDataSize } } protected override void Serialize(byte[] binState, out int nextOffset) { base.Serialize(binState, out nextOffset); SerializeInt(_maxDataSize, binState, ref nextOffset); } protected internal override void Deserialize(byte[] binState, out int nextOffset) { base.Deserialize(binState, out nextOffset); _maxDataSize = DeserializeInt(binState, ref nextOffset); } /// <summary> /// generates random bitmap array (optimized) /// </summary> public BitArray NextBitmap(int bitCount) { if (bitCount <= 0) throw new ArgumentOutOfRangeException("bitCount"); // optimize for any number of bits byte[] randValues = new byte[(bitCount + 7) / 8]; base.NextBytes(randValues); BitArray bitMap = new BitArray(randValues); // the bitmap was created with length rounded up to 8, truncate to ensure correct size bitMap.Length = bitCount; return bitMap; } /// <summary> /// generates random bitmap array, using probability for null (nullOdds is from 0 to 100) /// </summary> public BitArray NextBitmap(int bitCount, int nullOdds) { if (bitCount <= 0) throw new ArgumentOutOfRangeException("bitCount"); if (nullOdds < 0 || nullOdds > 100) throw new ArgumentOutOfRangeException("nullOdds"); // optimize for any number of bits BitArray bitMap = new BitArray(bitCount, false); for (int i = 0; i < bitCount; i++) { bitMap[i] = Next(100) < nullOdds; } return bitMap; } /// <summary> /// generates random list of columns in random order, no repeated columns /// </summary> public int[] NextIndices(int count) { if (count <= 0) throw new ArgumentOutOfRangeException("count"); int[] indices = new int[count]; for (int c = 0; c < count; c++) { indices[c] = c; } // shuffle Shuffle(indices); return indices; } /// <summary> /// Shuffles the values in given array, numbers are taken from the whole array, even if valuesToSet is provided. /// </summary> /// <param name="valuesToSet">if provided, only the beginning of the array up to this index will be shuffled</param> public void Shuffle<T>(T[] values, int? valuesToSet = null) { if (values == null) throw new ArgumentNullException("values"); int count = values.Length; int selectValues = count; if (valuesToSet.HasValue) { selectValues = valuesToSet.Value; if (selectValues < 0 || selectValues > count) throw new ArgumentOutOfRangeException("valuesToShuffle"); } for (int i = 0; i < selectValues; i++) { int nextIndex = NextIntInclusive(i, maxValueInclusive: count - 1); // swap T temp = values[i]; values[i] = values[nextIndex]; values[nextIndex] = temp; } } private enum LowValueEnforcementLevel { Uniform = 32, Weak = 16, Medium = 10, Strong = 4, VeryStrong = 2 } /// <summary> /// generates size value with low probability of large size values within the given range /// </summary> /// <param name="lowValuesEnforcementLevel"> /// lowValuesEnforcementLevel is value between 0 and 31; /// 0 means uniform distribution in the min/max range; /// 31 means very low chances for high values /// </param> private int NextAllocationUnit(int minSize, int maxSize, LowValueEnforcementLevel lowValuesLevel) { if (minSize < 0 || maxSize < 0 || minSize > maxSize) throw new ArgumentOutOfRangeException("minSize or maxSize are out of range"); if (lowValuesLevel < LowValueEnforcementLevel.VeryStrong || lowValuesLevel > LowValueEnforcementLevel.Uniform) throw new ArgumentOutOfRangeException("lowValuesLevel"); if (minSize == maxSize) return minSize; // shortcut for fixed size long longRange = (long)maxSize - (long)minSize + 1; // create a sample in range [0, 1) (it is never 1) double sample = base.NextDouble(); // decrease chances of large size values based on the how many bits digits are set in the maxValue int bitsPerLevel = (int)lowValuesLevel; long maxBitsLeft = longRange >> bitsPerLevel; while (maxBitsLeft > 0) { sample *= base.NextDouble(); maxBitsLeft >>= bitsPerLevel; } int res = minSize + (int)(sample * longRange); Debug.Assert(res >= minSize && res <= maxSize); return res; } /// <summary> /// Generates a random number to be used as a size for memory allocations. /// This method will return with low numbers most of the time, but it has very low probability to generate large ones. /// The limit is currently set to MaxData (even if maxSize is larger) /// </summary> public int NextAllocationSizeBytes(int minSize = 0, int? maxSize = null) { if (minSize > _maxDataSize) throw new ArgumentOutOfRangeException("minSize cannot be greater than a maximum defined data size"); if (!maxSize.HasValue || maxSize.Value > _maxDataSize) maxSize = _maxDataSize; return NextAllocationUnit(minSize, maxSize.Value, LowValueEnforcementLevel.Strong); } /// <summary> /// used by random table generators to select random number of columns and rows. This method will return very low numbers with high probability, /// </summary> public void NextTableDimentions(int maxRows, int maxColumns, int maxTotalSize, out int randRows, out int randColumns) { // prefer really low values to ensure table size will not go up way too much too frequently const LowValueEnforcementLevel level = LowValueEnforcementLevel.Medium; if (NextBit()) { // select rows first, then columns randColumns = NextAllocationUnit(1, maxColumns, level); randRows = NextAllocationUnit(1, Math.Min(maxRows, maxTotalSize / randColumns), level); } else { randRows = NextAllocationUnit(1, maxRows, level); randColumns = NextAllocationUnit(1, Math.Min(maxColumns, maxTotalSize / randRows), level); } } #region byte and char array generators /// <summary> /// used internally to repeat randomly generated portions of the array /// </summary> private void Repeat<T>(T[] result, int trueRandomCount) { // repeat the first chunk into rest of the array int remainder = result.Length - trueRandomCount; int offset = trueRandomCount; // repeat whole chunks while (remainder >= trueRandomCount) { Array.Copy(result, 0, result, offset, trueRandomCount); remainder -= trueRandomCount; offset += trueRandomCount; } // complete the last (partial) chunk in the end, if any if (remainder > 0) Array.Copy(result, 0, result, offset, remainder); } /// <summary> /// fill byte array with pseudo random data. Only the beginning of the array is filled with true random numbers, rest of it /// is repeated data. /// </summary> public void FillByteArray(byte[] result) { if (result == null) throw new ArgumentNullException("result"); if (result.Length == 0) return; // generate the first chunk of the array with true random values int trueRandomCount = base.Next(1, Math.Min(result.Length, RepeatThreshold)); for (int i = 0; i < trueRandomCount; i++) result[i] = unchecked((byte)base.Next()); Repeat(result, trueRandomCount); } /// <summary> /// Fill the array with pseudo random ANSI characters (ascii code less than 128). This method can be used to generate /// char, varchar and text values. /// </summary> public void FillAnsiCharArray(char[] result) { if (result == null) throw new ArgumentNullException("result"); if (result.Length == 0) return; // generate the first chunk of the array with true random values int trueRandomCount = base.Next(1, Math.Min(result.Length, RepeatThreshold)); for (int i = 0; i < trueRandomCount; i++) result[i] = (char)NextIntInclusive(0, maxValueInclusive: 127); Repeat(result, trueRandomCount); } /// <summary> /// Fill the array with pseudo random unicode characters, not including the surrogate ranges. This method can be used to generate /// nchar, nvarchar and ntext values. /// </summary> public void FillUcs2CharArray(char[] result) { if (result == null) throw new ArgumentNullException("result"); if (result.Length == 0) return; // generate the first chunk of the array with true random values int trueRandomCount = base.Next(1, Math.Min(result.Length, RepeatThreshold)); for (int i = 0; i < trueRandomCount; i++) result[i] = (char)NextIntInclusive(0, maxValueInclusive: 0xD800 - 1); // do not include surrogates Repeat(result, trueRandomCount); } /// <summary> /// generates random byte array with high probability of small-size arrays /// </summary> public byte[] NextByteArray(int minSize = 0, int? maxSize = null) { int size = NextAllocationSizeBytes(minSize, maxSize); byte[] resArray = new byte[size]; FillByteArray(resArray); return resArray; } /// <summary> /// generates random Ucs2 array with high probability of small-size arrays. The result does not include surrogate pairs or characters. /// </summary> public char[] NextUcs2Array(int minSize = 0, int? maxByteSize = null) { // enforce max data in characters if (!maxByteSize.HasValue || maxByteSize.Value > _maxDataSize) maxByteSize = _maxDataSize; int charSize = NextAllocationSizeBytes(minSize, maxByteSize) / 2; char[] resArray = new char[charSize]; FillUcs2CharArray(resArray); return resArray; } /// <summary> /// generates random array with high probability of small-size arrays. The result includes only characters with code less than 128. /// </summary> public char[] NextAnsiArray(int minSize = 0, int? maxSize = null) { // enforce max allocation size for char array if (!maxSize.HasValue || maxSize.Value > _maxDataSize / 2) maxSize = _maxDataSize / 2; int size = NextAllocationSizeBytes(minSize, maxSize); char[] resArray = new char[size]; FillAnsiCharArray(resArray); return resArray; } /// <summary> /// generates random binary value for SQL Server, with high probability of small-size arrays. /// </summary> public byte[] NextBinary(int minSize = 0, int maxSize = 8000) { return NextByteArray(minSize, maxSize); } /// <summary> /// returns a random 8-byte array as a timestamp (rowversion) value /// </summary> public byte[] NextRowVersion() { return NextByteArray(8, 8); } /// <summary> /// returns a random GUID to be used as unique identifier in SQL. Note that this method is deterministic for fixed seed random instances /// (it does NOT use Guid.NewGuid). /// </summary> public Guid NextUniqueIdentifier() { return new Guid(NextByteArray(16, 16)); } #endregion #region Date and Time values /// <summary> /// generates random, but valid datetime-type value, for SQL Server, with 3msec resolution (0, 3, 7msec) /// </summary> public DateTime NextDateTime() { DateTime dt = NextDateTime(SqlDateTime.MinValue.Value, SqlDateTime.MaxValue.Value); // round to datetime type resolution (increments of .000, .003, or .007 seconds) long totalMilliseconds = dt.Ticks / TimeSpan.TicksPerMillisecond; int lastDigit = (int)(totalMilliseconds % 10); if (lastDigit < 3) lastDigit = 0; else if (lastDigit < 7) lastDigit = 3; else lastDigit = 7; totalMilliseconds = (totalMilliseconds / 10) * 10 + lastDigit; return new DateTime(totalMilliseconds * TimeSpan.TicksPerMillisecond); } /// <summary> /// generates random, but valid datetime2 value for SQL Server /// </summary> public DateTime NextDateTime2() { return NextDateTime(DateTime.MinValue, DateTime.MaxValue); } /// <summary> /// generates random, but valid datetimeoffset value for SQL Server /// </summary> public DateTimeOffset NextDateTimeOffset() { return new DateTimeOffset(NextDateTime2()); } /// <summary> /// generates random, but valid date value for SQL Server /// </summary> public DateTime NextDate() { return NextDateTime2().Date; } /// <summary> /// generates random DateTime value in the given range. /// </summary> public DateTime NextDateTime(DateTime minValue, DateTime maxValueInclusive) { double ticksRange = unchecked((double)maxValueInclusive.Ticks - minValue.Ticks + 1); long ticks = minValue.Ticks + (long)(ticksRange * base.NextDouble()); return new DateTime(ticks); } /// <summary> /// generates random smalldatetime value for SQL server, in the range of January 1, 1900 to June 6, 2079, to an accuracy of one minute /// </summary> public DateTime NextSmallDateTime() { DateTime dt = NextDateTime( minValue: new DateTime(1900, 1, 1, 0, 0, 0), maxValueInclusive: new DateTime(2079, 6, 6)); // truncate minutes dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0); return dt; } /// <summary> /// generates random TIME value for SQL Server (one day clock, 100 nano second precision) /// </summary> public TimeSpan NextTime() { return TimeSpan.FromTicks(Math.Abs(NextBigInt()) % TimeSpan.TicksPerDay); } #endregion #region Double values /// <summary> /// generates random Double value in the given range /// </summary> public double NextDouble(double minValue, double maxValueExclusive) { double res; if (minValue >= maxValueExclusive) throw new ArgumentException("minValue >= maxValueExclusive"); double rand01 = base.NextDouble(); if (((minValue >= 0) && (maxValueExclusive >= 0)) || ((minValue <= 0) && (maxValueExclusive <= 0))) { // safe to diff double diff = maxValueExclusive - minValue; res = minValue + diff * rand01; } else { // not safe to diff, (max-min) may cause overflow res = minValue - minValue * rand01 + maxValueExclusive * rand01; } Debug.Assert(res >= minValue && res < maxValueExclusive); return res; } /// <summary> /// generates random Double value in the given range and up to precision specified /// </summary> public double NextDouble(double minValue, double maxValueExclusive, int precision) { // ensure input values are rounded if (maxValueExclusive != Math.Round(maxValueExclusive, precision)) { throw new ArgumentException("maxValueExclusive must be rounded to the given precision"); } if (minValue != Math.Round(minValue, precision)) { throw new ArgumentException("minValue must be rounded to the given precision"); } // this call will also ensure that minValue < maxValueExclusive double res = NextDouble(minValue, maxValueExclusive); res = Math.Round(res, precision); if (res >= maxValueExclusive) { // this can happen after rounding up value which was too close to the max edge // just use minValue instead res = minValue; } Debug.Assert(res >= minValue && res < maxValueExclusive); return res; } /// <summary> /// generates random real value for SQL server. Note that real is a single precision floating number, mapped to 'float' in .Net. /// </summary> public float NextReal() { return (float)NextDouble(float.MinValue, float.MaxValue); } #endregion #region Integral values /// <summary> /// generates random number in the given range, both min and max values can be in the range of returned values. /// </summary> public int NextIntInclusive(int minValue = int.MinValue, int maxValueInclusive = int.MaxValue) { if (minValue == maxValueInclusive) return minValue; int res; if (maxValueInclusive == int.MaxValue) { if (minValue == int.MinValue) { byte[] temp = new byte[4]; base.NextBytes(temp); res = BitConverter.ToInt32(temp, 0); } else { res = base.Next(minValue - 1, maxValueInclusive) + 1; } } else // maxValue < int.MaxValue { res = base.Next(minValue, maxValueInclusive + 1); } Debug.Assert(res >= minValue && res <= maxValueInclusive); return res; } /// <summary> /// random bigint 64-bit value /// </summary> public long NextBigInt() { byte[] temp = new byte[8]; base.NextBytes(temp); return BitConverter.ToInt64(temp, 0); } /// <summary> /// random smallint (16-bit) value /// </summary> public short NextSmallInt() { return (short)NextIntInclusive(short.MinValue, maxValueInclusive: short.MaxValue); } /// <summary> /// generates a tinyint value (8 bit, unsigned) /// </summary> public byte NextTinyInt() { return (byte)NextIntInclusive(0, maxValueInclusive: byte.MaxValue); } /// <summary> /// random bit /// </summary> public bool NextBit() { return base.Next() % 2 == 0; } #endregion #region Monetary types /// <summary> /// generates random SMALLMONEY value /// </summary> public decimal NextSmallMoney() { return (decimal)NextDouble( minValue: -214748.3648, maxValueExclusive: 214748.3647, precision: 4); } /// <summary> /// generates random MONEY value /// </summary> /// <returns></returns> public decimal NextMoney() { return (decimal)NextDouble((double)SqlMoney.MinValue.Value, (double)SqlMoney.MaxValue.Value); } #endregion #region helper methods to create random SQL object names /// <summary> /// Generates a random name to be used for database object. The length will be no more then (16 + prefix.Length + escapeLeft.Length + escapeRight.Length) /// Note this method is not deterministic, it uses Guid.NewGuild to generate unique name to avoid name conflicts between test runs. /// </summary> private static string GenerateUniqueObjectName(string prefix, string escapeLeft, string escapeRight) { string uniqueName = string.Format("{0}{1}_{2}_{3}{4}", escapeLeft, prefix, DateTime.Now.Ticks.ToString("X", CultureInfo.InvariantCulture), // up to 8 characters Guid.NewGuid().ToString().Substring(0, 6), // take the first 6 characters only escapeRight); return uniqueName; } /// <summary> /// Generates a random name to be used for SQL Server database object. SQL Server supports long names (up to 128 characters), add extra info for troubleshooting. /// Note this method is not deterministic, it uses Guid.NewGuild to generate unique name to avoid name conflicts between test runs. /// </summary> public static string GenerateUniqueObjectNameForSqlServer(string prefix) { Process currentProcess = Process.GetCurrentProcess(); string extendedPrefix = string.Format( "{0}_{1}@{2}", prefix, currentProcess.ProcessName, currentProcess.MachineName, DateTime.Now.ToString("yyyy_MM_dd", CultureInfo.InvariantCulture)); string name = GenerateUniqueObjectName(extendedPrefix, "[", "]"); if (name.Length > 128) { throw new ArgumentOutOfRangeException("the name is too long - SQL Server names are limited to 128"); } return name; } /// <summary> /// Generates a random temp table name for SQL Server. /// Note this method is not deterministic, it uses Guid.NewGuild to generate unique name to avoid name conflicts between test runs. /// </summary> public static string GenerateUniqueTempTableNameForSqlServer() { return GenerateUniqueObjectNameForSqlServer("#T"); } #endregion } }
using System.Collections.Generic; using UnityEngine; using CreateThis.VR.UI.Interact; namespace MeshEngine.Controller { public static class RotateAroundPivotExtensions { //http://answers.unity3d.com/questions/47115/vector3-rotate-around.html //Returns the rotated Vector3 using a Quaterion public static Vector3 RotateAroundPivot(this Vector3 point, Vector3 pivot, Quaternion angle) { // NOTE: (point - pivot) Gets a vector that points from the pivot's position to the point's. return angle * (point - pivot) + pivot; } //Returns the rotated Vector3 using Euler public static Vector3 RotateAroundPivot(this Vector3 point, Vector3 pivot, Vector3 euler) { return RotateAroundPivot(point, pivot, Quaternion.Euler(euler)); } //Rotates the Transform's position using a Quaterion public static void RotateAroundPivot(this Transform me, Vector3 pivot, Quaternion angle) { me.position = me.position.RotateAroundPivot(pivot, angle); } //Rotates the Transform's position using Euler public static void RotateAroundPivot(this Transform me, Vector3 pivot, Vector3 euler) { me.position = me.position.RotateAroundPivot(pivot, Quaternion.Euler(euler)); } } public class VertexController : Grabbable { class DragData { public int controllerIndex; public Vector3 dragPoint; public Vector3 preDragPosition; public Quaternion startTransformRotation; public FakeTransform transform; } public class FakeTransform { public Vector3 position; public Quaternion rotation; } private List<DragData> drags = new List<DragData>(); public Vector3 lastPosition; // last local position of the vertex inside the mesh public UnityEngine.Material material; public UnityEngine.Material stickySelectedMaterial; public Mesh mesh; private bool stickySelected; private List<ModeType> draggableModes = new List<ModeType>(new ModeType[] { ModeType.Vertex, ModeType.SelectVertices, ModeType.PrimitiveBox, ModeType.PrimitiveCylinder, ModeType.BoxSelect }); private List<ModeType> selectionDraggableModes = new List<ModeType>(new ModeType[] { ModeType.Vertex, ModeType.SelectVertices, ModeType.PrimitiveBox, ModeType.PrimitiveCylinder, ModeType.BoxSelect }); private bool selectable = true; public override void OnGrabStart(Transform controller, int controllerIndex) { base.OnGrabStart(controller, controllerIndex); DragStart(controller, controllerIndex); } public override void OnGrabUpdate(Transform controller, int controllerIndex) { DragUpdate(controller, controllerIndex); } public override void OnGrabStop(Transform controller, int controllerIndex) { base.OnGrabStop(controller, controllerIndex); DragEnd(controller, controllerIndex); } public int DragsIndexOfControllerIndex(int controllerIndex) { //Debug.Log("DragsIndexOfControllerIndex["+ GetInstanceID()+"] drags.Count=" + drags.Count + ",controllerIndex=" + controllerIndex); for (int i = 0; i < drags.Count; i++) { DragData drag = drags[i]; if (drag.controllerIndex == controllerIndex) { return i; } } return -1; } public int FindOrCreateDragsIndexOfControllerIndex(int controllerIndex) { int index = DragsIndexOfControllerIndex(controllerIndex); if (index == -1) { DragData drag = new DragData(); drag.controllerIndex = controllerIndex; drags.Add(drag); //Debug.Log("FindOrCreateDragsIndexOfControllerIndex[" + GetInstanceID() + "] created new index controllerIndex=" + controllerIndex + ",drags.Count=" + drags.Count); return drags.Count - 1; } else { return index; } } private void RotateAroundTransform(DragData drag) { // In order to add two quaternion rotations correctly you multiply them. // To subtract you need to multiply by the inverse. Quaternion rotationDelta = ( Snap.LocalRotationOfWorldRotation(mesh.transform, drag.transform.rotation) * Quaternion.Inverse(Snap.LocalRotationOfWorldRotation(mesh.transform, drag.startTransformRotation)) ); Quaternion snappedRotationDelta = Snap.RotationDelta(rotationDelta); transform.position = Snap.RotateAroundPivot(mesh.transform, transform.position, drag.transform.position, snappedRotationDelta); } public void DragStart(Transform controller, int controllerIndex) { //Debug.Log("DragStart mode=" + Mode.mode + ",stickySelected=" + stickySelected); if (stickySelected && selectionDraggableModes.Contains(Mode.mode)) { mesh.selection.BroadcastDragStart(controller, controllerIndex, gameObject); } SelectionDragStart(controller, controllerIndex, gameObject); } public FakeTransform WhichTransform(Transform controller, GameObject instanceOfOrigin) { Transform whichTransform = instanceOfOrigin == gameObject ? controller : instanceOfOrigin.transform; FakeTransform fakeTransform = new FakeTransform(); fakeTransform.position = whichTransform.position; fakeTransform.rotation = controller.rotation; return fakeTransform; } public void SelectionDragStart(Transform controller, int controllerIndex, GameObject instanceOfOrigin, bool allowSnap = true, bool forceDrag = false) { FakeTransform transformToUse = WhichTransform(controller, instanceOfOrigin); int index = FindOrCreateDragsIndexOfControllerIndex(controllerIndex); //Debug.Log("SelectionDragStart[" + GetInstanceID() + "] controllerIndex=" + controllerIndex + ",index=" + index); if (index > 0) { drags.RemoveAt(index); return; // only one controller may drag at a time. } if (!forceDrag && !draggableModes.Contains(Mode.mode)) { drags.RemoveAt(index); return; // only allow dragging vertices in vertex mode } drags[index].preDragPosition = transform.position; drags[index].dragPoint = transformToUse.position; drags[index].transform = transformToUse; drags[index].startTransformRotation = controller.rotation; lastPosition = transform.localPosition; Vector3 preSnapPosition = transformToUse.position - drags[index].dragPoint + drags[index].preDragPosition; Vector3 position = Settings.SnapEnabled() && allowSnap ? Snap.WorldPosition(mesh.transform, preSnapPosition) : preSnapPosition; UpdateLocalPositionFromWorldPosition(position); } public void DragUpdate(Transform controller, int controllerIndex) { SelectionDragUpdate(controller, controllerIndex, gameObject); if (stickySelected && selectionDraggableModes.Contains(Mode.mode)) { mesh.selection.BroadcastDragUpdate(controller, controllerIndex, gameObject); } } public void SelectionDragUpdate(Transform controller, int controllerIndex, GameObject instanceOfOrigin, bool allowSnap = true) { FakeTransform transformToUse = WhichTransform(controller, instanceOfOrigin); int index = DragsIndexOfControllerIndex(controllerIndex); //Debug.Log("SelectionDragUpdate[" + GetInstanceID() + "] controllerIndex=" + controllerIndex + ",index=" + index); if (index == -1 || index > 0) return; // only one controller may drag at a time. drags[index].transform = transformToUse; Vector3 preSnapPosition = transformToUse.position - drags[index].dragPoint + drags[index].preDragPosition; Vector3 position = Settings.SnapEnabled() && allowSnap ? Snap.WorldPosition(mesh.transform, preSnapPosition) : preSnapPosition; UpdateLocalPositionFromWorldPosition(position); if (instanceOfOrigin != gameObject) { RotateAroundTransform(drags[index]); UpdateLocalPositionFromWorldPosition(transform.position); } else { // no rotation } } public void DragEnd(Transform controller, int controllerIndex) { SelectionDragEnd(controller, controllerIndex, gameObject); if (stickySelected && selectionDraggableModes.Contains(Mode.mode)) { mesh.selection.BroadcastDragEnd(controller, controllerIndex, gameObject); } } public void SelectionDragEnd(Transform controller, int controllerIndex, GameObject instanceOfOrigin, bool allowSnap = true) { FakeTransform transformToUse = WhichTransform(controller, instanceOfOrigin); int index = DragsIndexOfControllerIndex(controllerIndex); //Debug.Log("SelectionDragEnd[" + GetInstanceID() + "] controllerIndex=" + controllerIndex + ",index=" + index); if (index == -1 || index > 0) return; // only one controller may drag at a time. drags[index].transform = transformToUse; Vector3 preSnapPosition = transformToUse.position - drags[index].dragPoint + drags[index].preDragPosition; Vector3 position = Settings.SnapEnabled() && allowSnap ? Snap.WorldPosition(mesh.transform, preSnapPosition) : preSnapPosition; UpdateLocalPositionFromWorldPosition(position); if (instanceOfOrigin != gameObject) { RotateAroundTransform(drags[index]); UpdateLocalPositionFromWorldPosition(transform.position); } else { // no rotation } lastPosition = Vector3.zero; GetComponent<Selectable>().SetSelected(false); drags.RemoveAt(index); } void TriggerDownModeFace() { mesh.triangles.AddTriangleVertex(gameObject); } void TriggerDownModeDelete() { RemoveVertex(); } public void RemoveVertex() { //Debug.Log("VertexController#RemoveVertex"); mesh.vertices.RemoveByVertexInstance(gameObject); mesh.vertices.DeactivateAndMoveToPool(gameObject); } void TriggerDownModeSelectVertices() { Vertex vertex = mesh.vertices.VertexOfInstance(gameObject); if (mesh.selection.VertexSelected(vertex)) { mesh.selection.DeselectVertex(gameObject); return; } mesh.selection.SelectVertex(gameObject); } public void TriggerDown(Transform controller, int controllerIndex) { switch (Mode.mode) { case ModeType.Delete: TriggerDownModeDelete(); break; case ModeType.Face: TriggerDownModeFace(); break; case ModeType.SelectVertices: TriggerDownModeSelectVertices(); break; } } public void AddToMeshController() { mesh.vertices.AddVertexWithInstance(transform.localPosition, gameObject); } public UnityEngine.Material GetMaterial() { if (stickySelected) { return stickySelectedMaterial; } else { return material; } } public void SetStickySelected(bool value) { stickySelected = value; UnityEngine.Material[] materials = new UnityEngine.Material[1]; materials[0] = GetMaterial(); Selectable selectable = GetComponent<Selectable>(); selectable.unselectedMaterials = materials; selectable.UpdateSelectedMaterials(); selectable.SetSelected(selectable.selected); } public void CreateSphereCollider() { SphereCollider sphereCollider = GetComponent<SphereCollider>(); if (sphereCollider == null) { sphereCollider = gameObject.AddComponent<SphereCollider>(); sphereCollider.radius = 0.5f; sphereCollider.center = Vector3.zero; } } public void SetSelectable(bool value) { selectable = value; SphereCollider sphereCollider = GetComponent<SphereCollider>(); if (selectable) { if (sphereCollider == null) CreateSphereCollider(); } else { if (sphereCollider != null) Destroy(sphereCollider); } } public void Create(Vector3 position, Mesh mesh, bool addToMesh = true) { //Debug.Log("VertexController#Create[" + GetInstanceID() + "] position=" + position); transform.localPosition = GetLocalPositionFromWorldPosition(position); CreateFromLocalPosition(transform.localPosition, mesh, addToMesh); } public void CreateFromLocalPosition(Vector3 localPosition, Mesh mesh, bool addToMesh = true) { transform.localPosition = localPosition; lastPosition = transform.localPosition; //Debug.Log("VertexController#CreateFromLocalPosition[" + GetInstanceID() + "] localPosition=" + transform.localPosition); this.mesh = mesh; if (addToMesh) AddToMeshController(); } public Vector3 GetLocalPositionFromWorldPosition(Vector3 newWorldPosition) { //Debug.Log("UpdateLocalPositionFromWorldPosition newWorldPosition=" + newWorldPosition); return transform.parent.transform.InverseTransformPoint(newWorldPosition); } public void UpdateLocalPositionFromWorldPosition(Vector3 newWorldPosition) { transform.localPosition = GetLocalPositionFromWorldPosition(newWorldPosition); //Debug.Log("UpdateLocalPositionFromWorldPosition transform.localPosition=" + transform.localPosition); UpdatePosition(transform.localPosition); } public void UpdatePosition(Vector3 newPosition) { //Debug.Log("VertexController#UpdatePosition[" + GetInstanceID() + "] lastPosition=" + lastPosition + ",newPosition=" + newPosition); mesh.vertices.ReplaceVertex(gameObject, newPosition); lastPosition = newPosition; } private void Start() { //Debug.Log("VertexController Start[" + GetInstanceID() + "]"); //stickySelected = false; } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation.Internal.Metadata { using System; using System.Collections.Generic; using System.Text; using System.Activities.Presentation.Metadata; using System.Reflection; using System.Diagnostics; using System.Collections; using System.Globalization; using System.Diagnostics.CodeAnalysis; using System.Runtime; // <summary> // Helper class that knows how to look up the base implementation of a given MemberInfo, // as well as custom attributes from the MetadataStore or the CLR. However, it does not // actually cache those attributes. We can add this functionality in the future if needed. // On the other hand, this class does cache the map between attribute types and our internal // AttributeData data structures that contain AttributeUsageAttributes so we don't have to keep // looking them up via reflection. // </summary> internal static class AttributeDataCache { // BindingFlags used for all GetInfo() types of calls private static readonly BindingFlags _getInfoBindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; // Note: we use Hashtables instead of Dictionaries because they are thread safe for // read operations without the need for explicit locking. // Hashtable of MemberInfos to their base MemberInfos, or null if there is no base MemberInfo private static Hashtable _baseMemberMap = new Hashtable(); // Hashtable of attribute Types to their corresponding AttributeData classes private static Hashtable _attributeDataCache = new Hashtable(); // Indicator for no MemberInfo in _baseMemberMap: Null value means the base MemberInfo wasn't // looked up yet, _noMemberInfo value means it was looked up but it doesn't exist. private static object _noMemberInfo = new object(); // Used for thread safety private static object _syncObject = new object(); // This table gets populated once at initialization, so there is no need for a Hashtable here private static Dictionary<MemberTypes, GetBaseMemberCallback> _baseMemberFinders; // Static Ctor to populate the lookup table for helper methods that know how // to look up the base MemberInfo of a particular MemberType (ctor, method, event, ...) [SuppressMessage(FxCop.Category.Performance, FxCop.Rule.InitializeReferenceTypeStaticFieldsInline)] static AttributeDataCache() { _baseMemberFinders = new Dictionary<MemberTypes, GetBaseMemberCallback>(); _baseMemberFinders[MemberTypes.Constructor] = new GetBaseMemberCallback(GetBaseConstructorInfo); _baseMemberFinders[MemberTypes.Method] = new GetBaseMemberCallback(GetBaseMethodInfo); _baseMemberFinders[MemberTypes.Property] = new GetBaseMemberCallback(GetBasePropertyInfo); _baseMemberFinders[MemberTypes.Event] = new GetBaseMemberCallback(GetBaseEventInfo); } // <summary> // Gets the base MemberInfo for the specified MemberInfo. For types, // the method returns the base type, if any. For methods, events, and properties // the method returns the base method, event, or property, if they exists, null // otherwise. // </summary> // <param name="member">MemberInfo to look up in the base class</param> // <returns>Specified MemberInfo in the base class if it exists, null otherwise.</returns> internal static MemberInfo GetBaseMemberInfo(MemberInfo member) { object baseMember = _baseMemberMap[member]; if (baseMember == _noMemberInfo) { return null; } if (baseMember == null) { baseMember = CalculateBaseMemberInfo(member); // With Hashtable we only need to lock on writes lock (_syncObject) { _baseMemberMap[member] = baseMember ?? _noMemberInfo; } } return (MemberInfo)baseMember; } // <summary> // Looks up the specified MemberInfo in the custom MetadataStore AttributeTables // and returns any attributes associated with it as an enumeration. This method // does not return any inherited attributes. // </summary> // <param name="type">Type to look up</param> // <param name="memberName">Member name to look up. If null, attributes associated // with the type itself will be returned.</param> // <param name="tables">AttributeTables to look in</param> // <returns>Attributes in the AttributeTables associated with the specified // Type and member name.</returns> internal static IEnumerable<object> GetMetadataStoreAttributes(Type type, string memberName, AttributeTable[] tables) { if (tables == null || tables.Length == 0) { yield break; } foreach (AttributeTable table in tables) { if (table.ContainsAttributes(type)) { IEnumerable attrEnum; if (memberName == null) { attrEnum = table.GetCustomAttributes(type); } else { attrEnum = table.GetCustomAttributes(type, memberName); } foreach (object attr in attrEnum) { yield return attr; } } } } // <summary> // Looks up custom attributes for the specified MemberInfo in CLR via reflection // and returns them as an enumeration. This method does not return any // inherited attributes. // </summary> // <param name="member">MemberInfo to look up</param> // <returns>Custom Attributes associated with the specified // MemberInfo in the CLR.</returns> internal static IEnumerable<object> GetClrAttributes(MemberInfo member) { object[] attrs = member.GetCustomAttributes(false); Fx.Assert(attrs != null, "It looks like GetCustomAttributes() CAN return null. Protect for it."); return attrs; } // <summary> // Gets an existing instance of AttributeData associated with the // specified attribute Type, or creates a new one and caches it for // later. AttributeData is used as a cache for AttributeUsageAttributes // so don't have to keep using reflection to get them. // </summary> // <param name="attributeType">Attribute type to look up</param> // <returns>Instance of AttributeData associated with the specified // attribute type.</returns> internal static AttributeData GetAttributeData(Type attributeType) { AttributeData attrData = _attributeDataCache[attributeType] as AttributeData; if (attrData == null) { attrData = new AttributeData(attributeType); // With Hashtable we only need to lock on writes lock (_syncObject) { _attributeDataCache[attributeType] = attrData; } } return attrData; } // // Tries to get the base MemberInfo associated with the specified // member info, if any. // private static MemberInfo CalculateBaseMemberInfo(MemberInfo member) { Fx.Assert(member != null, "member parameter should not be null"); // Type is a special case that covers the majority of cases Type type = member as Type; if (type != null) { return type.BaseType; } Type targetType = member.DeclaringType.BaseType; Fx.Assert( _baseMemberFinders.ContainsKey(member.MemberType), string.Format( CultureInfo.CurrentCulture, "Didn't know how to look up the base MemberInfo for member type {0}. " + "Please update the list of known GetBaseInfoCallbacks in AttributeDataCache.", member.MemberType)); MemberInfo baseMemberInfo = null; while (targetType != null && baseMemberInfo == null) { baseMemberInfo = _baseMemberFinders[member.MemberType](member, targetType); targetType = targetType.BaseType; } return baseMemberInfo; } // // Helper method that knows how to look up the base constructor of a class. However, // since constructors can't derive from one another, this method always returns // null. // private static MemberInfo GetBaseConstructorInfo(MemberInfo info, Type targetType) { return null; } // // Helper method that knows how to look up the base implementation of a virtual method. // private static MemberInfo GetBaseMethodInfo(MemberInfo info, Type targetType) { MethodInfo methodInfo = info as MethodInfo; Fx.Assert(methodInfo != null, "It looks like MemberType did not match the type of MemberInfo: " + info.GetType().Name); return targetType.GetMethod(methodInfo.Name, _getInfoBindingFlags, null, ToTypeArray(methodInfo.GetParameters()), null); } // // Helper method that knows how to look up the base implementation of a virtual property. // private static MemberInfo GetBasePropertyInfo(MemberInfo info, Type targetType) { PropertyInfo propInfo = info as PropertyInfo; Fx.Assert(propInfo != null, "It looks like MemberType did not match the type of MemberInfo: " + info.GetType().Name); return targetType.GetProperty(propInfo.Name, _getInfoBindingFlags, null, propInfo.PropertyType, ToTypeArray(propInfo.GetIndexParameters()), null); } // // Helper method that knows how to look up the base implementation of a virtual event. // private static MemberInfo GetBaseEventInfo(MemberInfo info, Type targetType) { EventInfo eventInfo = info as EventInfo; Fx.Assert(eventInfo != null, "It looks like MemberType did not match the type of MemberInfo: " + info.GetType().Name); return targetType.GetEvent(eventInfo.Name, _getInfoBindingFlags); } // // Helper that converts ParamenterInfo[] into Type[] // private static Type[] ToTypeArray(ParameterInfo[] parameterInfo) { if (parameterInfo == null) { return null; } Type[] parameterTypes = new Type[parameterInfo.Length]; for (int i = 0; i < parameterInfo.Length; i++) { parameterTypes[i] = parameterInfo[i].ParameterType; } return parameterTypes; } // Delegate used to call specific methods to get a base MemberInfo from the given MemberInfo private delegate MemberInfo GetBaseMemberCallback(MemberInfo member, Type targetType); } }
/* Copyright (c) 2004-2010 Tomas Matousek, Jakub Misek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ /* * TODO: * * JSON_NUMERIC_CHECK (integer) * Encodes numeric strings as numbers. Available since PHP 5.3.3. * * JSON_BIGINT_AS_STRING (integer) * Available since PHP 5.4.0. * * JSON_PRETTY_PRINT (integer) * Use whitespace in returned data to format it. Available since PHP 5.4.0. * * JSON_UNESCAPED_SLASHES (integer) * Don't escape /. Available since PHP 5.4.0. * */ using System; using System.IO; using System.Text; using System.Collections.Generic; using System.Globalization; using System.Security; using System.Security.Permissions; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using PHP.Core; using PHP.Core.Reflection; using PHP.Library; #if SILVERLIGHT using PHP.CoreCLR; #else using System.Web; using System.Runtime.Serialization.Formatters.Binary; using System.Diagnostics; #endif namespace PHP.Library { #region JSON PHP API /// <summary> /// Classes implementing Countable can be used with the count() function. /// </summary> [ImplementsType] public interface JsonSerializable { /// <summary> /// Specify data which should be serialized to JSON. /// </summary> /// <param name="context">Current <see cref="ScriptContext"/> provided by Phalanger.</param> /// <returns>Return data which should be serialized by <c>json_encode()</c>, see <see cref="PhpJson.Serialize"/>.</returns> [ImplementsMethod] [AllowReturnValueOverride] object jsonSerialize(ScriptContext context); } /// <summary> /// JSON encoding/decoding functions. /// </summary> /// <threadsafety static="true"/> [ImplementsExtension(LibraryDescriptor.ExtJson)] public static class PhpJson { #region Constants /// <summary> /// Values returned by json_last_error function. /// </summary> public enum JsonLastError : int { /// <summary> /// No error has occurred /// </summary> [ImplementsConstant("JSON_ERROR_NONE")] JSON_ERROR_NONE = 0, /// <summary> /// The maximum stack depth has been exceeded /// </summary> [ImplementsConstant("JSON_ERROR_DEPTH")] JSON_ERROR_DEPTH = 1, /// <summary> /// Occurs with underflow or with the modes mismatch. /// </summary> [ImplementsConstant("PHP_JSON_ERROR_STATE_MISMATCH")] PHP_JSON_ERROR_STATE_MISMATCH = 2, /// <summary> /// Control character error, possibly incorrectly encoded /// </summary> [ImplementsConstant("JSON_ERROR_CTRL_CHAR")] JSON_ERROR_CTRL_CHAR = 3, /// <summary> /// Syntax error /// </summary> [ImplementsConstant("JSON_ERROR_SYNTAX")] JSON_ERROR_SYNTAX = 4, /// <summary> /// /// </summary> [ImplementsConstant("JSON_ERROR_UTF8")] JSON_ERROR_UTF8 = 5, } /// <summary> /// Options given to json_encode function. /// </summary> public enum JsonEncodeOptions { /// <summary> /// No options specified. /// </summary> Default = 0, /// <summary> /// All &lt; and &gt; are converted to \u003C and \u003E. /// </summary> [ImplementsConstant("JSON_HEX_TAG")] JSON_HEX_TAG = 1, /// <summary> /// All &amp;s are converted to \u0026. /// </summary> [ImplementsConstant("JSON_HEX_AMP")] JSON_HEX_AMP = 2, /// <summary> /// All ' are converted to \u0027. /// </summary> [ImplementsConstant("JSON_HEX_APOS")] JSON_HEX_APOS = 4, /// <summary> /// All " are converted to \u0022. /// </summary> [ImplementsConstant("JSON_HEX_QUOT")] JSON_HEX_QUOT = 8, /// <summary> /// Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. /// </summary> [ImplementsConstant("JSON_FORCE_OBJECT")] JSON_FORCE_OBJECT = 16, /// <summary> /// Encodes numeric strings as numbers. /// </summary> [ImplementsConstant("JSON_NUMERIC_CHECK")] JSON_NUMERIC_CHECK = 32, } /// <summary> /// Options given to json_decode function. /// </summary> public enum JsonDecodeOptions { Default = 0, /// <summary> /// Big integers represent as strings rather than floats. /// </summary> [ImplementsConstant("JSON_BIGINT_AS_STRING")] JSON_BIGINT_AS_STRING = 1, } #endregion #region json_encode, json_decode, json_last_error (CLR only) #if !SILVERLIGHT [ImplementsFunction("json_encode")] public static PhpBytes Serialize(object value) { return PhpJsonSerializer.Default.Serialize(value, UnknownTypeDesc.Singleton); } [ImplementsFunction("json_encode")] public static PhpBytes Serialize(object value, JsonEncodeOptions options) { return new PhpJsonSerializer( new JsonFormatter.EncodeOptions() { ForceObject = (options & JsonEncodeOptions.JSON_FORCE_OBJECT) != 0, HexAmp = (options & JsonEncodeOptions.JSON_HEX_AMP) != 0, HexApos = (options & JsonEncodeOptions.JSON_HEX_APOS) != 0, HexQuot = (options & JsonEncodeOptions.JSON_HEX_QUOT) != 0, HexTag = (options & JsonEncodeOptions.JSON_HEX_TAG) != 0, NumericCheck = (options & JsonEncodeOptions.JSON_NUMERIC_CHECK) != 0, }, new JsonFormatter.DecodeOptions() ).Serialize(value, UnknownTypeDesc.Singleton); } [ImplementsFunction("json_decode")] public static PhpReference Unserialize(PhpBytes json) { if (json == null) return null; return PhpJsonSerializer.Default.Deserialize(json, UnknownTypeDesc.Singleton); } [ImplementsFunction("json_decode")] public static PhpReference Unserialize(PhpBytes json, bool assoc /* = false*/) { return Unserialize(json, assoc, 512, JsonDecodeOptions.Default); } [ImplementsFunction("json_decode")] public static PhpReference Unserialize(PhpBytes json, bool assoc /* = false*/ , int depth /* = 512*/) { return Unserialize(json, assoc, depth, JsonDecodeOptions.Default); } /// <summary> /// /// </summary> /// <param name="json"></param> /// <param name="assoc">When TRUE, returned object's will be converted into associative array s. </param> /// <param name="depth">User specified recursion depth. </param> /// <param name="options"></param> /// <returns></returns> [ImplementsFunction("json_decode")] public static PhpReference Unserialize(PhpBytes json, bool assoc /* = false*/ , int depth /* = 512*/ , JsonDecodeOptions options /* = 0 */) { if (json == null) return null; return new PhpJsonSerializer( new JsonFormatter.EncodeOptions(), new JsonFormatter.DecodeOptions() { Assoc = assoc, Depth = depth, BigIntAsString = (options & JsonDecodeOptions.JSON_BIGINT_AS_STRING) != 0 } ).Deserialize(json, UnknownTypeDesc.Singleton); } [ImplementsFunction("json_last_error")] public static int GetLastError() { JsonLastError err; var ctx = ScriptContext.CurrentContext; if (ctx.Properties.TryGetProperty<JsonLastError>(out err) == false) err = JsonLastError.JSON_ERROR_NONE; return (int)err; } #endif #endregion } #endregion #region JsonFormatter /// <summary> /// Implements a JSON formatter (serializer). /// </summary> public sealed class JsonFormatter : IFormatter { #region Tokens /// <summary> /// Contains definition of (one-character) tokens that constitute PHP serialized data. /// </summary> internal class Tokens { internal const char ObjectOpen = '{'; internal const char ObjectClose = '}'; internal const char ItemsSeparator = ','; internal const char PropertyKeyValueSeparator = ':'; internal const char Quote = '"'; internal const char Escape = '\\'; internal const string EscapedNewLine = @"\n"; internal const string EscapedCR = @"\r"; internal const string EscapedTab = @"\t"; internal const string EscapedBackspace = @"\b"; internal const string EscapedQuote = "\\\""; internal const string EscapedReverseSolidus = @"\\"; internal const string EscapedSolidus = @"\/"; internal const string EscapedFormFeed = @"\f"; internal const string EscapedUnicodeChar = @"\u"; // 4-digit number follows internal const char ArrayOpen = '['; internal const char ArrayClose = ']'; internal const string NullLiteral = "null"; internal const string TrueLiteral = "true"; internal const string FalseLiteral = "false"; } #endregion /// <summary> /// Implements the serialization functionality. Serializes an object, or graph of objects /// with the given root to the provided <see cref="StreamWriter"/>. /// </summary> internal class ObjectWriter { #region Fields and Properties private readonly ScriptContext/*!*/ context; /// <summary> /// The stream writer to write serialized data to. /// </summary> private readonly StreamWriter/*!*/ writer; /// <summary> /// Options. /// </summary> private readonly EncodeOptions/*!*/ encodeOptions; /// <summary> /// The encoding to be used when writing and reading the serialization stream. /// </summary> private Encoding encoding; /// <summary> /// Stack of objects being currently serialized. Used to avoid stack overflow and to properly outputs "recursion_detected" warning. /// </summary> private List<object> recursionStack = null; #endregion #region Construction /// <summary> /// Creates a new <see cref="ObjectWriter"/> with a given <see cref="StreamWriter"/>. /// </summary> /// <param name="context">The current <see cref="ScriptContext"/>.</param> /// <param name="writer">The writer to write serialized data to.</param> /// <param name="encodeOptions">Encoding options.</param> /// <param name="encoding">Encoding used for reading PhpBytes.</param> internal ObjectWriter(ScriptContext/*!*/ context, StreamWriter/*!*/ writer, EncodeOptions/*!*/encodeOptions, Encoding encoding) { Debug.Assert(context != null && writer != null && encodeOptions != null); this.context = context; this.writer = writer; this.encodeOptions = encodeOptions; this.encoding = encoding; } #endregion #region Recursion /// <summary> /// Push currently serialized array or object to the stack to prevent recursion. /// </summary> /// <param name="obj"></param> /// <returns></returns> private bool PushObject(object/*!*/obj) { Debug.Assert(obj != null); if (recursionStack == null) recursionStack = new List<object>(8); else { // check recursion int hits = 0; for (int i = 0; i < recursionStack.Count; i++) if (recursionStack[i] == obj) hits++; if (hits >= 2) { PhpException.Throw(PhpError.Warning, LibResources.GetString("recursion_detected")); return false; } } recursionStack.Add(obj); return true; } /// <summary> /// Pop the serialized object from the stack. /// </summary> private void PopObject() { Debug.Assert(recursionStack != null); recursionStack.RemoveAt(recursionStack.Count - 1); } #endregion #region Serialize, Write* /// <summary> /// Serializes an object or graph of objects to <see cref="writer"/>. /// </summary> /// <param name="graph">The object (graph) to serialize.</param> internal void Serialize(object graph) { if (graph == null) { WriteNull(); return; } switch (Type.GetTypeCode(graph.GetType())) { case TypeCode.Boolean: WriteBoolean((bool)graph); break; case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Decimal: writer.Write(graph.ToString()); break; case TypeCode.Single: writer.Write(graph.ToString()); break; case TypeCode.Double: writer.Write((double)graph); break; case TypeCode.Char: WriteString(graph.ToString()); break; case TypeCode.String: WriteString((string)graph); break; case TypeCode.Object: { PhpArray array; if ((array = graph as PhpArray) != null) { if (PushObject(graph)) { WriteArray(array); PopObject(); } else WriteNull(); break; } DObject obj; JsonSerializable jsonserializeble; if ((jsonserializeble = graph as JsonSerializable) != null) { var retval = jsonserializeble.jsonSerialize(context); if ((obj = (retval as DObject)) != null) // Handle the case where jsonSerialize() returns itself. WriteDObject(obj); else Serialize(retval); break; } if ((obj = graph as DObject) != null) { if (PushObject(graph)) { WriteDObject(obj); PopObject(); } else WriteNull(); break; } PhpReference reference; if ((reference = graph as PhpReference) != null) { Serialize(reference.Value); break; } PhpBytes bytes; if ((bytes = graph as PhpBytes) != null) { WriteString(((IPhpConvertible)bytes).ToString()); break; } PhpString str; if ((str = graph as PhpString) != null) { WriteString(str.ToString()); break; } if (graph is PhpResource) { WriteUnsupported(PhpResource.PhpTypeName); break; } goto default; } default: WriteUnsupported(graph.GetType().FullName); break; } } /// <summary> /// Serializes null and throws an exception. /// </summary> /// <param name="TypeName"></param> private void WriteUnsupported(string TypeName) { PhpException.Throw(PhpError.Warning, LibResources.GetString("serialization_unsupported_type", TypeName)); WriteNull(); } /// <summary> /// Serializes <B>Null</B>. /// </summary> private void WriteNull() { writer.Write(Tokens.NullLiteral); } /// <summary> /// Serializes a bool value. /// </summary> /// <param name="value">The value.</param> private void WriteBoolean(bool value) { writer.Write(value ? Tokens.TrueLiteral : Tokens.FalseLiteral); } #region encoding strings /// <summary> /// Determines if given character is printable character. Otherwise it must be encoded. /// </summary> /// <param name="c"></param> /// <returns></returns> private static bool CharIsPrintable(char c) { return (c <= 0x7f) && // ASCII (!char.IsControl(c)) && // not control (!(c >= 9 && c <= 13)); // not BS, HT, LF, Vertical Tab, Form Feed, CR } /// <summary> /// Determines if given character should be encoded. /// </summary> /// <param name="c"></param> /// <returns></returns> private bool CharShouldBeEncoded(char c) { switch (c) { case '\n': case '\r': case '\t': case '/': case Tokens.Escape: case '\b': case '\f': case Tokens.Quote: return true; case '\'': return encodeOptions.HexApos; case '<': return encodeOptions.HexTag; case '>': return encodeOptions.HexTag; case '&': return encodeOptions.HexAmp; default: return !CharIsPrintable(c); } } /// <summary> /// Convert 16b character into json encoded character. /// </summary> /// <param name="value">The full string to be encoded.</param> /// <param name="i">The index of character to be encoded. Can be increased if more characters are processed.</param> /// <returns>The encoded part of string, from value[i] to value[i after method call]</returns> private string EncodeStringIncremental(string value, ref int i) { char c = value[i]; switch (c) { case '\n': return (Tokens.EscapedNewLine); case '\r': return (Tokens.EscapedCR); case '\t': return (Tokens.EscapedTab); case '/': return (Tokens.EscapedSolidus); case Tokens.Escape: return (Tokens.EscapedReverseSolidus); case '\b': return (Tokens.EscapedBackspace); case '\f': return (Tokens.EscapedFormFeed); case Tokens.Quote: return (encodeOptions.HexQuot ? (Tokens.EscapedUnicodeChar + "0022") : Tokens.EscapedQuote); case '\'': return (encodeOptions.HexApos ? (Tokens.EscapedUnicodeChar + "0027") : "'"); case '<': return (encodeOptions.HexTag ? (Tokens.EscapedUnicodeChar + "003C") : "<"); case '>': return (encodeOptions.HexTag ? (Tokens.EscapedUnicodeChar + "003E") : ">"); case '&': return (encodeOptions.HexAmp ? (Tokens.EscapedUnicodeChar + "0026") : "&"); default: { if (CharIsPrintable(c)) { int start = i++; for (; i < value.Length && !CharShouldBeEncoded(value[i]); ++i) ; return value.Substring(start, (i--) - start); // accumulate characters, mostly it is entire string value (faster) } else { return (Tokens.EscapedUnicodeChar + ((int)c).ToString("X4")); } } } } #endregion /// <summary> /// Serializes JSON string. /// </summary> /// <param name="value">The string.</param> private void WriteString(string value) { if (encodeOptions.NumericCheck) { int i; long l; double d; var result = PHP.Core.Convert.StringToNumber(value, out i, out l, out d); if ((result & Core.Convert.NumberInfo.IsNumber) != 0) { if ((result & Core.Convert.NumberInfo.Integer) != 0) writer.Write(i.ToString()); if ((result & Core.Convert.NumberInfo.LongInteger) != 0) writer.Write(l.ToString()); if ((result & Core.Convert.NumberInfo.Double) != 0) writer.Write(d.ToString()); return; } } StringBuilder strVal = new StringBuilder(value.Length + 2); strVal.Append(Tokens.Quote); for (int i = 0; i < value.Length; ++i) { strVal.Append(EncodeStringIncremental(value, ref i)); } strVal.Append(Tokens.Quote); writer.Write(strVal.ToString()); } #region formatting JSON objects / arrays private void WriteJsonObject(IEnumerable<KeyValuePair<string, object>> items) { writer.Write(Tokens.ObjectOpen); bool bFirst = true; foreach (var x in items) { if (bFirst) bFirst = false; else writer.Write(Tokens.ItemsSeparator); WriteString(x.Key); writer.Write(Tokens.PropertyKeyValueSeparator); Serialize(x.Value); } writer.Write(Tokens.ObjectClose); } private void WriteJsonArray(IEnumerable<object> items) { writer.Write(Tokens.ArrayOpen); bool bFirst = true; foreach (var x in items) { if (bFirst) bFirst = false; else writer.Write(Tokens.ItemsSeparator); Serialize(x); } writer.Write(Tokens.ArrayClose); } private IEnumerable<KeyValuePair<string, object>> JsonObjectProperties(PhpArray/*!*/value) { foreach (var x in value) yield return new KeyValuePair<string, object>(x.Key.ToString(), x.Value); } private IEnumerable<KeyValuePair<string, object>> JsonObjectProperties(DObject/*!*/value, bool avoidPicName) { foreach (KeyValuePair<string, object> pair in Serialization.EnumerateSerializableProperties(value)) { if (avoidPicName && pair.Key == __PHP_Incomplete_Class.ClassNameFieldName) { // skip the __PHP_Incomplete_Class_Name field continue; } yield return pair; } } #endregion /// <summary> /// Serializes a <see cref="PhpArray"/>. /// </summary> /// <param name="value">The array.</param> private void WriteArray(PhpArray value) { if (encodeOptions.ForceObject || (value.StringCount > 0 || value.MaxIntegerKey + 1 != value.IntegerCount)) WriteJsonObject(JsonObjectProperties(value)); else WriteJsonArray(value.Values); } /// <summary> /// Serializes a <see cref="DObject"/>. /// </summary> /// <param name="value">The object.</param> private void WriteDObject(DObject value) { __PHP_Incomplete_Class pic; // write out properties WriteJsonObject(JsonObjectProperties(value, (pic = value as __PHP_Incomplete_Class) != null && pic.__PHP_Incomplete_Class_Name.IsSet)); } #endregion } /// <summary> /// Implements the deserialization functionality. Deserializes the data on the provided /// <see cref="StreamReader"/> and reconstitutes the graph of objects. /// </summary> internal class ObjectReader { #region Fields and Properties private readonly ScriptContext/*!*/ context; /// <summary> /// The stream reader to read serialized data from. /// </summary> private readonly StreamReader/*!*/ reader; /// <summary> /// Decoding options. /// </summary> private readonly DecodeOptions/*!*/decodeOptions; #endregion #region Construction /// <summary> /// Creates a new <see cref="ObjectReader"/> with a given <see cref="StreamReader"/>. /// </summary> /// <param name="context">The current <see cref="ScriptContext"/>.</param> /// <param name="reader">The reader to reader serialized data from.</param> /// <param name="decodeOptions"></param> internal ObjectReader(ScriptContext/*!*/ context, StreamReader/*!*/ reader, DecodeOptions/*!*/decodeOptions) { Debug.Assert(context != null && reader != null && decodeOptions != null); this.context = context; this.reader = reader; this.decodeOptions = decodeOptions; } #endregion /// <summary> /// De-serializes the data is <see cref="reader"/> and reconstitutes the graph of objects. /// </summary> /// <returns>The top object of the deserialized graph. Null in case of error.</returns> internal object Deserialize() { context.Properties.RemoveProperty<PhpJson.JsonLastError>(); var scanner = new JsonScanner(reader, decodeOptions); var parser = new Json.Parser(context, decodeOptions) { Scanner = scanner }; try { if (!parser.Parse()) throw new Exception("Syntax error"); } catch (Exception) { context.Properties.SetProperty<PhpJson.JsonLastError>(PhpJson.JsonLastError.JSON_ERROR_SYNTAX); return null; } // return parser.Result; } } #region Fields and properties /// <summary> /// Serialization security permission demanded in <see cref="Serialize"/>. /// </summary> private static SecurityPermission serializationPermission = new SecurityPermission(SecurityPermissionFlag.SerializationFormatter); /// <summary> /// The encoding to be used when writing and reading the serialization stream. /// </summary> private Encoding encoding; /// <summary> /// Gets or sets the encoding to be used when writing and reading the serialized stream. /// </summary> public Encoding Encoding { get { return encoding; } set { encoding = (value ?? new ASCIIEncoding()); } } /// <summary> /// Gets or sets the serialization binder that performs type lookups during deserialization. /// </summary> public SerializationBinder Binder { get { return null; } set { throw new NotSupportedException(LibResources.GetString("serialization_binder_unsupported")); } } /// <summary> /// Gets or sets the streaming context used for serialization and deserialization. /// </summary> public StreamingContext Context { get { return new StreamingContext(StreamingContextStates.Persistence); } set { throw new NotSupportedException(LibResources.GetString("streaming_context_unsupported")); } } /// <summary> /// Gets or sets the surrogate selector used by the current formatter. /// </summary> public ISurrogateSelector SurrogateSelector { get { return null; } set { throw new NotSupportedException(LibResources.GetString("surrogate_selector_unsupported")); } } #endregion #region Options /// <summary> /// Encode (serialize) options. All false. /// </summary> public class EncodeOptions { public bool HexTag = false, HexAmp = false, HexApos = false, HexQuot = false, ForceObject = false, NumericCheck = false; } /// <summary> /// Decode (unserialize) options. /// </summary> public class DecodeOptions { public bool BigIntAsString = false; /// <summary> /// When TRUE, returned object s will be converted into associative array s. /// </summary> public bool Assoc = false; /// <summary> /// User specified recursion depth. /// </summary> public int Depth = 512; } private readonly EncodeOptions encodeOptions; private readonly DecodeOptions decodeOptions; #endregion #region Construction ///// <summary> ///// Creates a new <see cref="PhpFormatter"/> with <see cref="ASCIIEncoding"/> and ///// default <see cref="Context"/>. ///// </summary> //public JsonFormatter() // :this(new ASCIIEncoding(), new EncodeOptions(), new DecodeOptions()) //{ //} /// <summary> /// Creates a new <see cref="PhpFormatter"/> with a given <see cref="Encoding"/> and /// default <see cref="Context"/>. /// </summary> /// <param name="encoding">The encoding to be used when writing and reading the serialization stream.</param> /// <param name="encodeOptions">Options used to encode the data stream.</param> /// <param name="decodeOptions">Options used to decode the data stream.</param> /// <param name="caller">DTypeDesc of the caller's class context if it is known or UnknownTypeDesc if it should be determined lazily.</param> public JsonFormatter(Encoding encoding, EncodeOptions encodeOptions, DecodeOptions decodeOptions, DTypeDesc caller) { // no UTF8 BOM! if (encoding is UTF8Encoding) this.encoding = new UTF8Encoding(false); else this.encoding = (encoding ?? new ASCIIEncoding()); // options this.encodeOptions = encodeOptions; this.decodeOptions = decodeOptions; } #endregion #region Serialize and Deserialize /// <summary> /// Serializes an object, or graph of objects with the given root to the provided stream. /// </summary> /// <param name="serializationStream">The stream where the formatter puts the serialized data.</param> /// <param name="graph">The object, or root of the object graph, to serialize.</param> public void Serialize(Stream/*!*/serializationStream, object graph) { if (serializationStream == null) throw new ArgumentNullException("serializationStream"); serializationPermission.Demand(); StreamWriter stream_writer = new StreamWriter(serializationStream, encoding); ObjectWriter object_writer = new ObjectWriter(ScriptContext.CurrentContext, stream_writer, encodeOptions, encoding); try { object_writer.Serialize(graph); } finally { stream_writer.Flush(); } } /// <summary> /// Deserializes the data on the provided stream and reconstitutes the graph of objects. /// </summary> /// <param name="serializationStream">The stream containing the data to deserialize.</param> /// <returns>The top object of the deserialized graph.</returns> public object Deserialize(Stream/*!*/serializationStream) { if (serializationStream == null) throw new ArgumentNullException("serializationStream"); serializationPermission.Demand(); ScriptContext context = ScriptContext.CurrentContext; ObjectReader object_reader = new ObjectReader(context, new StreamReader(serializationStream, encoding), decodeOptions); return object_reader.Deserialize(); } #endregion } #endregion #region JsonScanner public class JsonScanner : Json.Lexer, PHP.Core.Parsers.GPPG.ITokenProvider<Json.SemanticValueType, Json.Position> { Json.SemanticValueType tokenSemantics; Json.Position tokenPosition; private readonly PHP.Library.JsonFormatter.DecodeOptions/*!*/decodeOptions; public JsonScanner(TextReader/*!*/ reader, PHP.Library.JsonFormatter.DecodeOptions/*!*/decodeOptions) : base(reader) { Debug.Assert(decodeOptions != null); this.decodeOptions = decodeOptions; } #region ITokenProvider<SemanticValueType,Position> Members public Json.SemanticValueType TokenValue { get { return tokenSemantics; } } public Json.Position TokenPosition { get { return tokenPosition; } } public new int GetNextToken() { tokenPosition = new Json.Position(); tokenSemantics = new Json.SemanticValueType(); Json.Tokens token = base.GetNextToken(); switch (token) { case Json.Tokens.STRING_BEGIN: while ((token = base.GetNextToken()) != Json.Tokens.STRING_END) { if (token == Json.Tokens.ERROR || token == Json.Tokens.EOF) throw new Exception("Syntax error, unexpected " + TokenChunkLength.ToString()); } token = Json.Tokens.STRING; tokenSemantics.obj = base.QuotedStringContent; break; case Json.Tokens.INTEGER: case Json.Tokens.DOUBLE: { int i; long l; double d; string numtext = yytext(); switch (PHP.Core.Convert.StringToNumber(numtext, out i, out l, out d) & PHP.Core.Convert.NumberInfo.TypeMask) { case PHP.Core.Convert.NumberInfo.Double: if (decodeOptions.BigIntAsString && token == Json.Tokens.INTEGER) tokenSemantics.obj = numtext; // it was integer, but converted to double because it was too long else tokenSemantics.obj = d; break; case PHP.Core.Convert.NumberInfo.Integer: tokenSemantics.obj = i; break; case PHP.Core.Convert.NumberInfo.LongInteger: tokenSemantics.obj = l; break; default: tokenSemantics.obj = numtext; break; } } break; } return (int)token; } public void ReportError(string[] expectedTokens) { } #endregion } #endregion } namespace PHP.Library.Json { public partial class Lexer { private char Map(char c) { return (c > SByte.MaxValue) ? 'a' : c; } } }
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ // // 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. namespace Castle.ActiveRecord.Generator.Dialogs { using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Castle.ActiveRecord.Generator.Components; using Castle.ActiveRecord.Generator.Components.Database; /// <summary> /// Summary description for ActiveRecordPropertiesDialog. /// </summary> public class ActiveRecordPropertiesDialog : System.Windows.Forms.Form { private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.ListView listView1; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.Label title; private System.Windows.Forms.ColumnHeader columnHeader5; private System.Windows.Forms.ColumnHeader columnHeader6; private System.Windows.Forms.ColumnHeader columnHeader7; private System.Windows.Forms.ColumnHeader columnHeader8; private System.Windows.Forms.ListView listView2; private System.Windows.Forms.ColumnHeader columnHeader9; private System.Windows.Forms.ColumnHeader columnHeader10; private System.Windows.Forms.ColumnHeader columnHeader11; private System.Windows.Forms.ColumnHeader columnHeader12; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button AddRelation; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.CheckBox useDiscriminator; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox discValue; private System.Windows.Forms.ComboBox discColumn; private System.Windows.Forms.CheckBox isJoinedSubClass; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox joinedSubKeyColumn; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox parentClass; private System.Windows.Forms.TextBox className; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.ColumnHeader columnHeader13; private System.Windows.Forms.Button cancelButton; private ActiveRecordDescriptor _descriptor; private ActiveRecordDescriptor _parent; private System.Windows.Forms.Button EditRelation; private Project _project; public ActiveRecordPropertiesDialog(ActiveRecordDescriptor descriptor, Project project) { _project = project; _descriptor = descriptor; if (descriptor is ActiveRecordDescriptorSubClass) { _parent = ((ActiveRecordDescriptorSubClass) descriptor).BaseClass; } InitializeComponent(); Title = descriptor.ClassName + " Properties"; FillClassDetails(descriptor); FillClassProperties(descriptor); FillClassRelationships(descriptor); } private void FillClassDetails(ActiveRecordDescriptor descriptor) { className.Text = descriptor.ClassName; parentClass.Items.Add( "ActiveRecordBase" ); foreach(TableDefinition table in descriptor.Table.DatabaseDefinition.Tables) { if (table.RelatedDescriptor == null) continue; if (table.RelatedDescriptor.ClassName == null) continue; if (table.RelatedDescriptor == descriptor) continue; parentClass.Items.Add( table.RelatedDescriptor.ClassName ); } parentClass.Enabled = false; groupBox2.Enabled = false; discColumn.ValueMember = "Name"; foreach(ColumnDefinition col in descriptor.Table.Columns) { discColumn.Items.Add( col ); if (col.Name.Equals(descriptor.DiscriminatorField)) { discColumn.SelectedItem = col; } } useDiscriminator.Checked = descriptor.DiscriminatorField != null; if (descriptor.DiscriminatorValue != null) { discValue.Text = descriptor.DiscriminatorValue; } if (descriptor is ActiveRecordDescriptorSubClass || descriptor is ActiveRecordDescriptorJoinedSubClass ) { useDiscriminator.Enabled = false; isJoinedSubClass.Enabled = false; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.title = new System.Windows.Forms.Label(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.parentClass = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.joinedSubKeyColumn = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.isJoinedSubClass = new System.Windows.Forms.CheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.discValue = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.discColumn = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.useDiscriminator = new System.Windows.Forms.CheckBox(); this.className = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.listView1 = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.columnHeader3 = new System.Windows.Forms.ColumnHeader(); this.columnHeader4 = new System.Windows.Forms.ColumnHeader(); this.columnHeader13 = new System.Windows.Forms.ColumnHeader(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.EditRelation = new System.Windows.Forms.Button(); this.AddRelation = new System.Windows.Forms.Button(); this.listView2 = new System.Windows.Forms.ListView(); this.columnHeader9 = new System.Windows.Forms.ColumnHeader(); this.columnHeader10 = new System.Windows.Forms.ColumnHeader(); this.columnHeader11 = new System.Windows.Forms.ColumnHeader(); this.columnHeader12 = new System.Windows.Forms.ColumnHeader(); this.columnHeader5 = new System.Windows.Forms.ColumnHeader(); this.columnHeader6 = new System.Windows.Forms.ColumnHeader(); this.columnHeader7 = new System.Windows.Forms.ColumnHeader(); this.columnHeader8 = new System.Windows.Forms.ColumnHeader(); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.tabControl1.SuspendLayout(); this.tabPage3.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.SuspendLayout(); // // title // this.title.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.title.Location = new System.Drawing.Point(16, 12); this.title.Name = "title"; this.title.Size = new System.Drawing.Size(648, 23); this.title.TabIndex = 1; this.title.Text = "Class properties"; // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Location = new System.Drawing.Point(16, 40); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(656, 320); this.tabControl1.TabIndex = 2; // // tabPage3 // this.tabPage3.Controls.Add(this.parentClass); this.tabPage3.Controls.Add(this.label3); this.tabPage3.Controls.Add(this.groupBox2); this.tabPage3.Controls.Add(this.groupBox1); this.tabPage3.Controls.Add(this.className); this.tabPage3.Controls.Add(this.label1); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(648, 294); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Class"; // // parentClass // this.parentClass.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.parentClass.Location = new System.Drawing.Point(272, 48); this.parentClass.Name = "parentClass"; this.parentClass.Size = new System.Drawing.Size(192, 21); this.parentClass.TabIndex = 9; // // label3 // this.label3.Location = new System.Drawing.Point(176, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(100, 24); this.label3.TabIndex = 8; this.label3.Text = "Parent:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // groupBox2 // this.groupBox2.Controls.Add(this.joinedSubKeyColumn); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.isJoinedSubClass); this.groupBox2.Location = new System.Drawing.Point(336, 104); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(288, 168); this.groupBox2.TabIndex = 4; this.groupBox2.TabStop = false; this.groupBox2.Text = "Joined-subclass"; // // joinedSubKeyColumn // this.joinedSubKeyColumn.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.joinedSubKeyColumn.Enabled = false; this.joinedSubKeyColumn.Location = new System.Drawing.Point(128, 64); this.joinedSubKeyColumn.Name = "joinedSubKeyColumn"; this.joinedSubKeyColumn.Size = new System.Drawing.Size(136, 21); this.joinedSubKeyColumn.TabIndex = 7; // // label5 // this.label5.Enabled = false; this.label5.Location = new System.Drawing.Point(32, 64); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(100, 24); this.label5.TabIndex = 6; this.label5.Text = "Key column:"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // isJoinedSubClass // this.isJoinedSubClass.Location = new System.Drawing.Point(72, 24); this.isJoinedSubClass.Name = "isJoinedSubClass"; this.isJoinedSubClass.Size = new System.Drawing.Size(152, 24); this.isJoinedSubClass.TabIndex = 4; this.isJoinedSubClass.Text = "Is Joined subclass"; // // groupBox1 // this.groupBox1.Controls.Add(this.discValue); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.discColumn); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.useDiscriminator); this.groupBox1.Location = new System.Drawing.Point(24, 104); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(288, 168); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Text = "Table hierarchy"; // // discValue // this.discValue.Location = new System.Drawing.Point(120, 96); this.discValue.Name = "discValue"; this.discValue.Size = new System.Drawing.Size(136, 21); this.discValue.TabIndex = 9; this.discValue.Text = ""; // // label4 // this.label4.Location = new System.Drawing.Point(24, 96); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(100, 24); this.label4.TabIndex = 8; this.label4.Text = "Disc. Value:"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // discColumn // this.discColumn.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.discColumn.Enabled = false; this.discColumn.Location = new System.Drawing.Point(120, 64); this.discColumn.Name = "discColumn"; this.discColumn.Size = new System.Drawing.Size(136, 21); this.discColumn.TabIndex = 5; // // label2 // this.label2.Enabled = false; this.label2.Location = new System.Drawing.Point(24, 64); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(100, 24); this.label2.TabIndex = 4; this.label2.Text = "Discriminator:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // useDiscriminator // this.useDiscriminator.Location = new System.Drawing.Point(56, 24); this.useDiscriminator.Name = "useDiscriminator"; this.useDiscriminator.Size = new System.Drawing.Size(152, 24); this.useDiscriminator.TabIndex = 3; this.useDiscriminator.Text = "Use discriminator column"; this.useDiscriminator.CheckedChanged += new System.EventHandler(this.useDiscriminator_CheckedChanged); // // className // this.className.Location = new System.Drawing.Point(272, 16); this.className.Name = "className"; this.className.Size = new System.Drawing.Size(192, 21); this.className.TabIndex = 1; this.className.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(176, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 24); this.label1.TabIndex = 0; this.label1.Text = "Class name:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tabPage1 // this.tabPage1.Controls.Add(this.listView1); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(648, 294); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Columns"; // // listView1 // this.listView1.CheckBoxes = true; this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4, this.columnHeader13}); this.listView1.FullRowSelect = true; this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listView1.LabelEdit = true; this.listView1.Location = new System.Drawing.Point(36, 27); this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(576, 213); this.listView1.TabIndex = 2; this.listView1.View = System.Windows.Forms.View.Details; this.listView1.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.listView1_AfterLabelEdit); // // columnHeader1 // this.columnHeader1.Text = "Property"; this.columnHeader1.Width = 170; // // columnHeader2 // this.columnHeader2.Text = "Type"; this.columnHeader2.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader2.Width = 90; // // columnHeader3 // this.columnHeader3.Text = "Column"; this.columnHeader3.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader3.Width = 160; // // columnHeader4 // this.columnHeader4.Text = "Type"; this.columnHeader4.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader4.Width = 90; // // columnHeader13 // this.columnHeader13.Text = "PK"; this.columnHeader13.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // tabPage2 // this.tabPage2.Controls.Add(this.EditRelation); this.tabPage2.Controls.Add(this.AddRelation); this.tabPage2.Controls.Add(this.listView2); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(648, 294); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Relationships"; // // EditRelation // this.EditRelation.Enabled = false; this.EditRelation.Location = new System.Drawing.Point(392, 256); this.EditRelation.Name = "EditRelation"; this.EditRelation.Size = new System.Drawing.Size(104, 23); this.EditRelation.TabIndex = 6; this.EditRelation.Text = "Edit Relation"; this.EditRelation.Click += new System.EventHandler(this.EditRelation_Click); // // AddRelation // this.AddRelation.Location = new System.Drawing.Point(504, 256); this.AddRelation.Name = "AddRelation"; this.AddRelation.Size = new System.Drawing.Size(104, 23); this.AddRelation.TabIndex = 5; this.AddRelation.Text = "Add Relation"; this.AddRelation.Click += new System.EventHandler(this.AddRelation_Click); // // listView2 // this.listView2.CheckBoxes = true; this.listView2.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader9, this.columnHeader10, this.columnHeader11, this.columnHeader12}); this.listView2.FullRowSelect = true; this.listView2.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listView2.LabelEdit = true; this.listView2.Location = new System.Drawing.Point(36, 27); this.listView2.Name = "listView2"; this.listView2.Size = new System.Drawing.Size(576, 213); this.listView2.TabIndex = 4; this.listView2.View = System.Windows.Forms.View.Details; this.listView2.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.listView2_AfterLabelEdit); // // columnHeader9 // this.columnHeader9.Text = "Property"; this.columnHeader9.Width = 190; // // columnHeader10 // this.columnHeader10.Text = "Type"; this.columnHeader10.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader10.Width = 90; // // columnHeader11 // this.columnHeader11.Text = "Association"; this.columnHeader11.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader11.Width = 120; // // columnHeader12 // this.columnHeader12.Text = "Column"; this.columnHeader12.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader12.Width = 160; // // columnHeader5 // this.columnHeader5.Text = "Property"; this.columnHeader5.Width = 190; // // columnHeader6 // this.columnHeader6.Text = "Type"; this.columnHeader6.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader6.Width = 90; // // columnHeader7 // this.columnHeader7.Text = "Association"; this.columnHeader7.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader7.Width = 120; // // columnHeader8 // this.columnHeader8.Text = "Column"; this.columnHeader8.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.columnHeader8.Width = 160; // // okButton // this.okButton.Location = new System.Drawing.Point(592, 376); this.okButton.Name = "okButton"; this.okButton.TabIndex = 3; this.okButton.Text = "OK"; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(504, 376); this.cancelButton.Name = "cancelButton"; this.cancelButton.TabIndex = 4; this.cancelButton.Text = "Cancel"; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // ActiveRecordPropertiesDialog // this.AcceptButton = this.okButton; this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(686, 408); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.Controls.Add(this.tabControl1); this.Controls.Add(this.title); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ActiveRecordPropertiesDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Properties"; this.tabControl1.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void useDiscriminator_CheckedChanged(object sender, System.EventArgs e) { label2.Enabled = discColumn.Enabled = useDiscriminator.Checked; } public String Title { get { return title.Text; } set { title.Text = value; } } private void FillClassProperties(ActiveRecordDescriptor descriptor) { listView1.Items.Clear(); IList added = new ArrayList(); foreach(ActiveRecordPropertyDescriptor prop in descriptor.Properties) { ListViewItem item = listView1.Items.Add(prop.PropertyName); item.Tag = prop; item.Checked = prop.Generate; item.SubItems.Add( prop.PropertyType.ToString() ); item.SubItems.Add( prop.ColumnName ); item.SubItems.Add( prop.ColumnTypeName ); item.SubItems.Add( (prop is ActiveRecordPrimaryKeyDescriptor) ? "Yes" : "" ); added.Add(prop); } if (descriptor is ActiveRecordDescriptorSubClass) { // This code might look strange, but we're // only showing the fields on the parent class that haven't been // marked for generation, so the user might have the // oportunity to add them foreach(ActiveRecordPropertyDescriptor prop in _parent.Properties) { if (prop.Generate || added.Contains(prop)) continue; ListViewItem item = listView1.Items.Add(prop.PropertyName); item.Tag = prop; item.Checked = prop.Generate; item.SubItems.Add( prop.PropertyType.ToString() ); item.SubItems.Add( prop.ColumnName ); item.SubItems.Add( prop.ColumnTypeName ); item.SubItems.Add( (prop is ActiveRecordPrimaryKeyDescriptor) ? "Yes" : "" ); } } } private void FillClassRelationships(ActiveRecordDescriptor descriptor) { listView2.Items.Clear(); IList added = new ArrayList(); foreach(ActiveRecordPropertyRelationDescriptor prop in descriptor.PropertiesRelations) { ListViewItem item = listView2.Items.Add(prop.PropertyName); item.Tag = prop; item.Checked = prop.Generate; if (prop.TargetType == null) { throw new ApplicationException("Information missing"); } item.SubItems.Add( prop.TargetType.ClassName ); item.SubItems.Add( prop.RelationType ); item.SubItems.Add( prop.ColumnName ); added.Add(prop); } if (descriptor is ActiveRecordDescriptorSubClass) { // This code might look strange, but we're // only showing the fields on the parent class that haven't been // marked for generation, so the user might have the // oportunity to add them foreach(ActiveRecordPropertyRelationDescriptor prop in _parent.PropertiesRelations) { if (prop.Generate || added.Contains(prop)) continue; ListViewItem item = listView2.Items.Add(prop.PropertyName); item.Tag = prop; item.Checked = prop.Generate; if (prop.TargetType == null) { throw new ApplicationException("Information missing"); } item.SubItems.Add( prop.TargetType.ClassName ); item.SubItems.Add( prop.RelationType ); item.SubItems.Add( prop.ColumnName ); } } } private void okButton_Click(object sender, System.EventArgs e) { if (className.Text.Length == 0 || className.Text.IndexOf(' ') != -1) { MessageBox.Show("Invalid class name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // What's common can be updated without any problems: SaveCommonFields(); // Updating properties SaveClassProperties(); // Updating relations SaveClassRelationships(); // Now here, semantic matters DialogResult = DialogResult.OK; Close(); } private void AddRelation_Click(object sender, System.EventArgs e) { using(AddRelationDialog addRelationDlg = new AddRelationDialog(_descriptor, _project)) { if (addRelationDlg.ShowDialog( this ) == DialogResult.OK) { FillClassRelationships( _descriptor ); } } } private void SaveClassRelationships() { _descriptor.PropertiesRelations.Clear(); foreach(ListViewItem item in listView2.Items) { ActiveRecordPropertyDescriptor prop = item.Tag as ActiveRecordPropertyDescriptor; if (_parent != null && _parent.PropertiesRelations.Contains(prop)) { // This is important as modification here // wont affect the property descriptor on the parent prop = (ActiveRecordPropertyDescriptor) prop.Clone(); } _descriptor.PropertiesRelations.Add( prop ); prop.Generate = item.Checked; } } private void SaveClassProperties() { _descriptor.Properties.Clear(); foreach(ListViewItem item in listView1.Items) { ActiveRecordPropertyDescriptor prop = item.Tag as ActiveRecordPropertyDescriptor; if (_parent != null && _parent.Properties.Contains(prop)) { // This is important as modification here // wont affect the property descriptor on the parent prop = (ActiveRecordPropertyDescriptor) prop.Clone(); } _descriptor.Properties.Add( prop ); prop.Generate = item.Checked; } } private void SaveCommonFields() { if (className.Text.Length != 0) { _descriptor.ClassName = className.Text; } if (discColumn.SelectedIndex == -1) { _descriptor.DiscriminatorField = null; } else { _descriptor.DiscriminatorField = (discColumn.SelectedItem as ColumnDefinition).Name; } if (discValue.Text.Length != 0) { _descriptor.DiscriminatorValue = discValue.Text; } else { _descriptor.DiscriminatorValue = null; } } private void listView1_AfterLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e) { if (e.Label == null || e.Label.Length == 0) { e.CancelEdit = true; } else { ActiveRecordPropertyDescriptor desc = listView1.Items[e.Item].Tag as ActiveRecordPropertyDescriptor; desc.PropertyName = e.Label; } } private void listView2_AfterLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e) { if (e.Label == null || e.Label.Length == 0) { e.CancelEdit = true; } else { ActiveRecordPropertyDescriptor desc = listView2.Items[e.Item].Tag as ActiveRecordPropertyDescriptor; desc.PropertyName = e.Label; } } private void cancelButton_Click(object sender, System.EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void EditRelation_Click(object sender, System.EventArgs e) { if (listView2.SelectedItems.Count != 0) { ActiveRecordPropertyRelationDescriptor prop = listView2.SelectedItems[0].Tag as ActiveRecordPropertyRelationDescriptor; using(EditRelationDialog editDlg = new EditRelationDialog(_descriptor, _project, prop)) { if (editDlg.ShowDialog( this ) == DialogResult.OK) { _descriptor.PropertiesRelations.Remove(prop); FillClassRelationships( _descriptor ); } } } else { MessageBox.Show(this.Owner, "Select an existing relationship first."); } } } }
using System; using System.IO; using System.Linq; using LibGit2Sharp.Tests.TestHelpers; using Xunit; using Xunit.Extensions; namespace LibGit2Sharp.Tests { public class UnstageFixture : BaseFixture { [Fact] public void StagingANewVersionOfAFileThenUnstagingItRevertsTheBlobToTheVersionOfHead() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; string filename = Path.Combine("1", "branch_file.txt"); const string posixifiedFileName = "1/branch_file.txt"; ObjectId blobId = repo.Index[posixifiedFileName].Id; string fullpath = Path.Combine(repo.Info.WorkingDirectory, filename); File.AppendAllText(fullpath, "Is there there anybody out there?"); repo.Index.Stage(filename); Assert.Equal(count, repo.Index.Count); Assert.NotEqual((blobId), repo.Index[posixifiedFileName].Id); repo.Index.Unstage(posixifiedFileName); Assert.Equal(count, repo.Index.Count); Assert.Equal(blobId, repo.Index[posixifiedFileName].Id); } } [Fact] public void CanStageAndUnstageAnIgnoredFile() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { Touch(repo.Info.WorkingDirectory, ".gitignore", "*.ign" + Environment.NewLine); const string relativePath = "Champa.ign"; Touch(repo.Info.WorkingDirectory, relativePath, "On stage!" + Environment.NewLine); Assert.Equal(FileStatus.Ignored, repo.Index.RetrieveStatus(relativePath)); repo.Index.Stage(relativePath); Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(relativePath)); repo.Index.Unstage(relativePath); Assert.Equal(FileStatus.Ignored, repo.Index.RetrieveStatus(relativePath)); } } [Theory] [InlineData("1/branch_file.txt", FileStatus.Unaltered, true, FileStatus.Unaltered, true, 0)] [InlineData("deleted_unstaged_file.txt", FileStatus.Missing, true, FileStatus.Missing, true, 0)] [InlineData("modified_unstaged_file.txt", FileStatus.Modified, true, FileStatus.Modified, true, 0)] [InlineData("modified_staged_file.txt", FileStatus.Staged, true, FileStatus.Modified, true, 0)] [InlineData("new_tracked_file.txt", FileStatus.Added, true, FileStatus.Untracked, false, -1)] [InlineData("deleted_staged_file.txt", FileStatus.Removed, false, FileStatus.Missing, true, 1)] public void CanUnstage( string relativePath, FileStatus currentStatus, bool doesCurrentlyExistInTheIndex, FileStatus expectedStatusOnceStaged, bool doesExistInTheIndexOnceStaged, int expectedIndexCountVariation) { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; Assert.Equal(doesCurrentlyExistInTheIndex, (repo.Index[relativePath] != null)); Assert.Equal(currentStatus, repo.Index.RetrieveStatus(relativePath)); repo.Index.Unstage(relativePath); Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count); Assert.Equal(doesExistInTheIndexOnceStaged, (repo.Index[relativePath] != null)); Assert.Equal(expectedStatusOnceStaged, repo.Index.RetrieveStatus(relativePath)); } } [Theory] [InlineData("new_untracked_file.txt", FileStatus.Untracked)] [InlineData("where-am-I.txt", FileStatus.Nonexistent)] public void UnstagingUnknownPathsWithStrictUnmatchedExplicitPathsValidationThrows(string relativePath, FileStatus currentStatus) { using (var repo = new Repository(CloneStandardTestRepo())) { Assert.Equal(currentStatus, repo.Index.RetrieveStatus(relativePath)); Assert.Throws<UnmatchedPathException>(() => repo.Index.Unstage(relativePath, new ExplicitPathsOptions())); } } [Theory] [InlineData("new_untracked_file.txt", FileStatus.Untracked)] [InlineData("where-am-I.txt", FileStatus.Nonexistent)] public void CanUnstageUnknownPathsWithLaxUnmatchedExplicitPathsValidation(string relativePath, FileStatus currentStatus) { using (var repo = new Repository(CloneStandardTestRepo())) { Assert.Equal(currentStatus, repo.Index.RetrieveStatus(relativePath)); Assert.DoesNotThrow(() => repo.Index.Unstage(relativePath, new ExplicitPathsOptions() { ShouldFailOnUnmatchedPath = false })); Assert.Equal(currentStatus, repo.Index.RetrieveStatus(relativePath)); } } [Fact] public void CanUnstageTheRemovalOfAFile() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; const string filename = "deleted_staged_file.txt"; string fullPath = Path.Combine(repo.Info.WorkingDirectory, filename); Assert.False(File.Exists(fullPath)); Assert.Equal(FileStatus.Removed, repo.Index.RetrieveStatus(filename)); repo.Index.Unstage(filename); Assert.Equal(count + 1, repo.Index.Count); Assert.Equal(FileStatus.Missing, repo.Index.RetrieveStatus(filename)); } } [Fact] public void CanUnstageUntrackedFileAgainstAnOrphanedHead() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { const string relativePath = "a.txt"; Touch(repo.Info.WorkingDirectory, relativePath, "hello test file\n"); repo.Index.Stage(relativePath); repo.Index.Unstage(relativePath); RepositoryStatus status = repo.Index.RetrieveStatus(); Assert.Equal(0, status.Staged.Count()); Assert.Equal(1, status.Untracked.Count()); Assert.Throws<UnmatchedPathException>(() => repo.Index.Unstage("i-dont-exist", new ExplicitPathsOptions())); } } [Theory] [InlineData("new_untracked_file.txt", FileStatus.Untracked)] [InlineData("where-am-I.txt", FileStatus.Nonexistent)] public void UnstagingUnknownPathsAgainstAnOrphanedHeadWithStrictUnmatchedExplicitPathsValidationThrows(string relativePath, FileStatus currentStatus) { using (var repo = new Repository(CloneStandardTestRepo())) { repo.Refs.UpdateTarget("HEAD", "refs/heads/orphaned"); Assert.True(repo.Info.IsHeadUnborn); Assert.Equal(currentStatus, repo.Index.RetrieveStatus(relativePath)); Assert.Throws<UnmatchedPathException>(() => repo.Index.Unstage(relativePath, new ExplicitPathsOptions())); } } [Theory] [InlineData("new_untracked_file.txt", FileStatus.Untracked)] [InlineData("where-am-I.txt", FileStatus.Nonexistent)] public void CanUnstageUnknownPathsAgainstAnOrphanedHeadWithLaxUnmatchedExplicitPathsValidation(string relativePath, FileStatus currentStatus) { using (var repo = new Repository(CloneStandardTestRepo())) { repo.Refs.UpdateTarget("HEAD", "refs/heads/orphaned"); Assert.True(repo.Info.IsHeadUnborn); Assert.Equal(currentStatus, repo.Index.RetrieveStatus(relativePath)); Assert.DoesNotThrow(() => repo.Index.Unstage(relativePath)); Assert.DoesNotThrow(() => repo.Index.Unstage(relativePath, new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false })); Assert.Equal(currentStatus, repo.Index.RetrieveStatus(relativePath)); } } [Fact] public void UnstagingANewFileWithAFullPathWhichEscapesOutOfTheWorkingDirThrows() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { DirectoryInfo di = Directory.CreateDirectory(scd.DirectoryPath); const string filename = "unit_test.txt"; string fullPath = Touch(di.FullName, filename, "some contents"); Assert.Throws<ArgumentException>(() => repo.Index.Unstage(fullPath)); } } [Fact] public void UnstagingANewFileWithAFullPathWhichEscapesOutOfTheWorkingDirAgainstAnOrphanedHeadThrows() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { DirectoryInfo di = Directory.CreateDirectory(scd.DirectoryPath); const string filename = "unit_test.txt"; string fullPath = Touch(di.FullName, filename, "some contents"); Assert.Throws<ArgumentException>(() => repo.Index.Unstage(fullPath)); } } [Fact] public void UnstagingFileWithBadParamsThrows() { using (var repo = new Repository(StandardTestRepoPath)) { Assert.Throws<ArgumentException>(() => repo.Index.Unstage(string.Empty)); Assert.Throws<ArgumentNullException>(() => repo.Index.Unstage((string)null)); Assert.Throws<ArgumentException>(() => repo.Index.Unstage(new string[] { })); Assert.Throws<ArgumentException>(() => repo.Index.Unstage(new string[] { null })); } } } }
/* * XmlSchemaReader.cs - Implementation of "System.Xml.Schema.XmlSchemaReader" * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * Copyright (C) 2003 FSF. * * Authors : Autogenerated using csdoc2stub * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Xml.Schema { public class XmlSchemaReader: System.Xml.XmlReader, System.Xml.IXmlLineInfo { [TODO] public XmlSchemaReader(System.Xml.XmlReader reader, System.Xml.Schema.ValidationEventHandler handler) { throw new NotImplementedException(".ctor"); } [TODO] public override void Close() { throw new NotImplementedException("Close"); } [TODO] public override bool Equals(System.Object obj) { throw new NotImplementedException("Equals"); } [TODO] public override System.String GetAttribute(int i) { throw new NotImplementedException("GetAttribute"); } [TODO] public override System.String GetAttribute(System.String name) { throw new NotImplementedException("GetAttribute"); } [TODO] public override System.String GetAttribute(System.String name, System.String namespaceURI) { throw new NotImplementedException("GetAttribute"); } [TODO] public override int GetHashCode() { throw new NotImplementedException("GetHashCode"); } [TODO] public bool HasLineInfo() { throw new NotImplementedException("HasLineInfo"); } [TODO] public override bool IsStartElement() { throw new NotImplementedException("IsStartElement"); } [TODO] public override bool IsStartElement(System.String localname, System.String ns) { throw new NotImplementedException("IsStartElement"); } [TODO] public override bool IsStartElement(System.String name) { throw new NotImplementedException("IsStartElement"); } [TODO] public override System.String LookupNamespace(System.String prefix) { throw new NotImplementedException("LookupNamespace"); } [TODO] public override void MoveToAttribute(int i) { throw new NotImplementedException("MoveToAttribute"); } [TODO] public override bool MoveToAttribute(System.String name) { throw new NotImplementedException("MoveToAttribute"); } [TODO] public override bool MoveToAttribute(System.String name, System.String ns) { throw new NotImplementedException("MoveToAttribute"); } [TODO] public override System.Xml.XmlNodeType MoveToContent() { throw new NotImplementedException("MoveToContent"); } [TODO] public override bool MoveToElement() { throw new NotImplementedException("MoveToElement"); } [TODO] public override bool MoveToFirstAttribute() { throw new NotImplementedException("MoveToFirstAttribute"); } [TODO] public override bool MoveToNextAttribute() { throw new NotImplementedException("MoveToNextAttribute"); } [TODO] public void RaiseInvalidElementError() { throw new NotImplementedException("RaiseInvalidElementError"); } [TODO] public override bool Read() { throw new NotImplementedException("Read"); } [TODO] public override bool ReadAttributeValue() { throw new NotImplementedException("ReadAttributeValue"); } [TODO] public override System.String ReadElementString() { throw new NotImplementedException("ReadElementString"); } [TODO] public override System.String ReadElementString(System.String localname, System.String ns) { throw new NotImplementedException("ReadElementString"); } [TODO] public override System.String ReadElementString(System.String name) { throw new NotImplementedException("ReadElementString"); } [TODO] public override void ReadEndElement() { throw new NotImplementedException("ReadEndElement"); } [TODO] public override System.String ReadInnerXml() { throw new NotImplementedException("ReadInnerXml"); } [TODO] public bool ReadNextElement() { throw new NotImplementedException("ReadNextElement"); } [TODO] public override System.String ReadOuterXml() { throw new NotImplementedException("ReadOuterXml"); } [TODO] public override void ReadStartElement() { throw new NotImplementedException("ReadStartElement"); } [TODO] public override void ReadStartElement(System.String localname, System.String ns) { throw new NotImplementedException("ReadStartElement"); } [TODO] public override void ReadStartElement(System.String name) { throw new NotImplementedException("ReadStartElement"); } [TODO] public override System.String ReadString() { throw new NotImplementedException("ReadString"); } [TODO] public override void ResolveEntity() { throw new NotImplementedException("ResolveEntity"); } [TODO] public override void Skip() { throw new NotImplementedException("Skip"); } [TODO] public void SkipToEnd() { throw new NotImplementedException("SkipToEnd"); } [TODO] public override System.String ToString() { throw new NotImplementedException("ToString"); } [TODO] public override int AttributeCount { get { throw new NotImplementedException("AttributeCount"); } } [TODO] public override System.String BaseURI { get { throw new NotImplementedException("BaseURI"); } } [TODO] public override bool CanResolveEntity { get { throw new NotImplementedException("CanResolveEntity"); } } [TODO] public override int Depth { get { throw new NotImplementedException("Depth"); } } [TODO] public override bool EOF { get { throw new NotImplementedException("EOF"); } } [TODO] public System.String FullName { get { throw new NotImplementedException("FullName"); } } [TODO] public override bool HasAttributes { get { throw new NotImplementedException("HasAttributes"); } } [TODO] public override bool HasValue { get { throw new NotImplementedException("HasValue"); } } [TODO] public override bool IsDefault { get { throw new NotImplementedException("IsDefault"); } } [TODO] public override bool IsEmptyElement { get { throw new NotImplementedException("IsEmptyElement"); } } [TODO] public override System.String this[int i] { get { throw new NotImplementedException("Item"); } } [TODO] public override System.String this[System.String name] { get { throw new NotImplementedException("Item"); } } [TODO] public override System.String this[System.String name, System.String namespaceURI] { get { throw new NotImplementedException("Item"); } } [TODO] public int LineNumber { get { throw new NotImplementedException("LineNumber"); } } [TODO] public int LinePosition { get { throw new NotImplementedException("LinePosition"); } } [TODO] public override System.String LocalName { get { throw new NotImplementedException("LocalName"); } } [TODO] public override System.String Name { get { throw new NotImplementedException("Name"); } } [TODO] public override System.Xml.XmlNameTable NameTable { get { throw new NotImplementedException("NameTable"); } } [TODO] public override System.String NamespaceURI { get { throw new NotImplementedException("NamespaceURI"); } } [TODO] public override System.Xml.XmlNodeType NodeType { get { throw new NotImplementedException("NodeType"); } } [TODO] public override System.String Prefix { get { throw new NotImplementedException("Prefix"); } } [TODO] public override char QuoteChar { get { throw new NotImplementedException("QuoteChar"); } } [TODO] public override System.Xml.ReadState ReadState { get { throw new NotImplementedException("ReadState"); } } [TODO] public override System.String Value { get { throw new NotImplementedException("Value"); } } [TODO] public override System.String XmlLang { get { throw new NotImplementedException("XmlLang"); } } [TODO] public override System.Xml.XmlSpace XmlSpace { get { throw new NotImplementedException("XmlSpace"); } } } }//namespace
// 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.Immutable; using System.Diagnostics; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { public struct TypeDefinition { private readonly MetadataReader _reader; // Workaround: JIT doesn't generate good code for nested structures, so use RowId. private readonly uint _treatmentAndRowId; internal TypeDefinition(MetadataReader reader, uint treatmentAndRowId) { Debug.Assert(reader != null); Debug.Assert(treatmentAndRowId != 0); _reader = reader; _treatmentAndRowId = treatmentAndRowId; } private int RowId { get { return (int)(_treatmentAndRowId & TokenTypeIds.RIDMask); } } private TypeDefTreatment Treatment { get { return (TypeDefTreatment)(_treatmentAndRowId >> TokenTypeIds.RowIdBitCount); } } private TypeDefinitionHandle Handle { get { return TypeDefinitionHandle.FromRowId(RowId); } } public TypeAttributes Attributes { get { if (Treatment == 0) { return _reader.TypeDefTable.GetFlags(Handle); } return GetProjectedFlags(); } } /// <summary> /// Name of the type. /// </summary> public StringHandle Name { get { if (Treatment == 0) { return _reader.TypeDefTable.GetName(Handle); } return GetProjectedName(); } } /// <summary> /// Full name of the namespace where the type is defined, or nil if the type is nested or defined in a root namespace. /// </summary> public StringHandle Namespace { get { if (Treatment == 0) { return _reader.TypeDefTable.GetNamespace(Handle); } return GetProjectedNamespaceString(); } } /// <summary> /// The definition handle of the namespace where the type is defined, or nil if the type is nested or defined in a root namespace. /// </summary> public NamespaceDefinitionHandle NamespaceDefinition { get { if (Treatment == 0) { return _reader.TypeDefTable.GetNamespaceDefinition(Handle); } return GetProjectedNamespace(); } } /// <summary> /// The base type of the type definition: either /// <see cref="TypeSpecificationHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeDefinitionHandle"/>. /// </summary> public EntityHandle BaseType { get { if (Treatment == 0) { return _reader.TypeDefTable.GetExtends(Handle); } return GetProjectedBaseType(); } } public TypeLayout GetLayout() { int classLayoutRowId = _reader.ClassLayoutTable.FindRow(Handle); if (classLayoutRowId == 0) { // NOTE: We don't need a bool/TryGetLayout because zero also means use default: // // Spec: // ClassSize of zero does not mean the class has zero size. It means that no .size directive was specified // at definition time, in which case, the actual size is calculated from the field types, taking account of // packing size (default or specified) and natural alignment on the target, runtime platform. // // PackingSize shall be one of {0, 1, 2, 4, 8, 16, 32, 64, 128}. (0 means use // the default pack size for the platform on which the application is // running.) return default(TypeLayout); } uint size = _reader.ClassLayoutTable.GetClassSize(classLayoutRowId); // The spec doesn't limit the size to 31bit. It only limits the size to 1MB if Parent is a value type. // It however doesn't make much sense to define classes with >2GB size. So in order to keep the API // clean of unsigned ints we impose the limit. if (unchecked((int)size) != size) { throw new BadImageFormatException(MetadataResources.InvalidTypeSize); } int packingSize = _reader.ClassLayoutTable.GetPackingSize(classLayoutRowId); return new TypeLayout((int)size, packingSize); } /// <summary> /// Returns the enclosing type of a specified nested type or nil handle if the type is not nested. /// </summary> public TypeDefinitionHandle GetDeclaringType() { return _reader.NestedClassTable.FindEnclosingType(Handle); } public GenericParameterHandleCollection GetGenericParameters() { return _reader.GenericParamTable.FindGenericParametersForType(Handle); } public MethodDefinitionHandleCollection GetMethods() { return new MethodDefinitionHandleCollection(_reader, Handle); } public FieldDefinitionHandleCollection GetFields() { return new FieldDefinitionHandleCollection(_reader, Handle); } public PropertyDefinitionHandleCollection GetProperties() { return new PropertyDefinitionHandleCollection(_reader, Handle); } public EventDefinitionHandleCollection GetEvents() { return new EventDefinitionHandleCollection(_reader, Handle); } /// <summary> /// Returns an array of types nested in the specified type. /// </summary> public ImmutableArray<TypeDefinitionHandle> GetNestedTypes() { return _reader.GetNestedTypes(Handle); } public MethodImplementationHandleCollection GetMethodImplementations() { return new MethodImplementationHandleCollection(_reader, Handle); } public InterfaceImplementationHandleCollection GetInterfaceImplementations() { return new InterfaceImplementationHandleCollection(_reader, Handle); } public CustomAttributeHandleCollection GetCustomAttributes() { return new CustomAttributeHandleCollection(_reader, Handle); } public DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() { return new DeclarativeSecurityAttributeHandleCollection(_reader, Handle); } #region Projections private TypeAttributes GetProjectedFlags() { var flags = _reader.TypeDefTable.GetFlags(Handle); var treatment = Treatment; switch (treatment & TypeDefTreatment.KindMask) { case TypeDefTreatment.NormalNonAttribute: flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Import; break; case TypeDefTreatment.NormalAttribute: flags |= TypeAttributes.WindowsRuntime | TypeAttributes.Sealed; break; case TypeDefTreatment.UnmangleWinRTName: flags = flags & ~TypeAttributes.SpecialName | TypeAttributes.Public; break; case TypeDefTreatment.PrefixWinRTName: flags = flags & ~TypeAttributes.Public | TypeAttributes.Import; break; case TypeDefTreatment.RedirectedToClrType: flags = flags & ~TypeAttributes.Public | TypeAttributes.Import; break; case TypeDefTreatment.RedirectedToClrAttribute: flags &= ~TypeAttributes.Public; break; } if ((treatment & TypeDefTreatment.MarkAbstractFlag) != 0) { flags |= TypeAttributes.Abstract; } if ((treatment & TypeDefTreatment.MarkInternalFlag) != 0) { flags &= ~TypeAttributes.Public; } return flags; } private StringHandle GetProjectedName() { var name = _reader.TypeDefTable.GetName(Handle); switch (Treatment & TypeDefTreatment.KindMask) { case TypeDefTreatment.UnmangleWinRTName: return name.SuffixRaw(MetadataReader.ClrPrefix.Length); case TypeDefTreatment.PrefixWinRTName: return name.WithWinRTPrefix(); } return name; } private NamespaceDefinitionHandle GetProjectedNamespace() { // NOTE: NamespaceDefinitionHandle currently relies on never having virtual values. If this ever gets projected // to a virtual namespace name, then that assumption will need to be removed. // no change: return _reader.TypeDefTable.GetNamespaceDefinition(Handle); } private StringHandle GetProjectedNamespaceString() { // no change: return _reader.TypeDefTable.GetNamespace(Handle); } private EntityHandle GetProjectedBaseType() { // no change: return _reader.TypeDefTable.GetExtends(Handle); } #endregion } }
// $ANTLR 3.1.2 BuildOptions\\ProfileGrammar.g3 2009-09-30 13:18:18 // The variable 'variable' is assigned but its value is never used. #pragma warning disable 219 // Unreachable code detected. #pragma warning disable 162 using System.Collections.Generic; using Antlr.Runtime; using Stack = System.Collections.Generic.Stack<object>; using List = System.Collections.IList; using ArrayList = System.Collections.Generic.List<object>; [System.CodeDom.Compiler.GeneratedCode("ANTLR", "3.1.2")] [System.CLSCompliant(false)] public partial class ProfileGrammarLexer : Lexer { public const int EOF=-1; public const int T__10=10; public const int T__11=11; public const int T__12=12; public const int T__13=13; public const int T__14=14; public const int T__15=15; public const int T__16=16; public const int T__17=17; public const int CALL=4; public const int FUNC=5; public const int ID=6; public const int INT=7; public const int NEWLINE=8; public const int WS=9; // delegates // delegators public ProfileGrammarLexer() {} public ProfileGrammarLexer( ICharStream input ) : this( input, new RecognizerSharedState() ) { } public ProfileGrammarLexer( ICharStream input, RecognizerSharedState state ) : base( input, state ) { } public override string GrammarFileName { get { return "BuildOptions\\ProfileGrammar.g3"; } } // $ANTLR start "T__10" private void mT__10() { try { int _type = T__10; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:7:9: ( '-' ) // BuildOptions\\ProfileGrammar.g3:7:9: '-' { Match('-'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__10" // $ANTLR start "T__11" private void mT__11() { try { int _type = T__11; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:8:9: ( '%' ) // BuildOptions\\ProfileGrammar.g3:8:9: '%' { Match('%'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__11" // $ANTLR start "T__12" private void mT__12() { try { int _type = T__12; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:9:9: ( '(' ) // BuildOptions\\ProfileGrammar.g3:9:9: '(' { Match('('); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__12" // $ANTLR start "T__13" private void mT__13() { try { int _type = T__13; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:10:9: ( ')' ) // BuildOptions\\ProfileGrammar.g3:10:9: ')' { Match(')'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__13" // $ANTLR start "T__14" private void mT__14() { try { int _type = T__14; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:11:9: ( '*' ) // BuildOptions\\ProfileGrammar.g3:11:9: '*' { Match('*'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__14" // $ANTLR start "T__15" private void mT__15() { try { int _type = T__15; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:12:9: ( '/' ) // BuildOptions\\ProfileGrammar.g3:12:9: '/' { Match('/'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__15" // $ANTLR start "T__16" private void mT__16() { try { int _type = T__16; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:13:9: ( '+' ) // BuildOptions\\ProfileGrammar.g3:13:9: '+' { Match('+'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__16" // $ANTLR start "T__17" private void mT__17() { try { int _type = T__17; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:14:9: ( '=' ) // BuildOptions\\ProfileGrammar.g3:14:9: '=' { Match('='); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__17" // $ANTLR start "ID" private void mID() { try { int _type = ID; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:88:9: ( ( 'a' .. 'z' | 'A' .. 'Z' )+ ) // BuildOptions\\ProfileGrammar.g3:88:9: ( 'a' .. 'z' | 'A' .. 'Z' )+ { // BuildOptions\\ProfileGrammar.g3:88:9: ( 'a' .. 'z' | 'A' .. 'Z' )+ int cnt1=0; for ( ; ; ) { int alt1=2; int LA1_0 = input.LA(1); if ( ((LA1_0>='A' && LA1_0<='Z')||(LA1_0>='a' && LA1_0<='z')) ) { alt1=1; } switch ( alt1 ) { case 1: // BuildOptions\\ProfileGrammar.g3: { input.Consume(); } break; default: if ( cnt1 >= 1 ) goto loop1; EarlyExitException eee1 = new EarlyExitException( 1, input ); throw eee1; } cnt1++; } loop1: ; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "ID" // $ANTLR start "INT" private void mINT() { try { int _type = INT; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:91:9: ( ( '0' .. '9' )+ ) // BuildOptions\\ProfileGrammar.g3:91:9: ( '0' .. '9' )+ { // BuildOptions\\ProfileGrammar.g3:91:9: ( '0' .. '9' )+ int cnt2=0; for ( ; ; ) { int alt2=2; int LA2_0 = input.LA(1); if ( ((LA2_0>='0' && LA2_0<='9')) ) { alt2=1; } switch ( alt2 ) { case 1: // BuildOptions\\ProfileGrammar.g3: { input.Consume(); } break; default: if ( cnt2 >= 1 ) goto loop2; EarlyExitException eee2 = new EarlyExitException( 2, input ); throw eee2; } cnt2++; } loop2: ; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "INT" // $ANTLR start "NEWLINE" private void mNEWLINE() { try { int _type = NEWLINE; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:95:7: ( ( '\\r' )? '\\n' ) // BuildOptions\\ProfileGrammar.g3:95:7: ( '\\r' )? '\\n' { // BuildOptions\\ProfileGrammar.g3:95:7: ( '\\r' )? int alt3=2; int LA3_0 = input.LA(1); if ( (LA3_0=='\r') ) { alt3=1; } switch ( alt3 ) { case 1: // BuildOptions\\ProfileGrammar.g3:95:0: '\\r' { Match('\r'); } break; } Match('\n'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "NEWLINE" // $ANTLR start "WS" private void mWS() { try { int _type = WS; int _channel = DefaultTokenChannel; // BuildOptions\\ProfileGrammar.g3:98:9: ( ( ' ' | '\\t' )+ ) // BuildOptions\\ProfileGrammar.g3:98:9: ( ' ' | '\\t' )+ { // BuildOptions\\ProfileGrammar.g3:98:9: ( ' ' | '\\t' )+ int cnt4=0; for ( ; ; ) { int alt4=2; int LA4_0 = input.LA(1); if ( (LA4_0=='\t'||LA4_0==' ') ) { alt4=1; } switch ( alt4 ) { case 1: // BuildOptions\\ProfileGrammar.g3: { input.Consume(); } break; default: if ( cnt4 >= 1 ) goto loop4; EarlyExitException eee4 = new EarlyExitException( 4, input ); throw eee4; } cnt4++; } loop4: ; Skip(); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "WS" public override void mTokens() { // BuildOptions\\ProfileGrammar.g3:1:10: ( T__10 | T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | ID | INT | NEWLINE | WS ) int alt5=12; switch ( input.LA(1) ) { case '-': { alt5=1; } break; case '%': { alt5=2; } break; case '(': { alt5=3; } break; case ')': { alt5=4; } break; case '*': { alt5=5; } break; case '/': { alt5=6; } break; case '+': { alt5=7; } break; case '=': { alt5=8; } break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { alt5=9; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { alt5=10; } break; case '\n': case '\r': { alt5=11; } break; case '\t': case ' ': { alt5=12; } break; default: { NoViableAltException nvae = new NoViableAltException("", 5, 0, input); throw nvae; } } switch ( alt5 ) { case 1: // BuildOptions\\ProfileGrammar.g3:1:10: T__10 { mT__10(); } break; case 2: // BuildOptions\\ProfileGrammar.g3:1:16: T__11 { mT__11(); } break; case 3: // BuildOptions\\ProfileGrammar.g3:1:22: T__12 { mT__12(); } break; case 4: // BuildOptions\\ProfileGrammar.g3:1:28: T__13 { mT__13(); } break; case 5: // BuildOptions\\ProfileGrammar.g3:1:34: T__14 { mT__14(); } break; case 6: // BuildOptions\\ProfileGrammar.g3:1:40: T__15 { mT__15(); } break; case 7: // BuildOptions\\ProfileGrammar.g3:1:46: T__16 { mT__16(); } break; case 8: // BuildOptions\\ProfileGrammar.g3:1:52: T__17 { mT__17(); } break; case 9: // BuildOptions\\ProfileGrammar.g3:1:58: ID { mID(); } break; case 10: // BuildOptions\\ProfileGrammar.g3:1:61: INT { mINT(); } break; case 11: // BuildOptions\\ProfileGrammar.g3:1:65: NEWLINE { mNEWLINE(); } break; case 12: // BuildOptions\\ProfileGrammar.g3:1:73: WS { mWS(); } break; } } #region DFA protected override void InitDFAs() { base.InitDFAs(); } #endregion }
using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Security; using System.Security.Permissions; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media.Animation; using System.Windows.Threading; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows { /// <summary> /// ContentElement Class is a DependencyObject with IFE - input, focus, and events /// </summary> /// <ExternalAPI/> public partial class ContentElement : DependencyObject, IInputElement, IAnimatable { #region Construction /// <summary> /// Static Constructor for ContentElement /// </summary> /// <SecurityNote> /// Critical: This hooks up a bunch of thunks which are all critical since they /// can be used to spoof input /// TreatAsSafe: Since it does not expose the thunks /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] static ContentElement() { UIElement.RegisterEvents(typeof(ContentElement)); RegisterProperties(); UIElement.IsFocusedPropertyKey.OverrideMetadata( typeof(ContentElement), new PropertyMetadata( BooleanBoxes.FalseBox, // default value new PropertyChangedCallback(IsFocused_Changed))); } #endregion Construction #region DependencyObject #endregion /// <summary> /// Helper, gives the UIParent under control of which /// the OnMeasure or OnArrange are currently called. /// This may be implemented as a tree walk up until /// LayoutElement is found. /// </summary> internal DependencyObject GetUIParent() { return GetUIParent(false); } internal DependencyObject GetUIParent(bool continuePastVisualTree) { DependencyObject e = null; // Try to find a UIElement parent in the visual ancestry. e = InputElement.GetContainingInputElement(_parent) as DependencyObject; // If there was no InputElement parent in the visual ancestry, // check along the logical branch. if(e == null && continuePastVisualTree) { DependencyObject doParent = GetUIParentCore(); e = InputElement.GetContainingInputElement(doParent) as DependencyObject; } return e; } /// <summary> /// Called to get the UI parent of this element when there is /// no visual parent. /// </summary> /// <returns> /// Returns a non-null value when some framework implementation /// of this method has a non-visual parent connection, /// </returns> protected virtual internal DependencyObject GetUIParentCore() { return null; } internal DependencyObject Parent { get { return _parent; } } /// <summary> /// OnContentParentChanged is called when the parent of the content element is changed. /// </summary> /// <param name="oldParent">Old parent or null if the content element did not have a parent before.</param> [FriendAccessAllowed] // Built into Core, also used by Framework. internal virtual void OnContentParentChanged(DependencyObject oldParent) { SynchronizeReverseInheritPropertyFlags(oldParent, true); } #region Automation /// <summary> /// Called by the Automation infrastructure when AutomationPeer /// is requested for this element. The element can return null or /// the instance of AutomationPeer-derived clas, if it supports UI Automation /// </summary> protected virtual AutomationPeer OnCreateAutomationPeer() { return null; } /// <summary> /// Called by the Automation infrastructure or Control author /// to make sure the AutomationPeer is created. The element may /// create AP or return null, depending on OnCreateAutomationPeer override. /// </summary> internal AutomationPeer CreateAutomationPeer() { VerifyAccess(); //this will ensure the AP is created in the right context AutomationPeer ap = null; if (HasAutomationPeer) { ap = AutomationPeerField.GetValue(this); } else { ap = OnCreateAutomationPeer(); if (ap != null) { AutomationPeerField.SetValue(this, ap); HasAutomationPeer = true; } } return ap; } /// <summary> /// Returns AutomationPeer if one exists. /// The AutomationPeer may not exist if not yet created by Automation infrastructure /// or if this element is not supposed to have one. /// </summary> internal AutomationPeer GetAutomationPeer() { VerifyAccess(); if (HasAutomationPeer) return AutomationPeerField.GetValue(this); return null; } // If this element is currently listening to synchronized input, add a pre-opportunity handler to keep track of event routed through this element. internal void AddSynchronizedInputPreOpportunityHandler(EventRoute route, RoutedEventArgs args) { if (InputManager.IsSynchronizedInput) { if (SynchronizedInputHelper.IsListening(this, args)) { RoutedEventHandler eventHandler = new RoutedEventHandler(this.SynchronizedInputPreOpportunityHandler); SynchronizedInputHelper.AddHandlerToRoute(this, route, eventHandler, false); } } } // If this element is currently listening to synchronized input, add a handler to post process the synchronized input otherwise // add a synchronized input pre-opportunity handler from parent if parent is listening. internal void AddSynchronizedInputPostOpportunityHandler(EventRoute route, RoutedEventArgs args) { if (InputManager.IsSynchronizedInput) { if (SynchronizedInputHelper.IsListening(this, args)) { RoutedEventHandler eventHandler = new RoutedEventHandler(this.SynchronizedInputPostOpportunityHandler); SynchronizedInputHelper.AddHandlerToRoute(this, route, eventHandler, true); } else { // Add a preview handler from the parent. SynchronizedInputHelper.AddParentPreOpportunityHandler(this, route, args); } } } // This event handler to be called before all the class & instance handlers for this element. internal void SynchronizedInputPreOpportunityHandler(object sender, RoutedEventArgs args) { if (!args.Handled) { SynchronizedInputHelper.PreOpportunityHandler(sender, args); } } // This event handler to be called after class & instance handlers for this element. internal void SynchronizedInputPostOpportunityHandler(object sender, RoutedEventArgs args) { if (args.Handled && (InputManager.SynchronizedInputState == SynchronizedInputStates.HadOpportunity)) { SynchronizedInputHelper.PostOpportunityHandler(sender, args); } } // Called by automation peer, when called this element will be the listening element for synchronized input. internal bool StartListeningSynchronizedInput(SynchronizedInputType inputType) { if (InputManager.IsSynchronizedInput) { return false; } else { InputManager.StartListeningSynchronizedInput(this, inputType); return true; } } // When called, input processing will return to normal mode. internal void CancelSynchronizedInput() { InputManager.CancelSynchronizedInput(); } #endregion Automation #region Input /// <summary> /// A property indicating if the mouse is over this element or not. /// </summary> public bool IsMouseDirectlyOver { get { // We do not return the cached value of reverse-inherited seed properties. // // The cached value is only used internally to detect a "change". // // More Info: // The act of invalidating the seed property of a reverse-inherited property // on the first side of the path causes the invalidation of the // reverse-inherited properties on both sides. The input system has not yet // invalidated the seed property on the second side, so its cached value can // be incorrect. // return IsMouseDirectlyOver_ComputeValue(); } } private bool IsMouseDirectlyOver_ComputeValue() { return (Mouse.DirectlyOver == this); } /// <summary> /// Asynchronously re-evaluate the reverse-inherited properties. /// </summary> [FriendAccessAllowed] internal void SynchronizeReverseInheritPropertyFlags(DependencyObject oldParent, bool isCoreParent) { if(IsKeyboardFocusWithin) { Keyboard.PrimaryDevice.ReevaluateFocusAsync(this, oldParent, isCoreParent); } // Reevelauate the stylus properties first to guarentee that our property change // notifications fire before mouse properties. if(IsStylusOver) { StylusLogic.CurrentStylusLogicReevaluateStylusOver(this, oldParent, isCoreParent); } if(IsStylusCaptureWithin) { StylusLogic.CurrentStylusLogicReevaluateCapture(this, oldParent, isCoreParent); } if(IsMouseOver) { Mouse.PrimaryDevice.ReevaluateMouseOver(this, oldParent, isCoreParent); } if(IsMouseCaptureWithin) { Mouse.PrimaryDevice.ReevaluateCapture(this, oldParent, isCoreParent); } if (AreAnyTouchesOver) { TouchDevice.ReevaluateDirectlyOver(this, oldParent, isCoreParent); } if (AreAnyTouchesCapturedWithin) { TouchDevice.ReevaluateCapturedWithin(this, oldParent, isCoreParent); } } /// <summary> /// BlockReverseInheritance method when overriden stops reverseInheritProperties from updating their parent level properties. /// </summary> internal virtual bool BlockReverseInheritance() { return false; } /// <summary> /// A property indicating if the mouse is over this element or not. /// </summary> public bool IsMouseOver { get { return ReadFlag(CoreFlags.IsMouseOverCache); } } /// <summary> /// A property indicating if the stylus is over this element or not. /// </summary> public bool IsStylusOver { get { return ReadFlag(CoreFlags.IsStylusOverCache); } } /// <summary> /// Indicates if Keyboard Focus is anywhere /// within in the subtree starting at the /// current instance /// </summary> public bool IsKeyboardFocusWithin { get { return ReadFlag(CoreFlags.IsKeyboardFocusWithinCache); } } /// <summary> /// A property indicating if the mouse is captured to this element or not. /// </summary> public bool IsMouseCaptured { get { return (bool) GetValue(IsMouseCapturedProperty); } } /// <summary> /// Captures the mouse to this element. /// </summary> public bool CaptureMouse() { return Mouse.Capture(this); } /// <summary> /// Releases the mouse capture. /// </summary> public void ReleaseMouseCapture() { Mouse.Capture(null); } /// <summary> /// Indicates if mouse capture is anywhere within in the subtree /// starting at the current instance /// </summary> public bool IsMouseCaptureWithin { get { return ReadFlag(CoreFlags.IsMouseCaptureWithinCache); } } /// <summary> /// A property indicating if the stylus is over this element or not. /// </summary> public bool IsStylusDirectlyOver { get { // We do not return the cached value of reverse-inherited seed properties. // // The cached value is only used internally to detect a "change". // // More Info: // The act of invalidating the seed property of a reverse-inherited property // on the first side of the path causes the invalidation of the // reverse-inherited properties on both sides. The input system has not yet // invalidated the seed property on the second side, so its cached value can // be incorrect. // return IsStylusDirectlyOver_ComputeValue(); } } private bool IsStylusDirectlyOver_ComputeValue() { return (Stylus.DirectlyOver == this); } /// <summary> /// A property indicating if the stylus is captured to this element or not. /// </summary> public bool IsStylusCaptured { get { return (bool) GetValue(IsStylusCapturedProperty); } } /// <summary> /// Captures the stylus to this element. /// </summary> public bool CaptureStylus() { return Stylus.Capture(this); } /// <summary> /// Releases the stylus capture. /// </summary> public void ReleaseStylusCapture() { Stylus.Capture(null); } /// <summary> /// Indicates if stylus capture is anywhere within in the subtree /// starting at the current instance /// </summary> public bool IsStylusCaptureWithin { get { return ReadFlag(CoreFlags.IsStylusCaptureWithinCache); } } /// <summary> /// A property indicating if the keyboard is focused on this /// element or not. /// </summary> public bool IsKeyboardFocused { get { // We do not return the cached value of reverse-inherited seed properties. // // The cached value is only used internally to detect a "change". // // More Info: // The act of invalidating the seed property of a reverse-inherited property // on the first side of the path causes the invalidation of the // reverse-inherited properties on both sides. The input system has not yet // invalidated the seed property on the second side, so its cached value can // be incorrect. // return IsKeyboardFocused_ComputeValue(); } } private bool IsKeyboardFocused_ComputeValue() { return (Keyboard.FocusedElement == this); } /// <summary> /// Focuses the keyboard on this element. /// </summary> public bool Focus() { return Keyboard.Focus(this) == this; } /// <summary> /// Request to move the focus from this element to another element /// </summary> /// <param name="request">Determine how to move the focus</param> /// <returns> Returns true if focus is moved successfully. Returns false if there is no next element</returns> public virtual bool MoveFocus(TraversalRequest request) { return false; } /// <summary> /// Request to predict the element that should receive focus relative to this element for a /// given direction, without actually moving focus to it. /// </summary> /// <param name="direction">The direction for which focus should be predicted</param> /// <returns> /// Returns the next element that focus should move to for a given FocusNavigationDirection. /// Returns null if focus cannot be moved relative to this element. /// </returns> public virtual DependencyObject PredictFocus(FocusNavigationDirection direction) { return null; } /// <summary> /// GotFocus event /// </summary> public static readonly RoutedEvent GotFocusEvent = FocusManager.GotFocusEvent.AddOwner(typeof(ContentElement)); /// <summary> /// An event announcing that IsFocused changed to true. /// </summary> public event RoutedEventHandler GotFocus { add { AddHandler(GotFocusEvent, value); } remove { RemoveHandler(GotFocusEvent, value); } } /// <summary> /// LostFocus event /// </summary> public static readonly RoutedEvent LostFocusEvent = FocusManager.LostFocusEvent.AddOwner(typeof(ContentElement)); /// <summary> /// An event announcing that IsFocused changed to false. /// </summary> public event RoutedEventHandler LostFocus { add { AddHandler(LostFocusEvent, value); } remove { RemoveHandler(LostFocusEvent, value); } } /// <summary> /// The DependencyProperty for IsFocused. /// Flags: None /// Read-Only: true /// </summary> public static readonly DependencyProperty IsFocusedProperty = UIElement.IsFocusedProperty.AddOwner( typeof(ContentElement)); private static void IsFocused_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { ContentElement ce = ((ContentElement) d); if ((bool) e.NewValue) { ce.OnGotFocus(new RoutedEventArgs(GotFocusEvent, ce)); } else { ce.OnLostFocus(new RoutedEventArgs(LostFocusEvent, ce)); } } /// <summary> /// This method is invoked when the IsFocused property changes to true /// </summary> /// <param name="e">RoutedEventArgs</param> protected virtual void OnGotFocus(RoutedEventArgs e) { RaiseEvent(e); } /// <summary> /// This method is invoked when the IsFocused property changes to false /// </summary> /// <param name="e">RoutedEventArgs</param> protected virtual void OnLostFocus(RoutedEventArgs e) { RaiseEvent(e); } /// <summary> /// Gettor for IsFocused Property /// </summary> public bool IsFocused { get { return (bool) GetValue(IsFocusedProperty); } } /// <summary> /// The DependencyProperty for the IsEnabled property. /// </summary> public static readonly DependencyProperty IsEnabledProperty = UIElement.IsEnabledProperty.AddOwner( typeof(ContentElement), new UIPropertyMetadata( BooleanBoxes.TrueBox, // default value new PropertyChangedCallback(OnIsEnabledChanged), new CoerceValueCallback(CoerceIsEnabled))); /// <summary> /// A property indicating if this element is enabled or not. /// </summary> public bool IsEnabled { get { return (bool) GetValue(IsEnabledProperty); } set { SetValue(IsEnabledProperty, BooleanBoxes.Box(value)); } } /// <summary> /// IsEnabledChanged event /// </summary> public event DependencyPropertyChangedEventHandler IsEnabledChanged { add { EventHandlersStoreAdd(UIElement.IsEnabledChangedKey, value); } remove { EventHandlersStoreRemove(UIElement.IsEnabledChangedKey, value); } } /// <summary> /// Fetches the value that IsEnabled should be coerced to. /// </summary> /// <remarks> /// This method is virtual is so that controls derived from UIElement /// can combine additional requirements into the coersion logic. /// <P/> /// It is important for anyone overriding this property to also /// call CoerceValue when any of their dependencies change. /// </remarks> protected virtual bool IsEnabledCore { get { // As of 1/25/2006, the following controls override this method: // Hyperlink.IsEnabledCore: CanExecute return true; } } private static object CoerceIsEnabled(DependencyObject d, object value) { ContentElement ce = (ContentElement) d; // We must be false if our parent is false, but we can be // either true or false if our parent is true. // // Another way of saying this is that we can only be true // if our parent is true, but we can always be false. if((bool) value) { // Use the "logical" parent. This is different that UIElement, which // uses the visual parent. But the "content parent" is not a complete // tree description (for instance, we don't track "content children"), // so the best we can do is use the logical tree for ContentElements. // // Note: we assume the "logical" parent of a ContentElement is either // a UIElement or ContentElement. We explicitly assume that there // is never a raw Visual as the parent. DependencyObject parent = ce.GetUIParentCore(); if(parent == null || (bool)parent.GetValue(IsEnabledProperty)) { return BooleanBoxes.Box(ce.IsEnabledCore); } else { return BooleanBoxes.FalseBox; } } else { return BooleanBoxes.FalseBox; } } private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ContentElement ce = (ContentElement)d; // Raise the public changed event. ce.RaiseDependencyPropertyChanged(UIElement.IsEnabledChangedKey, e); // Invalidate the children so that they will inherit the new value. ce.InvalidateForceInheritPropertyOnChildren(e.Property); // The input manager needs to re-hittest because something changed // that is involved in the hit-testing we do, so a different result // could be returned. InputManager.SafeCurrentNotifyHitTestInvalidated(); } //********************************************************************* #region Focusable Property //********************************************************************* /// <summary> /// The DependencyProperty for the Focusable property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty FocusableProperty = UIElement.FocusableProperty.AddOwner( typeof(ContentElement), new UIPropertyMetadata( BooleanBoxes.FalseBox, // default value new PropertyChangedCallback(OnFocusableChanged))); /// <summary> /// Gettor and Settor for Focusable Property /// </summary> public bool Focusable { get { return (bool) GetValue(FocusableProperty); } set { SetValue(FocusableProperty, BooleanBoxes.Box(value)); } } /// <summary> /// FocusableChanged event /// </summary> public event DependencyPropertyChangedEventHandler FocusableChanged { add {EventHandlersStoreAdd(UIElement.FocusableChangedKey, value);} remove {EventHandlersStoreRemove(UIElement.FocusableChangedKey, value);} } private static void OnFocusableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ContentElement ce = (ContentElement) d; // Raise the public changed event. ce.RaiseDependencyPropertyChanged(UIElement.FocusableChangedKey, e); } //********************************************************************* #endregion Focusable Property //********************************************************************* /// <summary> /// A property indicating if the inptu method is enabled. /// </summary> public bool IsInputMethodEnabled { get { return (bool) GetValue(InputMethod.IsInputMethodEnabledProperty); } } #endregion Input #region Operations private void RaiseMouseButtonEvent(EventPrivateKey key, MouseButtonEventArgs e) { EventHandlersStore store = EventHandlersStore; if (store != null) { Delegate handler = store.Get(key); if (handler != null) { ((MouseButtonEventHandler)handler)(this, e); } } } // Helper method to retrieve and fire Clr Event handlers for DependencyPropertyChanged event private void RaiseDependencyPropertyChanged(EventPrivateKey key, DependencyPropertyChangedEventArgs args) { EventHandlersStore store = EventHandlersStore; if (store != null) { Delegate handler = store.Get(key); if (handler != null) { ((DependencyPropertyChangedEventHandler)handler)(this, args); } } } #endregion Operations #region AllowDrop /// <summary> /// The DependencyProperty for the AllowDrop property. /// </summary> public static readonly DependencyProperty AllowDropProperty = UIElement.AllowDropProperty.AddOwner( typeof(ContentElement), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// A dependency property that allows the drop object as DragDrop target. /// </summary> public bool AllowDrop { get { return (bool) GetValue(AllowDropProperty); } set { SetValue(AllowDropProperty, BooleanBoxes.Box(value)); } } #endregion AllowDrop #region ForceInherit property support // This has to be virtual, since there is no concept of "core" content children, // so we have no choice by to rely on FrameworkContentElement to use logical // children instead. internal virtual void InvalidateForceInheritPropertyOnChildren(DependencyProperty property) { } #endregion #region Touch /// <summary> /// A property indicating if any touch devices are over this element or not. /// </summary> public bool AreAnyTouchesOver { get { return ReadFlag(CoreFlags.TouchesOverCache); } } /// <summary> /// A property indicating if any touch devices are directly over this element or not. /// </summary> public bool AreAnyTouchesDirectlyOver { get { return (bool)GetValue(AreAnyTouchesDirectlyOverProperty); } } /// <summary> /// A property indicating if any touch devices are captured to elements in this subtree. /// </summary> public bool AreAnyTouchesCapturedWithin { get { return ReadFlag(CoreFlags.TouchesCapturedWithinCache); } } /// <summary> /// A property indicating if any touch devices are captured to this element. /// </summary> public bool AreAnyTouchesCaptured { get { return (bool)GetValue(AreAnyTouchesCapturedProperty); } } /// <summary> /// Captures the specified device to this element. /// </summary> /// <param name="touchDevice">The touch device to capture.</param> /// <returns>True if capture was taken.</returns> public bool CaptureTouch(TouchDevice touchDevice) { if (touchDevice == null) { throw new ArgumentNullException("touchDevice"); } return touchDevice.Capture(this); } /// <summary> /// Releases capture from the specified touch device. /// </summary> /// <param name="touchDevice">The device that is captured to this element.</param> /// <returns>true if capture was released, false otherwise.</returns> public bool ReleaseTouchCapture(TouchDevice touchDevice) { if (touchDevice == null) { throw new ArgumentNullException("touchDevice"); } if (touchDevice.Captured == this) { touchDevice.Capture(null); return true; } else { return false; } } /// <summary> /// Releases capture on any touch devices captured to this element. /// </summary> public void ReleaseAllTouchCaptures() { TouchDevice.ReleaseAllCaptures(this); } /// <summary> /// The touch devices captured to this element. /// </summary> public IEnumerable<TouchDevice> TouchesCaptured { get { return TouchDevice.GetCapturedTouches(this, /* includeWithin = */ false); } } /// <summary> /// The touch devices captured to this element and any elements in the subtree. /// </summary> public IEnumerable<TouchDevice> TouchesCapturedWithin { get { return TouchDevice.GetCapturedTouches(this, /* includeWithin = */ true); } } /// <summary> /// The touch devices which are over this element and any elements in the subtree. /// This is particularly relevant to elements which dont take capture (like Label). /// </summary> public IEnumerable<TouchDevice> TouchesOver { get { return TouchDevice.GetTouchesOver(this, /* includeWithin = */ true); } } /// <summary> /// The touch devices which are directly over this element. /// This is particularly relevant to elements which dont take capture (like Label). /// </summary> public IEnumerable<TouchDevice> TouchesDirectlyOver { get { return TouchDevice.GetTouchesOver(this, /* includeWithin = */ false); } } #endregion internal bool HasAutomationPeer { get { return ReadFlag(CoreFlags.HasAutomationPeer); } set { WriteFlag(CoreFlags.HasAutomationPeer, value); } } #region Data internal DependencyObject _parent; ///// ATTACHED STORAGE ///// internal static readonly UncommonField<EventHandlersStore> EventHandlersStoreField = UIElement.EventHandlersStoreField; internal static readonly UncommonField<InputBindingCollection> InputBindingCollectionField = UIElement.InputBindingCollectionField; internal static readonly UncommonField<CommandBindingCollection> CommandBindingCollectionField = UIElement.CommandBindingCollectionField; private static readonly UncommonField<AutomationPeer> AutomationPeerField = new UncommonField<AutomationPeer>(); // Caches the ContentElement's DependencyObjectType private static DependencyObjectType ContentElementType = DependencyObjectType.FromSystemTypeInternal(typeof(ContentElement)); #endregion Data } }
//--------------------------------------------------------------------------- // // <copyright file="EventManager.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Class to manage UIAutomation events and how they relate to winevents // // // History: // 08/25/2004 : preid Created //--------------------------------------------------------------------------- using System; using System.Text; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Runtime.InteropServices; using System.ComponentModel; using System.Collections; using Accessibility; using System.Windows; using System.Windows.Input; using System.Globalization; using MS.Win32; namespace MS.Internal.AutomationProxies { // Class to manage UIAutomation events and how they relate to winevents static class EventManager { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors #endregion //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal static void DispatchEvent(ProxySimple el, IntPtr hwnd, int eventId, object idProp, int idObject) { // This logic uses a hastables in order to get to a delegate that will raise the correct Automation event // that may be a property change event a Automation event or a structure changed event. // There are three hashtables one for each idObject we support. Depending on the idObject that gets // passed in we access one of these hashtables with a key of an automation identifier and then retrieve // the data which ia a delegate of type RasieEvent. This delegate is called to raise the correct type of event. RaiseEvent raiseEvent = null; switch (idObject) { case NativeMethods.OBJID_WINDOW: lock (_classLock) { if (_objectIdWindow == null) InitObjectIdWindow(); } raiseEvent = (RaiseEvent)_objectIdWindow[idProp]; break; case NativeMethods.OBJID_CLIENT: lock (_classLock) { if (_objectIdClient == null) InitObjectIdClient(); } raiseEvent = (RaiseEvent)_objectIdClient[idProp]; break; case NativeMethods.OBJID_VSCROLL: case NativeMethods.OBJID_HSCROLL: lock (_classLock) { if (_objectIdScroll == null) InitObjectIdScroll(); } raiseEvent = (RaiseEvent)_objectIdScroll[idProp]; break; case NativeMethods.OBJID_CARET: lock (_classLock) { if (_objectIdCaret == null) InitObjectIdCaret(); } raiseEvent = (RaiseEvent)_objectIdCaret[idProp]; break; case NativeMethods.OBJID_SYSMENU: case NativeMethods.OBJID_MENU: lock (_classLock) { if (_objectIdMenu == null) InitObjectIdMenu(); } raiseEvent = (RaiseEvent)_objectIdMenu[idProp]; break; default: // Commented out to remove annoying asserts temporarily. // (See work item PS1254940.) //System.Diagnostics.Debug.Assert(false, "Unexpected idObject " + idObject); return; } if (raiseEvent != null) { raiseEvent(el, hwnd, eventId); } else { // If there is no delegate then we need to handle this property genericly by just getting the property value // and raising the a property changed event. AutomationProperty property = idProp as AutomationProperty; if (property == null) { System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Unexpected idProp {0} for idOject 0x{1:x8} on element {2} for event {3}", idProp, idObject, el, eventId)); return; } object propertyValue = ((IRawElementProviderSimple)el).GetPropertyValue(property.Id); RaisePropertyChangedEvent(el, property, propertyValue); } } #endregion //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods private static void HandleIsReadOnlyProperty(ProxySimple el, IntPtr hwnd, int eventId) { // Special call for the ReadOnly Proxperty. If a Windows, becomes // enabled/disabled, all of its non hwnd children should become // change the read only state. if (eventId == NativeMethods.EventObjectStateChange) { bool fIsReadOnly = SafeNativeMethods.IsWindowEnabled(hwnd); el.RecursiveRaiseEvents(ValuePattern.IsReadOnlyProperty, new AutomationPropertyChangedEventArgs(ValuePattern.IsReadOnlyProperty, null, fIsReadOnly)); } } private static void HandleStructureChangedEventWindow(ProxySimple el, IntPtr hwnd, int eventId) { if (eventId == NativeMethods.EventObjectReorder) { AutomationInteropProvider.RaiseStructureChangedEvent( el, new StructureChangedEventArgs( StructureChangeType.ChildrenReordered, el.MakeRuntimeId() ) ); } } private static void HandleCanMinimizeProperty(ProxySimple el, IntPtr hwnd, int eventId) { if (eventId == NativeMethods.EventObjectLocationChange) { WindowVisualState wvs = GetWindowVisualState(hwnd); bool canMinimize = wvs != WindowVisualState.Minimized; RaisePropertyChangedEvent(el, WindowPattern.CanMinimizeProperty, canMinimize); } } private static void HandleCanMaximizeProperty(ProxySimple el, IntPtr hwnd, int eventId) { if (eventId == NativeMethods.EventObjectLocationChange) { WindowVisualState wvs = GetWindowVisualState(hwnd); bool canMaximize = wvs != WindowVisualState.Maximized; RaisePropertyChangedEvent(el, WindowPattern.CanMaximizeProperty, canMaximize); } } private static void HandleValueProperty(ProxySimple el, IntPtr hwnd, int eventId) { IValueProvider value = el.GetPatternProvider(ValuePattern.Pattern) as IValueProvider; if (value == null) return; RaisePropertyChangedEvent(el, ValuePattern.ValueProperty, value.Value); } private static void HandleRangeValueProperty(ProxySimple el, IntPtr hwnd, int eventId) { IRangeValueProvider rangeValue = el.GetPatternProvider(RangeValuePattern.Pattern) as IRangeValueProvider; if (rangeValue == null) return; RaisePropertyChangedEvent(el, RangeValuePattern.ValueProperty, rangeValue.Value); } private static void HandleIsSelectedProperty(ProxySimple el, IntPtr hwnd, int eventId) { ISelectionItemProvider selectionItem = el.GetPatternProvider(SelectionItemPattern.Pattern) as ISelectionItemProvider; if (selectionItem == null) return; RaisePropertyChangedEvent(el, SelectionItemPattern.IsSelectedProperty, selectionItem.IsSelected); } private static void HandleExpandCollapseStateProperty(ProxySimple el, IntPtr hwnd, int eventId) { IExpandCollapseProvider expandCollapse = el.GetPatternProvider(ExpandCollapsePattern.Pattern) as IExpandCollapseProvider; if (expandCollapse == null) return; RaisePropertyChangedEvent(el, ExpandCollapsePattern.ExpandCollapseStateProperty, expandCollapse.ExpandCollapseState); } private static void HandleColumnCountProperty(ProxySimple el, IntPtr hwnd, int eventId) { IGridProvider grid = el.GetPatternProvider(GridPattern.Pattern) as IGridProvider; if (grid == null) return; RaisePropertyChangedEvent(el, GridPattern.ColumnCountProperty, grid.ColumnCount); } private static void HandleRowCountProperty(ProxySimple el, IntPtr hwnd, int eventId) { IGridProvider grid = el.GetPatternProvider(GridPattern.Pattern) as IGridProvider; if (grid == null) return; RaisePropertyChangedEvent(el, GridPattern.RowCountProperty, grid.RowCount); } private static void HandleColumnProperty(ProxySimple el, IntPtr hwnd, int eventId) { IGridItemProvider gridItem = el.GetPatternProvider(GridItemPattern.Pattern) as IGridItemProvider; if (gridItem == null) return; RaisePropertyChangedEvent(el, GridItemPattern.ColumnProperty, gridItem.Column); } private static void HandleRowProperty(ProxySimple el, IntPtr hwnd, int eventId) { IGridItemProvider gridItem = el.GetPatternProvider(GridItemPattern.Pattern) as IGridItemProvider; if (gridItem == null) return; RaisePropertyChangedEvent(el, GridItemPattern.RowProperty, gridItem.Row); } private static void HandleColumnHeadersProperty(ProxySimple el, IntPtr hwnd, int eventId) { ITableProvider table = el.GetPatternProvider(TablePattern.Pattern) as ITableProvider; if (table == null) return; RaisePropertyChangedEvent(el, TablePattern.ColumnHeadersProperty, table.GetColumnHeaders()); } private static void HandleRowHeadersProperty(ProxySimple el, IntPtr hwnd, int eventId) { ITableProvider table = el.GetPatternProvider(TablePattern.Pattern) as ITableProvider; if (table == null) return; RaisePropertyChangedEvent(el, TablePattern.RowHeadersProperty, table.GetRowHeaders()); } private static void HandleIsSelectionRequiredProperty(ProxySimple el, IntPtr hwnd, int eventId) { ISelectionProvider selection = el.GetPatternProvider(SelectionPattern.Pattern) as ISelectionProvider; if (selection == null) return; RaisePropertyChangedEvent(el, SelectionPattern.IsSelectionRequiredProperty, selection.IsSelectionRequired); } private static void HandleVerticalViewSizeProperty(ProxySimple el, IntPtr hwnd, int eventId) { IScrollProvider scroll = el.GetPatternProvider(ScrollPattern.Pattern) as IScrollProvider; if (scroll == null) return; RaisePropertyChangedEvent(el, ScrollPattern.VerticalViewSizeProperty, scroll.VerticalViewSize); } private static void HandleHorizontalViewSizeProperty(ProxySimple el, IntPtr hwnd, int eventId) { IScrollProvider scroll = el.GetPatternProvider(ScrollPattern.Pattern) as IScrollProvider; if (scroll == null) return; RaisePropertyChangedEvent(el, ScrollPattern.HorizontalViewSizeProperty, scroll.HorizontalViewSize); } private static void HandleToggleStateProperty(ProxySimple el, IntPtr hwnd, int eventId) { IToggleProvider toggle = el.GetPatternProvider(TogglePattern.Pattern) as IToggleProvider; if (toggle == null) return; RaisePropertyChangedEvent(el, TogglePattern.ToggleStateProperty, toggle.ToggleState); } private static void HandleInvokedEvent(ProxySimple el, IntPtr hwnd, int eventId) { IInvokeProvider invoke = el.GetPatternProvider(InvokePattern.Pattern) as IInvokeProvider; if (invoke == null) return; if (eventId == NativeMethods.EventObjectInvoke || eventId == NativeMethods.EventObjectStateChange || eventId == NativeMethods.EventObjectSelection && el is ListViewItem) { AutomationInteropProvider.RaiseAutomationEvent(InvokePattern.InvokedEvent, el, new AutomationEventArgs(InvokePattern.InvokedEvent)); } } private static void HandleScrollInvokedEvent(ProxySimple el, IntPtr hwnd, int eventId) { IInvokeProvider invoke = el.GetPatternProvider(InvokePattern.Pattern) as IInvokeProvider; if (invoke == null) return; if (eventId == NativeMethods.EventObjectStateChange) { AutomationInteropProvider.RaiseAutomationEvent(InvokePattern.InvokedEvent, el, new AutomationEventArgs(InvokePattern.InvokedEvent)); } } private static void HandleWindowInvokedEvent(ProxySimple el, IntPtr hwnd, int eventId) { IInvokeProvider invoke = el.GetPatternProvider(InvokePattern.Pattern) as IInvokeProvider; if (invoke == null) return; if (eventId == NativeMethods.EventSystemCaptureEnd ) { AutomationInteropProvider.RaiseAutomationEvent(InvokePattern.InvokedEvent, el, new AutomationEventArgs(InvokePattern.InvokedEvent)); } } private static void HandleMenuItemInvokedEvent(ProxySimple el, IntPtr hwnd, int eventId) { // Skip the check for InvokePattern because el is just a wrapper on a dead element and // GetPatternProvider will fail to return the pattern. Later, if the caller tries to // use this element most properties and methods will throw ElementNotAvailable. if (eventId == NativeMethods.EventObjectInvoke) { AutomationInteropProvider.RaiseAutomationEvent(InvokePattern.InvokedEvent, el, new AutomationEventArgs(InvokePattern.InvokedEvent)); } } private static void HandleElementSelectedEvent(ProxySimple el, IntPtr hwnd, int eventId) { ISelectionItemProvider selProvider = el.GetPatternProvider(SelectionItemPattern.Pattern) as ISelectionItemProvider; if (selProvider == null) return; if (eventId == NativeMethods.EventObjectSelection || eventId == NativeMethods.EventObjectStateChange) { AutomationInteropProvider.RaiseAutomationEvent(SelectionItemPattern.ElementSelectedEvent, el, new AutomationEventArgs(SelectionItemPattern.ElementSelectedEvent)); } } private static void HandleElementAddedToSelectionEvent(ProxySimple el, IntPtr hwnd, int eventId) { ISelectionItemProvider selProvider = el.GetPatternProvider(SelectionItemPattern.Pattern) as ISelectionItemProvider; if (selProvider == null) return; if (eventId == NativeMethods.EventObjectSelectionAdd) { AutomationInteropProvider.RaiseAutomationEvent(SelectionItemPattern.ElementAddedToSelectionEvent, el, new AutomationEventArgs(SelectionItemPattern.ElementAddedToSelectionEvent)); } } private static void HandleElementRemovedFromSelectionEvent(ProxySimple el, IntPtr hwnd, int eventId) { ISelectionItemProvider selProvider = el.GetPatternProvider(SelectionItemPattern.Pattern) as ISelectionItemProvider; if (selProvider == null) return; if (eventId == NativeMethods.EventObjectSelectionRemove) { AutomationInteropProvider.RaiseAutomationEvent(SelectionItemPattern.ElementRemovedFromSelectionEvent, el, new AutomationEventArgs(SelectionItemPattern.ElementRemovedFromSelectionEvent)); } } private static void HandleStructureChangedEventClient(ProxySimple el, IntPtr hwnd, int eventId) { if (eventId == NativeMethods.EventObjectCreate) { AutomationInteropProvider.RaiseStructureChangedEvent (el, new StructureChangedEventArgs (StructureChangeType.ChildAdded, el.MakeRuntimeId())); } else if (eventId == NativeMethods.EventObjectDestroy) { AutomationInteropProvider.RaiseStructureChangedEvent( el, new StructureChangedEventArgs( StructureChangeType.ChildRemoved, el.MakeRuntimeId() ) ); } else if ( eventId == NativeMethods.EventObjectReorder ) { IGridProvider grid = el.GetPatternProvider(GridPattern.Pattern) as IGridProvider; if ( grid == null ) return; AutomationInteropProvider.RaiseStructureChangedEvent( el, new StructureChangedEventArgs( StructureChangeType.ChildrenInvalidated, el.MakeRuntimeId() ) ); } } private static void HandleVerticalScrollPercentProperty(ProxySimple el, IntPtr hwnd, int eventId) { IScrollProvider scroll = el.GetPatternProvider (ScrollPattern.Pattern) as IScrollProvider; if (scroll == null || scroll.VerticalScrollPercent == ScrollPattern.NoScroll) return; RaisePropertyChangedEvent(el, ScrollPattern.VerticalScrollPercentProperty, scroll.VerticalScrollPercent); } private static void HandleHorizontalScrollPercentProperty(ProxySimple el, IntPtr hwnd, int eventId) { IScrollProvider scroll = el.GetPatternProvider (ScrollPattern.Pattern) as IScrollProvider; if (scroll == null || scroll.HorizontalScrollPercent == ScrollPattern.NoScroll) return; RaisePropertyChangedEvent(el, ScrollPattern.HorizontalScrollPercentProperty, scroll.HorizontalScrollPercent); } private static void HandleInvalidatedEvent(ProxySimple el, IntPtr hwnd, int eventId) { AutomationInteropProvider.RaiseAutomationEvent(SelectionPattern.InvalidatedEvent, el, new AutomationEventArgs(SelectionPattern.InvalidatedEvent)); } private static void RaisePropertyChangedEvent(ProxySimple el, AutomationProperty property, object propertyValue) { if (propertyValue != null && propertyValue != AutomationElement.NotSupported) { AutomationInteropProvider.RaiseAutomationPropertyChangedEvent(el, new AutomationPropertyChangedEventArgs(property, null, propertyValue)); } } private static WindowVisualState GetWindowVisualState(IntPtr hwnd) { int style = Misc.GetWindowStyle(hwnd); // How do you return Invisable? if (Misc.IsBitSet(style, NativeMethods.WS_MAXIMIZE)) { return WindowVisualState.Maximized; } else if (Misc.IsBitSet(style, NativeMethods.WS_MINIMIZE)) { return WindowVisualState.Minimized; } else { return WindowVisualState.Normal; } } private static void HandleTextSelectionChangedEvent(ProxySimple el, IntPtr hwnd, int eventId) { ITextProvider textProvider = el.GetPatternProvider(TextPattern.Pattern) as ITextProvider; if (textProvider == null) return; if (eventId == NativeMethods.EventObjectLocationChange) { // We do not want to raise the EventObjectLocationChange when it is caused by a scroll. To do this // store the previous range and compare it to the current range. The range will not change when scrolling. ITextRangeProvider[] currentRanges = textProvider.GetSelection(); ITextRangeProvider currentRange = null; if (currentRanges != null && currentRanges.Length > 0) currentRange = currentRanges[0]; if (hwnd == _hwndLast && currentRange != null) { if (_lastSelection != null && !currentRange.Compare(_lastSelection)) { AutomationInteropProvider.RaiseAutomationEvent(TextPattern.TextSelectionChangedEvent, el, new AutomationEventArgs(TextPattern.TextSelectionChangedEvent)); } } else { AutomationInteropProvider.RaiseAutomationEvent(TextPattern.TextSelectionChangedEvent, el, new AutomationEventArgs(TextPattern.TextSelectionChangedEvent)); } //store the current range and window handle. _hwndLast = hwnd; _lastSelection = currentRange; } else if (eventId == NativeMethods.EventObjectTextSelectionChanged) { AutomationInteropProvider.RaiseAutomationEvent( TextPattern.TextSelectionChangedEvent, el, new AutomationEventArgs(TextPattern.TextSelectionChangedEvent)); } } private static void InitObjectIdWindow() { _objectIdWindow = new Hashtable(7, .1f); _objectIdWindow.Add(ValuePattern.IsReadOnlyProperty, new RaiseEvent(HandleIsReadOnlyProperty)); _objectIdWindow.Add(AutomationElement.StructureChangedEvent, new RaiseEvent(HandleStructureChangedEventWindow)); _objectIdWindow.Add(WindowPattern.CanMaximizeProperty, new RaiseEvent(HandleCanMaximizeProperty)); _objectIdWindow.Add(WindowPattern.CanMinimizeProperty, new RaiseEvent(HandleCanMinimizeProperty)); _objectIdWindow.Add(TogglePattern.ToggleStateProperty, new RaiseEvent(HandleToggleStateProperty)); _objectIdWindow.Add(InvokePattern.InvokedEvent, new RaiseEvent(HandleWindowInvokedEvent)); } private static void InitObjectIdClient() { _objectIdClient = new Hashtable(20, .1f); _objectIdClient.Add(ValuePattern.ValueProperty, new RaiseEvent(HandleValueProperty)); _objectIdClient.Add(RangeValuePattern.ValueProperty, new RaiseEvent(HandleRangeValueProperty)); _objectIdClient.Add(SelectionItemPattern.IsSelectedProperty, new RaiseEvent(HandleIsSelectedProperty)); _objectIdClient.Add(ExpandCollapsePattern.ExpandCollapseStateProperty, new RaiseEvent(HandleExpandCollapseStateProperty)); _objectIdClient.Add(GridPattern.ColumnCountProperty, new RaiseEvent(HandleColumnCountProperty)); _objectIdClient.Add(GridPattern.RowCountProperty, new RaiseEvent(HandleRowCountProperty)); _objectIdClient.Add(GridItemPattern.ColumnProperty, new RaiseEvent(HandleColumnProperty)); _objectIdClient.Add(GridItemPattern.RowProperty, new RaiseEvent(HandleRowProperty)); _objectIdClient.Add(TablePattern.ColumnHeadersProperty, new RaiseEvent(HandleColumnHeadersProperty)); _objectIdClient.Add(TablePattern.RowHeadersProperty, new RaiseEvent(HandleRowHeadersProperty)); _objectIdClient.Add(SelectionPattern.IsSelectionRequiredProperty, new RaiseEvent(HandleIsSelectionRequiredProperty)); _objectIdClient.Add(ScrollPattern.VerticalViewSizeProperty, new RaiseEvent(HandleVerticalViewSizeProperty)); _objectIdClient.Add(ScrollPattern.HorizontalViewSizeProperty, new RaiseEvent(HandleHorizontalViewSizeProperty)); _objectIdClient.Add(InvokePattern.InvokedEvent, new RaiseEvent(HandleInvokedEvent)); _objectIdClient.Add(SelectionItemPattern.ElementSelectedEvent, new RaiseEvent(HandleElementSelectedEvent)); _objectIdClient.Add(SelectionItemPattern.ElementAddedToSelectionEvent, new RaiseEvent(HandleElementAddedToSelectionEvent)); _objectIdClient.Add(SelectionItemPattern.ElementRemovedFromSelectionEvent, new RaiseEvent(HandleElementRemovedFromSelectionEvent)); _objectIdClient.Add(AutomationElement.StructureChangedEvent, new RaiseEvent(HandleStructureChangedEventClient)); _objectIdClient.Add(SelectionPattern.InvalidatedEvent, new RaiseEvent(HandleInvalidatedEvent)); _objectIdClient.Add(TogglePattern.ToggleStateProperty, new RaiseEvent(HandleToggleStateProperty)); _objectIdClient.Add(TextPattern.TextSelectionChangedEvent, new RaiseEvent(HandleTextSelectionChangedEvent)); } private static void InitObjectIdScroll() { _objectIdScroll = new Hashtable(3, .1f); _objectIdScroll.Add(ScrollPattern.VerticalScrollPercentProperty, new RaiseEvent(HandleVerticalScrollPercentProperty)); _objectIdScroll.Add(ScrollPattern.HorizontalScrollPercentProperty, new RaiseEvent(HandleHorizontalScrollPercentProperty)); _objectIdScroll.Add(InvokePattern.InvokedEvent, new RaiseEvent(HandleScrollInvokedEvent)); } private static void InitObjectIdCaret() { _objectIdCaret = new Hashtable(1, .1f); _objectIdCaret.Add(TextPattern.TextSelectionChangedEvent, new RaiseEvent(HandleTextSelectionChangedEvent)); } private static void InitObjectIdMenu() { _objectIdMenu = new Hashtable(1, .1f); _objectIdMenu.Add(InvokePattern.InvokedEvent, new RaiseEvent(HandleMenuItemInvokedEvent)); } #endregion //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private delegate void RaiseEvent (ProxySimple el, IntPtr hwnd, int eventId); private static Hashtable _objectIdWindow; private static Hashtable _objectIdClient; private static Hashtable _objectIdScroll; private static Hashtable _objectIdCaret; private static Hashtable _objectIdMenu; private static object _classLock = new object(); // use lock object vs typeof(class) for perf // The hwndLast and objLast is to allow limited filtering of events. private static IntPtr _hwndLast = IntPtr.Zero; private static ITextRangeProvider _lastSelection = null; #endregion } }
//--------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Contents: The XML Composite font parsing // // Created: 6-11-2003 Tarek Mahmoud Sayed ([....]) // //--------------------------------------------------------------------------- using System; using System.IO; using System.Security; using System.Security.Permissions; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Markup; using System.Xml; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using MS.Internal.TextFormatting; using System.Reflection; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace MS.Internal.FontFace { internal class CompositeFontParser { internal static void VerifyMultiplierOfEm(string propertyName, ref double value) { if (DoubleUtil.IsNaN(value)) { throw new ArgumentException(SR.Get(SRID.PropertyValueCannotBeNaN, propertyName)); } else if (value > Constants.GreatestMutiplierOfEm) { value = Constants.GreatestMutiplierOfEm; } else if (value < -Constants.GreatestMutiplierOfEm) { value = -Constants.GreatestMutiplierOfEm; } } internal static void VerifyPositiveMultiplierOfEm(string propertyName, ref double value) { if (DoubleUtil.IsNaN(value)) { throw new ArgumentException(SR.Get(SRID.PropertyValueCannotBeNaN, propertyName)); } else if (value > Constants.GreatestMutiplierOfEm) { value = Constants.GreatestMutiplierOfEm; } else if (value <= 0) { throw new ArgumentException(SR.Get(SRID.PropertyMustBeGreaterThanZero, propertyName)); } } internal static void VerifyNonNegativeMultiplierOfEm(string propertyName, ref double value) { if (DoubleUtil.IsNaN(value)) { throw new ArgumentException(SR.Get(SRID.PropertyValueCannotBeNaN, propertyName)); } else if (value > Constants.GreatestMutiplierOfEm) { value = Constants.GreatestMutiplierOfEm; } else if (value < 0) { throw new ArgumentException(SR.Get(SRID.PropertyCannotBeNegative, propertyName)); } } private double GetAttributeAsDouble() { object value = null; try { value = _doubleTypeConverter.ConvertFromString( null, // type converter context System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS, GetAttributeValue() ); } catch (NotSupportedException) { FailAttributeValue(); } if (value == null) FailAttributeValue(); return (double)value; } private XmlLanguage GetAttributeAsXmlLanguage() { object value = null; try { value = _xmlLanguageTypeConverter.ConvertFromString( null, // type converter context System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS, GetAttributeValue() ); } catch (NotSupportedException) { FailAttributeValue(); } if (value == null) FailAttributeValue(); return (XmlLanguage)value; } /// <summary> /// Gets the value of the value of the current node which is assumed to be an /// attribute. Checks for markup expressions or escaped braces. /// </summary> private string GetAttributeValue() { string s = _reader.Value; if (string.IsNullOrEmpty(s)) return string.Empty; if (s[0] == '{') { if (s.Length > 1 && s[1] == '}') { s = s.Substring(2); } else { FailAttributeValue(); } } return s; } private const NumberStyles UnsignedDecimalPointStyle = NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingWhite | NumberStyles.AllowDecimalPoint; private const NumberStyles SignedDecimalPointStyle = UnsignedDecimalPointStyle | NumberStyles.AllowLeadingSign; /// <summary> /// Reads the specified composite font file. /// </summary> internal static CompositeFontInfo LoadXml(Stream fileStream) { CompositeFontParser parser = new CompositeFontParser(fileStream); return parser._compositeFontInfo; } /// <summary> /// Constructs the composite font parser and parses the file. /// </summary> /// <param name="fileStream">File stream to parse.</param> private CompositeFontParser(Stream fileStream) { _compositeFontInfo = new CompositeFontInfo(); _namespaceMap = new Hashtable(); _doubleTypeConverter = TypeDescriptor.GetConverter(typeof(double)); _xmlLanguageTypeConverter = new System.Windows.Markup.XmlLanguageConverter(); _reader = CreateXmlReader(fileStream); try { if (IsStartElement(FontFamilyElement, CompositeFontNamespace)) { ParseFontFamilyElement(); } else { FailUnknownElement(); } } catch (XmlException x) { FailNotWellFormed(x); } catch (XmlSyntaxException x) { FailNotWellFormed(x); } catch (FormatException x) { if (_reader.NodeType == XmlNodeType.Attribute) FailAttributeValue(x); else Fail(x.Message, x); } catch (ArgumentException x) { if (_reader.NodeType == XmlNodeType.Attribute) FailAttributeValue(x); else Fail(x.Message, x); } finally { _reader.Close(); _reader = null; } } /// <summary> /// Creates the XML reader for the specified file. /// </summary> private XmlReader CreateXmlReader(Stream fileStream) { XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = true; settings.IgnoreComments = true; settings.IgnoreWhitespace = false; settings.ProhibitDtd = true; XmlReader baseReader = XmlReader.Create(fileStream, settings); return new XmlCompatibilityReader(baseReader, new IsXmlNamespaceSupportedCallback(IsXmlNamespaceSupported)); } /// <summary> /// Determines whether a given XML namespace is "known" (i.e., should always be processed) /// or "unknown" (i.e., should be skipped if declared ignorable). /// </summary> /// <param name="xmlNamespace">XML namespace to look up.</param> /// <param name="newXmlNamespace">Other namespace to map to, if any. Used for versioning. /// This implementation always returns null in this parameter.</param> /// <returns> /// Returns true ("known") for the XAML namespace or the composite font namespace. /// for which a Mapping PI exists. /// </returns> /// <remarks> /// System.String is the only object in a mapped namespace that we can instantiate. However, /// we don't want to ignore any mapped namespaces for compatibility reasons. In general, it's /// better for us to reject valid XAML than to accept invalid XAML. We therefore don't want /// to ignore an element which the XAML parser would not ignore -- the ignored element might /// be invalid. If mapped elements other than System.String are needed in future versions, a /// composite font author can achieve backwards compatibility by conditionalizing mapped /// elements using c:AlternateContent markup. /// </remarks> private bool IsXmlNamespaceSupported(string xmlNamespace, out string newXmlNamespace) { newXmlNamespace = null; return xmlNamespace == CompositeFontNamespace || xmlNamespace == XamlNamespace || IsMappedNamespace(xmlNamespace); } /// <summary> /// Calls MoveToContent and checks whether the reader is positioned on the specified element. /// </summary> /// <remarks> /// We should always call this method instead of calling _reader.IsStartElement directly because /// the latter calls MoveToContent on the underlying reader which means we could fail to parse /// Mapping processing instructions. /// </remarks> private bool IsStartElement(string localName, string namespaceURI) { MoveToContent(); return _reader.IsStartElement(localName, namespaceURI); } /// <summary> /// Same semantics as XmlReader.MoveToContent, but this method processes Mapping processing /// instructions as it advances past them. /// </summary> private XmlNodeType MoveToContent() { bool contentNode = false; do { switch (_reader.NodeType) { case XmlNodeType.CDATA: case XmlNodeType.Element: case XmlNodeType.EndElement: case XmlNodeType.EntityReference: case XmlNodeType.EndEntity: contentNode = true; break; } } while (!contentNode && _reader.Read()); return _reader.NodeType; } #region ProcessingInstructions private bool IsMappedNamespace(string xmlNamespace) { return _namespaceMap.ContainsKey(xmlNamespace); } private bool IsSystemNamespace(string xmlNamespace) { return (xmlNamespace == "clr-namespace:System;assembly=mscorlib"); } #endregion ProcessingInstructions /// <summary> /// Parses the FontFamily element, including its attributes and children, /// and advances to the next sibling element. /// </summary> private void ParseFontFamilyElement() { // Iterate over the attributes. if (_reader.MoveToFirstAttribute()) { do { // Process attributes in the composite font namespace if (IsCompositeFontAttribute()) { string name = _reader.LocalName; if (name == BaselineAttribute) { _compositeFontInfo.Baseline = GetAttributeAsDouble(); } else if (name == LineSpacingAttribute) { _compositeFontInfo.LineSpacing = GetAttributeAsDouble(); } else { FailUnknownAttribute(); } } else if (!IsIgnorableAttribute()) { FailUnknownAttribute(); } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); } // Empty element? if (_reader.IsEmptyElement) { VerifyCompositeFontInfo(); _reader.Read(); return; } // Advance past the start tag. _reader.Read(); // Iterate over children. while (MoveToContent() != XmlNodeType.EndElement) { if (_reader.NodeType == XmlNodeType.Element && _reader.NamespaceURI == CompositeFontNamespace) { bool isEmpty = _reader.IsEmptyElement; // It's an element in the composite font namespace; branch depending on the name. switch (_reader.LocalName) { case FamilyNamesPropertyElement: VerifyNoAttributes(); _reader.Read(); if (!isEmpty) { // Process all child elements. while (MoveToContent() == XmlNodeType.Element) { if (_reader.LocalName == StringElement && IsSystemNamespace(_reader.NamespaceURI)) { // It's a System.String. ParseFamilyNameElement(); } else { // Only System.String is valid in this context. FailUnknownElement(); } } // Advance past the </FontFamily.FamilyNames> end element, or throw // an exception if we're not at an end element. _reader.ReadEndElement(); } break; case FamilyTypefacesPropertyElement: VerifyNoAttributes(); _reader.Read(); if (!isEmpty) { // Process child elements, of which the only one we recognize in this // context is FamilyTypeface. while (IsStartElement(FamilyTypefaceElement, CompositeFontNamespace)) { ParseFamilyTypefaceElement(); } // Advance past the </FontFamily.FamilyTypefaces> end element, or throw // an exception if we're not at an end element. _reader.ReadEndElement(); } break; case FamilyMapsPropertyElement: VerifyNoAttributes(); _reader.Read(); if (!isEmpty) { // Process child elements, of which the only one we recognize in this // context is FontFamilyMap. while (IsStartElement(FamilyMapElement, CompositeFontNamespace)) { ParseFamilyMapElement(); } // Advance past the </FontFamily.FamilyTypefaces> end element, or throw // an exception if we're not at an end element. _reader.ReadEndElement(); } break; default: // It's some other element. FailUnknownElement(); break; } } else { // It's some other content besides an element in the composite font namespace; skip it. _reader.Skip(); } } // We should now have read right up to the </FontFamily> end tag. VerifyCompositeFontInfo(); _reader.ReadEndElement(); } /// <summary> /// Makes sure the current element has no attributes (except ignorable ones). /// </summary> private void VerifyNoAttributes() { if (_reader.MoveToFirstAttribute()) { do { if (!IsIgnorableAttribute()) FailUnknownAttribute(); } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); } } /// <summary> /// Parses the FamilyName element (actually String), including its attributes /// and children, and advances to the next sibling element. /// </summary> private void ParseFamilyNameElement() { XmlLanguage language = null; // Iterate over the attributes. if (_reader.MoveToFirstAttribute()) { do { if (_reader.NamespaceURI == XamlNamespace && _reader.LocalName == KeyAttribute) { language = GetAttributeAsXmlLanguage(); } else if (!IsIgnorableAttribute()) { FailUnknownAttribute(); } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); } // XAML requires x:Key so we should, too. if (language == null) { FailMissingAttribute(LanguageAttribute); } // The family name is the element content. string familyName = _reader.ReadElementString(); if (string.IsNullOrEmpty(familyName)) { FailMissingAttribute(NameAttribute); } _compositeFontInfo.FamilyNames.Add(language, familyName); } /// <summary> /// Parses the FamilyTypeface element, including its attributes and children, /// and advances to the next sibling element. /// </summary> private void ParseFamilyTypefaceElement() { FamilyTypeface face = new FamilyTypeface(); ParseFamilyTypefaceAttributes(face); if (_reader.IsEmptyElement) { _reader.Read(); } else { _reader.Read(); while (MoveToContent() != XmlNodeType.EndElement) { if (_reader.NodeType == XmlNodeType.Element && _reader.NamespaceURI == CompositeFontNamespace) { if (_reader.LocalName == DeviceFontCharacterMetricsPropertyElement) { VerifyNoAttributes(); if (_reader.IsEmptyElement) { _reader.Read(); } else { _reader.Read(); // Process all child elements. while (MoveToContent() == XmlNodeType.Element) { if (_reader.LocalName == CharacterMetricsElement) { ParseCharacterMetricsElement(face); } else { // Only CharacterMetricsElement is valid in this context. FailUnknownElement(); } } // Process the end element for the collection. _reader.ReadEndElement(); } } else { FailUnknownElement(); } } else { _reader.Skip(); } } _reader.ReadEndElement(); } // Add the typeface. _compositeFontInfo.GetFamilyTypefaceList().Add(face); } /// <summary> /// Parses the attributes of the FamilyTypeface element and sets the corresponding /// properties on the specified FamilyTypeface object. On return, the reader remains /// positioned on the element. /// </summary> private void ParseFamilyTypefaceAttributes(FamilyTypeface face) { // Iterate over the attributes. if (_reader.MoveToFirstAttribute()) { do { // Process attributes in the composite font namespace; ignore any others. if (IsCompositeFontAttribute()) { string name = _reader.LocalName; if (name == StyleAttribute) { FontStyle fontStyle = new FontStyle(); if (!FontStyles.FontStyleStringToKnownStyle(GetAttributeValue(), CultureInfo.InvariantCulture, ref fontStyle)) FailAttributeValue(); face.Style = fontStyle; } else if (name == WeightAttribute) { FontWeight fontWeight = new FontWeight(); if (!FontWeights.FontWeightStringToKnownWeight(GetAttributeValue(), CultureInfo.InvariantCulture, ref fontWeight)) FailAttributeValue(); face.Weight = fontWeight; } else if (name == StretchAttribute) { FontStretch fontStretch = new FontStretch(); if (!FontStretches.FontStretchStringToKnownStretch(GetAttributeValue(), CultureInfo.InvariantCulture, ref fontStretch)) FailAttributeValue(); face.Stretch = fontStretch; } else if (name == UnderlinePositionAttribute) { face.UnderlinePosition = GetAttributeAsDouble(); } else if (name == UnderlineThicknessAttribute) { face.UnderlineThickness = GetAttributeAsDouble(); } else if (name == StrikethroughPositionAttribute) { face.StrikethroughPosition = GetAttributeAsDouble(); } else if (name == StrikethroughThicknessAttribute) { face.StrikethroughThickness = GetAttributeAsDouble(); } else if (name == CapsHeightAttribute) { face.CapsHeight = GetAttributeAsDouble(); } else if (name == XHeightAttribute) { face.XHeight = GetAttributeAsDouble(); } else if (name == DeviceFontNameAttribute) { face.DeviceFontName = GetAttributeValue(); } else { FailUnknownAttribute(); } } else if (!IsIgnorableAttribute()) { FailUnknownAttribute(); } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); } } /// <summary> /// Parses a CharacterMetrics element, and advances the current position beyond the /// element. Adds a CharacterMetrics object to the given FamilyTypface. /// </summary> private void ParseCharacterMetricsElement(FamilyTypeface face) { string key = null; string metrics = null; if (_reader.MoveToFirstAttribute()) { do { if (_reader.NamespaceURI == XamlNamespace && _reader.LocalName == KeyAttribute) { key = GetAttributeValue(); } else if (IsCompositeFontAttribute() && _reader.LocalName == MetricsAttribute) { metrics = GetAttributeValue(); } else if (!IsIgnorableAttribute()) { FailUnknownAttribute(); } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); } if (key == null) FailMissingAttribute(KeyAttribute); if (metrics == null) FailMissingAttribute(MetricsAttribute); face.DeviceFontCharacterMetrics.Add( CharacterMetricsDictionary.ConvertKey(key), new CharacterMetrics(metrics) ); // There should be no child elements. ParseEmptyElement(); } /// <summary> /// Parses the FontFamilyMap element, including its attributes and children, /// and advances to the next sibling element. /// </summary> private void ParseFamilyMapElement() { FontFamilyMap fmap = new FontFamilyMap(); // Parse the family map attributes. if (_reader.MoveToFirstAttribute()) { do { // Process attributes in the composite font namespace; ignore any others. if (IsCompositeFontAttribute()) { string name = _reader.LocalName; if (name == UnicodeAttribute) { fmap.Unicode = GetAttributeValue(); } else if (name == TargetAttribute) { fmap.Target = GetAttributeValue(); } else if (name == ScaleAttribute) { fmap.Scale = GetAttributeAsDouble(); } else if (name == LanguageAttribute) { fmap.Language = GetAttributeAsXmlLanguage(); } else { FailUnknownAttribute(); } } else if (!IsIgnorableAttribute()) { FailUnknownAttribute(); } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); } _compositeFontInfo.FamilyMaps.Add(fmap); // There should be no child elements. ParseEmptyElement(); } /// <summary> /// Advances past the current element and its children, throwing and exception /// if there are any child elements in the composite font namespace. /// </summary> private void ParseEmptyElement() { if (_reader.IsEmptyElement) { _reader.Read(); return; } _reader.Read(); while (MoveToContent() != XmlNodeType.EndElement) { if (_reader.NodeType == XmlNodeType.Element && _reader.NamespaceURI == CompositeFontNamespace) { FailUnknownElement(); } else { _reader.Skip(); } } _reader.ReadEndElement(); } /// <summary> /// Determines whether the reader is positioned on an composite font attribute, /// which we define to me either (a) it has no namespace at all, or (b) it's in /// the composite font namespace. /// </summary> private bool IsCompositeFontAttribute() { string ns = _reader.NamespaceURI; return string.IsNullOrEmpty(ns) || ns == CompositeFontNamespace; } /// <summary> /// Determines whether the attribute can be safely ignored, even if it /// has not been explicitly declared as ignorable via compatibility markup. /// Currently, we ignore attributes defined by the XML and XML namespaces /// standards. /// </summary> private bool IsIgnorableAttribute() { string ns = _reader.NamespaceURI; return ns == XmlNamespace || ns == XmlnsNamespace; } #region error reporting /// <summary> /// Make sure the minimum required information is specified. /// </summary> private void VerifyCompositeFontInfo() { if (_compositeFontInfo.FamilyMaps.Count == 0) Fail(SR.Get(SRID.CompositeFontMissingElement, FamilyMapElement)); if (_compositeFontInfo.FamilyNames.Count == 0) Fail(SR.Get(SRID.CompositeFontMissingElement, StringElement)); } /// <summary> /// Fail because of an XML exception. /// </summary> private void FailNotWellFormed(Exception x) { throw new FileFormatException(new Uri(_reader.BaseURI, UriKind.RelativeOrAbsolute), x); } /// <summary> /// Fail because of an incorrect attribute value. /// </summary> private void FailAttributeValue() { Fail(SR.Get( SRID.CompositeFontAttributeValue1, _reader.LocalName)); } /// <summary> /// Fail because of an incorrect attribute value with an inner exception. /// </summary> private void FailAttributeValue(Exception x) { Fail(SR.Get( SRID.CompositeFontAttributeValue2, _reader.LocalName, x.Message), x); } /// <summary> /// Fail because of an unknown element. /// </summary> private void FailUnknownElement() { Fail(SR.Get( SRID.CompositeFontUnknownElement, _reader.LocalName, _reader.NamespaceURI)); } /// <summary> /// Fail because of an unknown attribute. /// </summary> private void FailUnknownAttribute() { Fail(SR.Get( SRID.CompositeFontUnknownAttribute, _reader.LocalName, _reader.NamespaceURI)); } /// <summary> /// Fail because a required attribute is not present. /// </summary> /// <param name="name"></param> private void FailMissingAttribute(string name) { Fail(SR.Get(SRID.CompositeFontMissingAttribute, name)); } /// <summary> /// Fail with a specified error message. /// </summary> private void Fail(string message) { Fail(message, null); } /// <summary> /// Fail with a specified error message and inner exception. /// </summary> private void Fail(string message, Exception innerException) { string fileName = _reader.BaseURI; throw new FileFormatException(new Uri(fileName, UriKind.RelativeOrAbsolute), message, innerException); } #endregion private CompositeFontInfo _compositeFontInfo; private XmlReader _reader; // XML namespaces for which Mapping processing instructions have been read. For each entry, // the key is the XML namespace, and the value is either SystemClrNamespace (if the the // Mapping PI specifies "System" and "MSCORLIB") or String.Empty (any other Mapping). private Hashtable _namespaceMap; // Type converters for double and XmlLanguage types. private TypeConverter _doubleTypeConverter; private TypeConverter _xmlLanguageTypeConverter; private const string SystemClrNamespace = "System"; private const string CompositeFontNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/composite-font"; private const string XamlNamespace = "http://schemas.microsoft.com/winfx/2006/xaml"; private const string XmlNamespace = "http://www.w3.org/XML/1998/namespace"; private const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; private const string FontFamilyElement = "FontFamily"; private const string BaselineAttribute = "Baseline"; private const string LineSpacingAttribute = "LineSpacing"; private const string FamilyNamesPropertyElement = "FontFamily.FamilyNames"; private const string StringElement = "String"; private const string FamilyTypefacesPropertyElement = "FontFamily.FamilyTypefaces"; private const string FamilyTypefaceElement = "FamilyTypeface"; private const string FamilyMapsPropertyElement = "FontFamily.FamilyMaps"; private const string FamilyMapElement = "FontFamilyMap"; private const string KeyAttribute = "Key"; private const string LanguageAttribute = "Language"; private const string NameAttribute = "Name"; private const string StyleAttribute = "Style"; private const string WeightAttribute = "Weight"; private const string StretchAttribute = "Stretch"; private const string UnderlinePositionAttribute = "UnderlinePosition"; private const string UnderlineThicknessAttribute = "UnderlineThickness"; private const string StrikethroughPositionAttribute = "StrikethroughPosition"; private const string StrikethroughThicknessAttribute = "StrikethroughThickness"; private const string CapsHeightAttribute = "CapsHeight"; private const string XHeightAttribute = "XHeight"; private const string UnicodeAttribute = "Unicode"; private const string TargetAttribute = "Target"; private const string ScaleAttribute = "Scale"; private const string DeviceFontNameAttribute = "DeviceFontName"; private const string DeviceFontCharacterMetricsPropertyElement = "FamilyTypeface.DeviceFontCharacterMetrics"; private const string CharacterMetricsElement = "CharacterMetrics"; private const string MetricsAttribute = "Metrics"; } } namespace MS.Internal.TextFormatting { /// <summary> /// Partial class splitted from the original one in LineServices.cs. /// We do this to avoid bringing in TextFormatting namespace when /// building FontCacheServices.exe /// </summary> internal static partial class Constants { /// <summary> /// Greatest multiple of em allowed in composite font file /// </summary> public const double GreatestMutiplierOfEm = 100; } }
using System; using System.Collections.Specialized; using System.Reflection; namespace MyApp.Core { /// This approach to weak event handlers can be found in various online posts for solving the problem. /// Paul Stovell: http://paulstovell.com/blog/weakevents /// Dustin Campbell: http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx /// ...and more. Not sure which one was the original inspiration but additions have been made here. /// <summary> /// A weak event handler wrapper for events based on the commonly used EventHandler protocol. /// </summary> public sealed class WeakEventHandler { private readonly WeakReference _targetReference; private readonly MethodInfo _method; public WeakEventHandler(EventHandler callback) { _method = callback.Method; _targetReference = new WeakReference(callback.Target, true); } public void Handler(object sender, EventArgs e) { var target = _targetReference.Target; if (target != null) { var callback = (Action<object, EventArgs>)Delegate.CreateDelegate(typeof(Action<object, EventArgs>), target, _method, true); if (callback != null) { callback(sender, e); } } } } /// <summary> /// A weak event handler wrapper for events based on the generic EventHandler<TArgs/> protocol. /// </summary> public sealed class WeakEventHandler<TEventArgs> where TEventArgs : EventArgs { private readonly WeakReference _targetReference; private readonly MethodInfo _method; public WeakEventHandler(EventHandler<TEventArgs> callback) { _method = callback.Method; _targetReference = new WeakReference(callback.Target, true); } public void Handler(object sender, TEventArgs e) { var target = _targetReference.Target; if (target != null) { var callback = (Action<object, TEventArgs>)Delegate.CreateDelegate(typeof(Action<object, TEventArgs>), target, _method, true); if (callback != null) { callback(sender, e); } } } } /// <summary> /// A weak event handler wrapper for collection changed events based on the NotifyCollectionChangedEventArgs protocol. /// </summary> public sealed class WeakCollectionChangedEventHandler { private readonly WeakReference _targetReference; private readonly MethodInfo _method; public WeakCollectionChangedEventHandler(NotifyCollectionChangedEventHandler callback) { _method = callback.Method; _targetReference = new WeakReference(callback.Target, true); } public void Handler(object sender, NotifyCollectionChangedEventArgs e) { var target = _targetReference.Target; if (target != null) { var callback = (Action<object, NotifyCollectionChangedEventArgs>)Delegate.CreateDelegate(typeof(Action<object, NotifyCollectionChangedEventArgs>), target, _method, true); if (callback != null) { callback(sender, e); } } } } /// <summary> /// A weak event handler wrapper for whatever generic handler protocol that takes no args and returns a value. /// </summary> public sealed class WeakFuncHandler<TResult> { private readonly WeakReference _targetReference; private readonly MethodInfo _method; public WeakFuncHandler(Func<TResult> callback) { _method = callback.Method; _targetReference = new WeakReference(callback.Target, true); } public TResult Handler() { var target = _targetReference.Target; if (target != null) { var callback = (Func<TResult>)Delegate.CreateDelegate(typeof(Func<TResult>), target, _method, true); if (callback != null) { return callback(); } } return default(TResult); } } /// <summary> /// A weak event handler wrapper for whatever generic handler protocol that takes a single arg and returns a value. /// </summary> public sealed class WeakFuncHandler<TArg, TResult> { private readonly WeakReference _targetReference; private readonly MethodInfo _method; public WeakFuncHandler(Func<TArg, TResult> callback) { _method = callback.Method; _targetReference = new WeakReference(callback.Target, true); } public TResult Handler(TArg arg) { var target = _targetReference.Target; if (target != null) { var callback = (Func<TArg, TResult>)Delegate.CreateDelegate(typeof(Func<TArg, TResult>), target, _method, true); if (callback != null) { return callback(arg); } } return default(TResult); } } /// <summary> /// A weak action handler wrapper that takes no args. /// </summary> public sealed class WeakActionHandler { private readonly WeakReference _targetReference; private readonly MethodInfo _method; public WeakActionHandler(Action callback) { _method = callback.Method; _targetReference = new WeakReference(callback.Target, true); } public void Handler() { var target = _targetReference.Target; if (target != null) { var callback = (Action)Delegate.CreateDelegate(typeof(Action), target, _method, true); if (callback != null) { callback(); } } } } /// <summary> /// A weak action handler wrapper that takes 1 arg. /// </summary> public sealed class WeakActionHandler<TArg> { private readonly WeakReference _targetReference; private readonly MethodInfo _method; public WeakActionHandler(Action<TArg> callback) { _method = callback.Method; _targetReference = new WeakReference(callback.Target, true); } public void Handler(TArg arg) { var target = _targetReference.Target; if (target != null) { var callback = (Action<TArg>)Delegate.CreateDelegate(typeof(Action<TArg>), target, _method, true); if (callback != null) { callback(arg); } } } } }
/* Copyright (c) 2012 Ant Micro <www.antmicro.com> Authors: * Konrad Kruczynski ([email protected]) * Piotr Zierhoffer ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using NUnit.Framework; using System.IO; using System; using System.Linq; namespace Antmicro.Migrant.Tests { [TestFixture(true)] [TestFixture(false)] public class PrimitiveReaderWriterTests { public PrimitiveReaderWriterTests(bool buffered) { this.buffered = buffered; } [Test] public void ShouldWriteAndReadInts( [Values(1, 10, 100, 10000, 1000*1000)] int numberOfInts) { var randomInts = Helpers.GetRandomIntegers(numberOfInts); var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < randomInts.Length; i++) { writer.Write(randomInts[i]); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < randomInts.Length; i++) { Assert.AreEqual(randomInts[i], reader.ReadInt32()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadLongs( [Values(1, 10, 100, 10000, 1000*1000)] int numberOfLongs) { var randomLongs = Helpers.GetRandomLongs(numberOfLongs); var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < randomLongs.Length; i++) { writer.Write(randomLongs[i]); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < randomLongs.Length; i++) { var read = reader.ReadInt64(); Assert.AreEqual(randomLongs[i], read); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadULongs( [Values(1, 10, 100, 10000, 1000*1000)] int numberOfULongs) { var randomULongs = Helpers.GetRandomLongs(numberOfULongs).Select(x=>(ulong)x).ToArray(); var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < randomULongs.Length; i++) { writer.Write(randomULongs[i]); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < randomULongs.Length; i++) { var read = reader.ReadUInt64(); Assert.AreEqual(randomULongs[i], read); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadStrings( [Values(1, 100, 10000)] int numberOfStrings, [Values(true, false)] bool withLongStrings) { const int maxLength = 100; const int longStringLength = 8000; const int longStringProbability = 10; var random = Helpers.Random; var strings = new string[numberOfStrings]; for(var i = 0; i < strings.Length; i++) { int length; if(withLongStrings && random.Next()%longStringProbability == 0) { length = longStringLength; } else { length = random.Next(maxLength); } strings[i] = Helpers.GetRandomString(length); } var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < strings.Length; i++) { writer.Write(strings[i]); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < strings.Length; i++) { Assert.AreEqual(strings[i], reader.ReadString()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadNegativeInt() { var value = -Helpers.Random.Next(); var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { writer.Write(value); } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { Assert.AreEqual(value, reader.ReadInt32()); } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadDoubles( [Values(1, 10, 100, 10000, 1000*1000)] int numberOfDoubles) { var randomDoubles = Helpers.GetRandomDoubles(numberOfDoubles); var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < randomDoubles.Length; i++) { writer.Write(randomDoubles[i]); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < randomDoubles.Length; i++) { Assert.AreEqual(randomDoubles[i], reader.ReadDouble()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadDecimal( [Values(1, 10, 100, 10000, 1000*1000)] int numberOfDecimals) { var randomDecimals = Helpers.GetRandomDecimals(numberOfDecimals); var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < randomDecimals.Length; i++) { writer.Write(randomDecimals[i]); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < randomDecimals.Length; i++) { Assert.AreEqual(randomDecimals[i], reader.ReadDecimal()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldSerializeDateTime( [Values(1, 10, 100, 10000)] int numberOfEntries) { var randomDateTimes = Helpers.GetRandomDateTimes(numberOfEntries); var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < randomDateTimes.Length; i++) { writer.Write(randomDateTimes[i]); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < randomDateTimes.Length; i++) { Assert.AreEqual(randomDateTimes[i], reader.ReadDateTime()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldSerializeTimeSpan( [Values(1, 10, 100, 10000)] int numberOfEntries) { var randomDateTimes = Helpers.GetRandomDateTimes(numberOfEntries); var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < randomDateTimes.Length; i++) { writer.Write(randomDateTimes[i]); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < randomDateTimes.Length; i++) { Assert.AreEqual(randomDateTimes[i], reader.ReadDateTime()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadByteArray( [Values(10, 1000, 100000)] int count ) { var stream = new MemoryStream(); byte[] array; using(var writer = new PrimitiveWriter(stream, buffered)) { array = new byte[count]; Helpers.Random.NextBytes(array); writer.Write(array); } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); byte[] copy; using(var reader = new PrimitiveReader(stream, buffered)) { copy = reader.ReadBytes(count); } CollectionAssert.AreEqual(array, copy); Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadGuid( [Values(10, 1000, 100000)] int count ) { var stream = new MemoryStream(); var array = new Guid[count]; using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < count; i++) { var guid = Guid.NewGuid(); array[i] = guid; writer.Write(guid); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < count; i++) { Assert.AreEqual(array[i], reader.ReadGuid()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldWriteAndReadPartsOfByteArrays() { var arrays = new byte[100][]; for(var i = 0; i < arrays.Length; i++) { arrays[i] = Enumerable.Range(0, 256).Select(x => (byte)x).ToArray(); } var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { for(var i = 0; i < arrays.Length; i++) { writer.Write(arrays[i], i, arrays[i].Length - i); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { for(var i = 0; i < arrays.Length; i++) { var writtenLength = arrays[i].Length - i; var writtenArray = reader.ReadBytes(writtenLength); var subarray = new byte[writtenLength]; Array.Copy(arrays[i], i, subarray, 0, writtenLength); CollectionAssert.AreEqual(subarray, writtenArray); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldReadAndWriteLimits() { var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { writer.Write(byte.MinValue); writer.Write(byte.MaxValue); writer.Write(sbyte.MinValue); writer.Write(sbyte.MaxValue); writer.Write(short.MinValue); writer.Write(short.MaxValue); writer.Write(ushort.MinValue); writer.Write(ushort.MaxValue); writer.Write(int.MinValue); writer.Write(int.MaxValue); writer.Write(uint.MinValue); writer.Write(uint.MaxValue); writer.Write(long.MinValue); writer.Write(long.MaxValue); writer.Write(ulong.MinValue); writer.Write(ulong.MaxValue); } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { Assert.AreEqual(byte.MinValue, reader.ReadByte()); Assert.AreEqual(byte.MaxValue, reader.ReadByte()); Assert.AreEqual(sbyte.MinValue, reader.ReadSByte()); Assert.AreEqual(sbyte.MaxValue, reader.ReadSByte()); Assert.AreEqual(short.MinValue, reader.ReadInt16()); Assert.AreEqual(short.MaxValue, reader.ReadInt16()); Assert.AreEqual(ushort.MinValue, reader.ReadUInt16()); Assert.AreEqual(ushort.MaxValue, reader.ReadUInt16()); Assert.AreEqual(int.MinValue, reader.ReadInt32()); Assert.AreEqual(int.MaxValue, reader.ReadInt32()); Assert.AreEqual(uint.MinValue, reader.ReadUInt32()); Assert.AreEqual(uint.MaxValue, reader.ReadUInt32()); Assert.AreEqual(long.MinValue, reader.ReadInt64()); Assert.AreEqual(long.MaxValue, reader.ReadInt64()); Assert.AreEqual(ulong.MinValue, reader.ReadUInt64()); Assert.AreEqual(ulong.MaxValue, reader.ReadUInt64()); } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldHandleNotAlignedWrites() { const int iterationCount = 80000; var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream, buffered)) { writer.Write((byte)1); for(var i = 0; i < iterationCount; i++) { writer.Write(int.MaxValue); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream, buffered)) { Assert.AreEqual((byte)1, reader.ReadByte()); for(var i = 0; i < iterationCount; i++) { Assert.AreEqual(int.MaxValue, reader.ReadInt32()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); } [Test] public void ShouldCopyFromStream() { var stream = new MemoryStream(); var testArray = Enumerable.Range(0, 1000).Select(x => (byte)x).ToArray(); var testStream = new MemoryStream(testArray); using(var writer = new PrimitiveWriter(stream, buffered)) { writer.CopyFrom(testStream, testArray.Length); } stream.Seek(0, SeekOrigin.Begin); var secondStream = new MemoryStream(testArray.Length); using(var reader = new PrimitiveReader(stream, buffered)) { reader.CopyTo(secondStream, testArray.Length); } CollectionAssert.AreEqual(testArray, secondStream.ToArray()); } [Test] public void ShouldThrowIfStreamPrematurelyFinishes() { var streamToRead = new MemoryStream(); var streamToWrite = new MemoryStream(); using(var reader = new PrimitiveReader(streamToRead, buffered)) { Assert.Throws<EndOfStreamException>(() => reader.CopyTo(streamToWrite, 100)); } } private readonly bool buffered; private const string StreamCorruptedMessage = "Stream was corrupted during read (in terms of position)."; } }
/* * SynchronizedList.cs - Wrap a list to make it synchronized. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Generics { using System; public class SynchronizedList<T> : SynchronizedCollection<T>, IList<T> { // Internal state. protected IList<T> list; // Constructor. public SynchronizedList(IList<T> list) : base(list) { this.list = list; } // Implement the IList<T> interface. public int Add(T value) { lock(SyncRoot) { return list.Add(value); } } public void Clear() { lock(SyncRoot) { list.Clear(); } } public bool Contains(T value) { lock(SyncRoot) { return list.Contains(value); } } public new IListIterator<T> GetIterator() { lock(SyncRoot) { return new SynchronizedListIterator<T> (list, list.GetIterator()); } } public int IndexOf(T value) { lock(SyncRoot) { return list.IndexOf(value); } } public void Insert(int index, T value) { lock(SyncRoot) { list.Insert(index, value); } } public void Remove(T value) { lock(SyncRoot) { list.Remove(value); } } public void RemoveAt(int index) { lock(SyncRoot) { list.RemoveAt(index); } } public bool IsRandomAccess { get { lock(SyncRoot) { return list.IsRandomAccess; } } } public T this[int index] { get { lock(SyncRoot) { return list[index]; } } set { lock(SyncRoot) { list[index] = value; } } } // Implement the ICloneable interface. public override Object Clone() { lock(SyncRoot) { if(list is ICloneable) { return new SynchronizedList<T> ((IList<T>)(((ICloneable)list).Clone())); } else { throw new InvalidOperationException (S._("Invalid_NotCloneable")); } } } // Synchronized list iterator. private sealed class SynchronizedListIterator<T> : IListIterator<T> { // Internal state. protected IList<T> list; protected IListIterator<T> iterator; // Constructor. public SynchronizedListIterator (IList<T> list, IListIterator<T> iterator) { this.list = list; this.iterator = iterator; } // Implement the IIterator<T> interface. public bool MoveNext() { lock(list.SyncRoot) { return iterator.MoveNext(); } } public void Reset() { lock(list.SyncRoot) { iterator.Reset(); } } public void Remove() { lock(list.SyncRoot) { iterator.Remove(); } } T IIterator<T>.Current { get { lock(list.SyncRoot) { return ((IIterator<T>)iterator).Current; } } } // Implement the IListIterator<T> interface. public bool MovePrev() { lock(list.SyncRoot) { return iterator.MovePrev(); } } public int Position { get { lock(list.SyncRoot) { return iterator.Position; } } } public T Current { get { lock(list.SyncRoot) { return iterator.Current; } } set { lock(list.SyncRoot) { iterator.Current = value; } } } }; // class SynchronizedListIterator<T> }; // class SynchronizedList<T> }; // namespace Generics
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenMetaverse; using OpenSim.Region.Framework.Scenes; namespace InWorldz.Region.Data.Thoosa.Tests { internal class Util { private readonly static Random rand = new Random(); public static Vector3 RandomVector() { return new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()); } public static Quaternion RandomQuat() { return new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()); } internal static byte RandomByte() { return (byte)rand.Next(byte.MaxValue); } public static SceneObjectPart RandomSOP(string name, uint localId) { var shape = new OpenSim.Framework.PrimitiveBaseShape(); shape.ExtraParams = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 }; shape.FlexiDrag = 0.3f; shape.FlexiEntry = true; shape.FlexiForceX = 1.0f; shape.FlexiForceY = 2.0f; shape.FlexiForceZ = 3.0f; shape.FlexiGravity = 10.0f; shape.FlexiSoftness = 1; shape.FlexiTension = 999.4f; shape.FlexiWind = 9292.33f; shape.HollowShape = OpenSim.Framework.HollowShape.Square; shape.LightColorA = 0.3f; shape.LightColorB = 0.22f; shape.LightColorG = 0.44f; shape.LightColorR = 0.77f; shape.LightCutoff = 0.4f; shape.LightEntry = true; shape.LightFalloff = 7474; shape.LightIntensity = 0.0f; shape.LightRadius = 10.0f; shape.Media = new OpenSim.Framework.PrimitiveBaseShape.PrimMedia(); shape.Media.New(2); shape.Media[0] = new MediaEntry { AutoLoop = true, AutoPlay = true, AutoScale = true, AutoZoom = true, ControlPermissions = MediaPermission.All, Controls = MediaControls.Standard, CurrentURL = "bam.com", EnableAlterntiveImage = true, EnableWhiteList = false, Height = 1, HomeURL = "anotherbam.com", InteractOnFirstClick = true, InteractPermissions = MediaPermission.Group, WhiteList = new string[] { "yo mamma" }, Width = 5 }; shape.Media[1] = new MediaEntry { AutoLoop = true, AutoPlay = true, AutoScale = true, AutoZoom = true, ControlPermissions = MediaPermission.All, Controls = MediaControls.Standard, CurrentURL = "kabam.com", EnableAlterntiveImage = true, EnableWhiteList = true, Height = 1, HomeURL = "anotherbam.com", InteractOnFirstClick = true, InteractPermissions = MediaPermission.Group, WhiteList = new string[] { "ur mamma" }, Width = 5 }; shape.PathBegin = 3; shape.PathCurve = 127; shape.PathEnd = 10; shape.PathRadiusOffset = 127; shape.PathRevolutions = 2; shape.PathScaleX = 50; shape.PathScaleY = 100; shape.PathShearX = 33; shape.PathShearY = 44; shape.PathSkew = 126; shape.PathTaperX = 110; shape.PathTaperY = 66; shape.PathTwist = 99; shape.PathTwistBegin = 3; shape.PCode = 3; shape.PreferredPhysicsShape = PhysicsShapeType.Prim; shape.ProfileBegin = 77; shape.ProfileCurve = 5; shape.ProfileEnd = 7; shape.ProfileHollow = 9; shape.ProfileShape = OpenSim.Framework.ProfileShape.IsometricTriangle; shape.ProjectionAmbiance = 0.1f; shape.ProjectionEntry = true; shape.ProjectionFocus = 3.4f; shape.ProjectionFOV = 4.0f; shape.ProjectionTextureUUID = UUID.Random(); shape.Scale = Util.RandomVector(); shape.SculptEntry = true; shape.SculptTexture = UUID.Random(); shape.SculptType = 40; shape.VertexCount = 1; shape.HighLODBytes = 2; shape.MidLODBytes = 3; shape.LowLODBytes = 4; shape.LowestLODBytes = 5; SceneObjectPart part = new SceneObjectPart(UUID.Zero, shape, new Vector3(1, 2, 3), new Quaternion(4, 5, 6, 7), Vector3.Zero, false); part.Name = name; part.Description = "Desc"; part.AngularVelocity = Util.RandomVector(); part.BaseMask = 0x0876; part.Category = 10; part.ClickAction = 5; part.CollisionSound = UUID.Random(); part.CollisionSoundVolume = 1.1f; part.CreationDate = OpenSim.Framework.Util.UnixTimeSinceEpoch(); part.CreatorID = UUID.Random(); part.EveryoneMask = 0x0543; part.Flags = PrimFlags.CameraSource | PrimFlags.DieAtEdge; part.GroupID = UUID.Random(); part.GroupMask = 0x0210; part.LastOwnerID = UUID.Random(); part.LinkNum = 4; part.LocalId = localId; part.Material = 0x1; part.MediaUrl = "http://bam"; part.NextOwnerMask = 0x0234; part.CreatorID = UUID.Random(); part.ObjectFlags = 10101; part.OwnerID = UUID.Random(); part.OwnerMask = 0x0567; part.OwnershipCost = 5; part.ParentID = 0202; part.ParticleSystem = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, }; part.PassTouches = true; part.PhysicalAngularVelocity = Util.RandomVector(); part.RegionHandle = 1234567; part.RegionID = UUID.Random(); part.RotationOffset = Util.RandomQuat(); part.SalePrice = 42; part.SavedAttachmentPoint = 6; part.SavedAttachmentPos = Util.RandomVector(); part.SavedAttachmentRot = Util.RandomQuat(); part.ScriptAccessPin = 87654; part.SerializedPhysicsData = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, }; part.ServerFlags = 0; part.ServerWeight = 3.0f; part.StreamingCost = 2.0f; part.SitName = "Sitting"; part.Sound = UUID.Random(); part.SoundGain = 3.4f; part.SoundOptions = 9; part.SoundRadius = 10.3f; part.Text = "Test"; part.TextColor = System.Drawing.Color.FromArgb(1, 2, 3, 4); part.TextureAnimation = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD }; part.TouchName = "DoIt"; part.UUID = UUID.Random(); part.Velocity = Util.RandomVector(); part.FromItemID = UUID.Random(); part.ServerFlags |= (uint)ServerPrimFlags.SitTargetStateSaved; // This one has been migrated to the new sit target storage part.SetSitTarget(true, Util.RandomVector(), Util.RandomQuat(), false); return part; } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace InfiniMap.Test { [TestFixture] public class MapTestsSerialization3D { [Test] public void MapSerializer() { var map = new Map3D<float>(); map[0, 0, 0] = 1.0f; // Chunk: (0,0,0) map[16, 16, 16] = 2.0f; // Chunk: (1,1,1) map[32, 32, 32] = 4.0f; // Chunk: (2,2,2) var list = new List<ChunkSpace>(); map.RegisterWriter((xyz, tuple) => { Console.WriteLine("Writing: ({0},{1},{2})", xyz.X, xyz.Y, xyz.Z); list.Add(xyz); }); map.UnloadArea((0, 0, 0), (32, 32, 32)); Assert.AreEqual(3, list.Count); Assert.That(list.Contains(new ChunkSpace(0L, 0L, 0L))); Assert.That(list.Contains(new ChunkSpace(1L, 1L, 1L))); Assert.That(list.Contains(new ChunkSpace(2L, 2L, 2L))); map.UnregisterWriter(); map[48, 48, 48] = 4.0f; map.UnloadArea((0, 0, 0), (48, 48, 48)); Assert.AreEqual(3, list.Count); } [Test] public void MapDeserializer() { var map = new Map3D<float>(); int i = 0; // Assert that the Reader function is called for each new chunk loaded into memory map.RegisterReader(tuple => { i++; return new Chunk<float>(16, 16, 16); }); map[0, 0, 0] = 1.0f; // Chunk: (0,0,0) map[16, 16, 16] = 2.0f; // Chunk: (1,1,1) map[32, 32, 32] = 4.0f; // Chunk: (2,2,2) Assert.AreEqual(3, i); map.UnregisterReader(); map[48, 48, 48] = 8.0f; // Assert that after unregistering, the callback is not invoked. Assert.AreEqual(3, i); } } [TestFixture] public class MapTests3D { [Test] public void CanInsertItems() { var mapStruct = new Map3D<StructItem>(); mapStruct[4, 4, 4] = new StructItem() {ItemId = 4}; Assert.That(mapStruct[4, 4, 4].ItemId == 4); var mapPrim = new Map3D<float>(); mapPrim[4, 4, 4] = 4.0f; Assert.That(Math.Abs(mapPrim[4, 4, 4] - 4.0f) < 0.001); var mapClass = new Map3D<ClassItem>(); mapClass[4, 4, 4] = new ClassItem() {ItemId = 4}; Assert.That(mapClass[4, 4, 4].ItemId == 4); } [Test] public void CanUseNegativePositions() { var map = new Map3D<float>(); map[-4, -4, -4] = 4.0f; Assert.That(Math.Abs(map[-4, -4, -4] - 4.0f) < 0.001); } [Test] public void CanEnumerateRanges() { var map = new Map3D<float>(); map[1, 1, 1] = 4.0f; Assert.That(map.Within(new WorldSpace(0, 0, 0), new WorldSpace(2, 2, 2)).Any()); Assert.That(map.Within(new WorldSpace(0, 0, 0), new WorldSpace(2, 2, 2)) .Any(i => Math.Abs(i - 4.0f) < 0.001)); } [Test] public void CanAccessRandomly() { var map = new Map3D<float>(); map[-8, -8, -8] = 4.0f; map[-240, -778, -255] = 8.0f; map[8, 8, 8] = 16.0f; map[240, 778, 255] = 32.0f; Assert.That(Math.Abs(map[-240, -778, -255] - 8.0f) < 0.001); Assert.That(Math.Abs(map[240, 778, 255] - 32.0f) < 0.001); } [Test] public void SparseCreation() { var map = new Map3D<float>(); map[-8, -8, -8] = 4.0f; map[-1024, -887, -900] = 8.0f; // With only two areas in memory, we only have (16*16*16)*2 blocks Assert.AreEqual(8192, map.Count); } [Test] public void CanUseContains() { var map = new Map3D<float>(); map[1, 2, 1] = 4.0f; Assert.That(map.Contains(4.0f)); Assert.That(map.Contains(4.0f, new EqualityLambda<float>((a, b) => Math.Abs(a - b) < 0.001))); } [Test] public void IsCubic() { var map = new Map3D<float>(); // 'Ground Level' map[1, 1, 1] = 1.0f; // 'Cloud Level' map[1, 1, 64] = 64.0f; // 'Atmosphere' map[1, 1, 128] = 128.0f; // Spaaaace map[1, 1, 256] = 256.0f; // Dad, are we space now? map[1, 1, 2048] = 2048.0f; // No son, we are Aldebaran. map[1, 1, Int64.MaxValue] = 8192.0f; Assert.AreEqual(((16*16*16)*6), map.Count); } [Test] public void SupportsUnloading() { var map = new Map3D<float>(); map[0, 0, 0] = 2.0f; map[16, 16, 16] = 2.0f; map[33, 33, 33] = 4.0f; Assert.AreEqual((16*16*16)*3, map.Count); map.UnloadArea((0, 0, 0), (33, 33, 33)); Assert.AreEqual(0, map.Count); } [Test] public void SupportsUnloadingWithPersistance() { var map = new Map3D<float>(); map[0, 0, 0] = 2.0f; map[16, 16, 16] = 2.0f; map[33, 33, 33] = 4.0f; Assert.AreEqual((16 * 16 * 16) * 3, map.Count); map.MakePersistant((1, 1, 1)); map.UnloadArea((0, 0, 0), (33, 33, 33)); Assert.AreEqual((16*16*16), map.Count); } [Test] public void ChunkGathering() { var map = new Map3D<float>(16, 16, 16); map[1, 1, 1] = 2.0f; map[1, 1, 17] = 4.0f; map[1, 1, 33] = 8.0f; // Assert we have 3 chunks in memory. Assert.AreEqual((16 * 16 * 16) * 3, map.Count); // A single chunk at the bottom of the stack { var begin = new WorldSpace(0, 0, 0); var end = new WorldSpace(15, 15, 15); var chunksFound = map.ChunksWithin(begin, end, createIfNull: false).ToList(); Assert.AreEqual(1, chunksFound.Count()); Assert.AreEqual(0, chunksFound.Select(s => s.Item1.Z).First()); // Assert that it is the correct chunk Assert.That(chunksFound.ElementAt(0).Item2.Contains(2.0f)); } // All three chunks stacked on top of each other { var begin = new WorldSpace(0, 0, 0); var end = new WorldSpace(15, 15, 33); var chunksFound = map.ChunksWithin(begin, end, createIfNull: false).ToList(); Assert.AreEqual(3, chunksFound.Count()); IEnumerable<long> zSequences = new List<long> { 0, 1, 2 }; var chunks = chunksFound.Select(chunk => chunk.Item1.Z).OrderBy(s => s).AsEnumerable(); Assert.AreEqual(3, chunks.Union(zSequences).Count()); // Assert we have the actual chunks Assert.That(chunksFound.ElementAt(0).Item2.Contains(2.0f)); Assert.That(chunksFound.ElementAt(1).Item2.Contains(4.0f)); Assert.That(chunksFound.ElementAt(2).Item2.Contains(8.0f)); } // The two top most stacks { var begin = new WorldSpace(0, 0, 16); var end = new WorldSpace(15, 15, 33); var chunksFound = map.ChunksWithin(begin, end, createIfNull: false).ToList(); Assert.AreEqual(2, chunksFound.Count()); // Assert that we got back the right chunks in terms of Z level startings var zSequences = new List<long> { 1, 2 }; var chunks = chunksFound.Select(chunk => chunk.Item1.Z).OrderBy(s => s); Assert.AreEqual(2, chunks.Union(zSequences).Count()); // Assert we have the actual chunks. Assert.That(chunksFound.ElementAt(0).Item2.Contains(4.0f)); Assert.That(chunksFound.ElementAt(1).Item2.Contains(8.0f)); } } [Test] public void SupportsUnloadingOutsideArea() { var map = new Map3D<float>(16, 16, 16); { map[4, 4, 0] = 2.0f; map[63, 63, 0] = 4.0f; // Two chunks loaded Assert.AreEqual((16 * 16 * 16) * 2, map.Count); var begin = new WorldSpace(0, 0, 0); var end = new WorldSpace(15, 15, 0); map.UnloadAreaOutside(begin, end); // Ony one chunk left Assert.AreEqual((16 * 16 * 16), map.Count); } // Non-zero test { map[0, 0, 0] = 2.0f; map[16, 16, 0] = 2.0f; map[32, 32, 0] = 4.0f; map[48, 48, 7] = 8.0f; map[64, 64, 15] = 16.0f; map[80, 80, 15] = 32.0f; map[96, 96, 0] = 64.0f; map[128, 128, 0] = 128.0f; Assert.AreEqual((16 * 16 * 16) * 8, map.Count); var begin = new WorldSpace(48, 48, 0); var end = new WorldSpace(80, 80, 15); map.UnloadAreaOutside(begin, end); Assert.AreEqual((16 * 16 * 16) * 3, map.Count); } } } [TestFixture] public class MapTestEntities3D { [Test] public void SupportsAddingEntities() { var map = new Map3D<float>(16, 16, 16); var oldBoot = new Entity { Name = "Old Boot" }; map.PutEntity(new WorldSpace(1, 1, 1), oldBoot); Assert.That(map.GetEntitiesAt(1, 1, 1).Any()); Assert.That(oldBoot.X == 1 && oldBoot.Y == 1); } [Test] public void SupportsQuantumEntanglementPrevention() { var map = new Map3D<float>(16, 16, 16); var oldBoot = new Entity { Name = "Old Boot" }; map.PutEntity(new WorldSpace(1, 1, 1), oldBoot); Assert.That(map.GetEntitiesAt(1, 1, 1).Any()); Assert.That(oldBoot.X == 1 && oldBoot.Y == 1); // Put the boot somewhere else, moving it. map.PutEntity(new WorldSpace(17, 17, 17), oldBoot); oldBoot.Name = "Spooky Old Boot"; Assert.That(map.GetEntitiesAt(1, 1, 1).Any() == false); Assert.That(map.GetEntitiesAt(17, 17, 17).Any()); } [Test] public void SupportsAddingAndRemovingEntities() { var map = new Map3D<float>(16, 16, 16); var oldBoot = new Entity { Name = "Old Boot" }; map.PutEntity(new WorldSpace(1, 1, 1), oldBoot); Assert.That(map.GetEntitiesAt(1, 1, 1).Any()); Assert.That(oldBoot.X == 1 && oldBoot.Y == 1); map.RemoveEntity(oldBoot); Assert.That(map.GetEntitiesAt(1, 1, 1).Any() == false); // After removing, items have null coordinates. Assert.That(oldBoot.X == null); Assert.That(oldBoot.Y == null); Assert.That(oldBoot.Z == null); } [Test] public void SupportsGettingEntitiesInLocalArea() { var map = new Map3D<float>(16, 16, 16); var oldBoot = new Entity { Name = "Old Boot" }; var oldCan = new Entity { Name = "Old Boot" }; var oldBucket = new Entity { Name = "Old Boot" }; map.PutEntity(new WorldSpace(1, 1, 1), oldBoot); map.PutEntity(new WorldSpace(1, 1, 1), oldBucket); map.PutEntity(new WorldSpace(1, 1, 1), oldCan); Assert.That(map.GetEntitiesAt(1, 1, 1).Any()); Assert.That(oldBoot.X == 1 && oldBoot.Y == 1); Assert.That(map.GetEntitiesInChunk(new WorldSpace(0, 0, 0)).Count() == 3); } [Test] public void SupportsAddingAndMovingEntities() { var map = new Map3D<float>(16, 16, 16); var oldBoot = new Entity { Name = "Old Boot" }; map.PutEntity(new WorldSpace(1, 1, 1), oldBoot); Assert.That(map.GetEntitiesAt(1, 1, 1).Any()); Assert.That(oldBoot.X == 1 && oldBoot.Y == 1); map.PutEntity(new WorldSpace(17, 17, 17), oldBoot); Assert.That(map.GetEntitiesAt(1, 1, 1).Any() == false); Assert.That(map.GetEntitiesAt(17, 17, 17).Any()); Assert.That(oldBoot.X == 17 && oldBoot.Y == 17); } public class Entity : IEntityLocationData { public long? X { get; set; } public long? Y { get; set; } public long? Z { get; set; } public string Name { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; namespace System.Buffers.Text { public static partial class Utf8Formatter { #region Constants private const byte OpenBrace = (byte)'{'; private const byte CloseBrace = (byte)'}'; private const byte OpenParen = (byte)'('; private const byte CloseParen = (byte)')'; private const byte Dash = (byte)'-'; #endregion Constants /// <summary> /// Formats a Guid as a UTF8 string. /// </summary> /// <param name="value">Value to format</param> /// <param name="destination">Buffer to write the UTF8-formatted value to</param> /// <param name="bytesWritten">Receives the length of the formatted text in bytes</param> /// <param name="format">The standard format to use</param> /// <returns> /// true for success. "bytesWritten" contains the length of the formatted text in bytes. /// false if buffer was too short. Iteratively increase the size of the buffer and retry until it succeeds. /// </returns> /// <remarks> /// Formats supported: /// D (default) nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn /// B {nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn} /// P (nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn) /// N nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn /// </remarks> /// <exceptions> /// <cref>System.FormatException</cref> if the format is not valid for this data type. /// </exceptions> public static bool TryFormat(Guid value, Span<byte> destination, out int bytesWritten, StandardFormat format = default) { const int INSERT_DASHES = unchecked((int)0x80000000); const int NO_DASHES = 0; const int INSERT_CURLY_BRACES = (CloseBrace << 16) | (OpenBrace << 8); const int INSERT_ROUND_BRACES = (CloseParen << 16) | (OpenParen << 8); const int NO_BRACES = 0; const int LEN_GUID_BASE = 32; const int LEN_ADD_DASHES = 4; const int LEN_ADD_BRACES = 2; // This is a 32-bit value whose contents (where 0 is the low byte) are: // 0th byte: minimum required length of the output buffer, // 1st byte: the ASCII byte to insert for the opening brace position (or 0 if no braces), // 2nd byte: the ASCII byte to insert for the closing brace position (or 0 if no braces), // 3rd byte: high bit set if dashes are to be inserted. // // The reason for keeping a single flag instead of separate vars is that we can avoid register spillage // as we build up the output value. int flags; switch (FormattingHelpers.GetSymbolOrDefault(format, 'D')) { case 'D': // nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn flags = INSERT_DASHES + NO_BRACES + LEN_GUID_BASE + LEN_ADD_DASHES; break; case 'B': // {nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn} flags = INSERT_DASHES + INSERT_CURLY_BRACES + LEN_GUID_BASE + LEN_ADD_DASHES + LEN_ADD_BRACES; break; case 'P': // (nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn) flags = INSERT_DASHES + INSERT_ROUND_BRACES + LEN_GUID_BASE + LEN_ADD_DASHES + LEN_ADD_BRACES; break; case 'N': // nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn flags = NO_BRACES + NO_DASHES + LEN_GUID_BASE; break; default: return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); } // At this point, the low byte of flags contains the minimum required length if ((byte)flags > destination.Length) { bytesWritten = 0; return false; } bytesWritten = (byte)flags; flags >>= 8; // At this point, the low byte of flags contains the opening brace char (if any) if ((byte)flags != 0) { destination[0] = (byte)flags; destination = destination.Slice(1); } flags >>= 8; // At this point, the low byte of flags contains the closing brace char (if any) // And since we're performing arithmetic shifting the high bit of flags is set (flags is negative) if dashes are required DecomposedGuid guidAsBytes = default; guidAsBytes.Guid = value; // When a GUID is blitted, the first three components are little-endian, and the last component is big-endian. // The line below forces the JIT to hoist the bounds check for the following segment. // The JIT will optimize away the read, but it cannot optimize away the bounds check // because it may have an observable side effect (throwing). // We use 8 instead of 7 so that we also capture the dash if we're asked to insert one. { _ = destination[8]; } FormattingHelpers.WriteHexByte(guidAsBytes.Byte03, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte02, destination, 2, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte01, destination, 4, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte00, destination, 6, FormattingHelpers.HexCasing.Lowercase); if (flags < 0 /* use dash? */) { destination[8] = Dash; destination = destination.Slice(9); } else { destination = destination.Slice(8); } { _ = destination[4]; } FormattingHelpers.WriteHexByte(guidAsBytes.Byte05, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte04, destination, 2, FormattingHelpers.HexCasing.Lowercase); if (flags < 0 /* use dash? */) { destination[4] = Dash; destination = destination.Slice(5); } else { destination = destination.Slice(4); } { _ = destination[4]; } FormattingHelpers.WriteHexByte(guidAsBytes.Byte07, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte06, destination, 2, FormattingHelpers.HexCasing.Lowercase); if (flags < 0 /* use dash? */) { destination[4] = Dash; destination = destination.Slice(5); } else { destination = destination.Slice(4); } { _ = destination[4]; } FormattingHelpers.WriteHexByte(guidAsBytes.Byte08, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte09, destination, 2, FormattingHelpers.HexCasing.Lowercase); if (flags < 0 /* use dash? */) { destination[4] = Dash; destination = destination.Slice(5); } else { destination = destination.Slice(4); } { _ = destination[11]; } // can't hoist bounds check on the final brace (if exists) FormattingHelpers.WriteHexByte(guidAsBytes.Byte10, destination, 0, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte11, destination, 2, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte12, destination, 4, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte13, destination, 6, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte14, destination, 8, FormattingHelpers.HexCasing.Lowercase); FormattingHelpers.WriteHexByte(guidAsBytes.Byte15, destination, 10, FormattingHelpers.HexCasing.Lowercase); if ((byte)flags != 0) { destination[12] = (byte)flags; } return true; } /// <summary> /// Used to provide access to the individual bytes of a GUID. /// </summary> [StructLayout(LayoutKind.Explicit)] private struct DecomposedGuid { [FieldOffset(00)] public Guid Guid; [FieldOffset(00)] public byte Byte00; [FieldOffset(01)] public byte Byte01; [FieldOffset(02)] public byte Byte02; [FieldOffset(03)] public byte Byte03; [FieldOffset(04)] public byte Byte04; [FieldOffset(05)] public byte Byte05; [FieldOffset(06)] public byte Byte06; [FieldOffset(07)] public byte Byte07; [FieldOffset(08)] public byte Byte08; [FieldOffset(09)] public byte Byte09; [FieldOffset(10)] public byte Byte10; [FieldOffset(11)] public byte Byte11; [FieldOffset(12)] public byte Byte12; [FieldOffset(13)] public byte Byte13; [FieldOffset(14)] public byte Byte14; [FieldOffset(15)] public byte Byte15; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/pricing/price_override_night.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 HOLMS.Types.Booking.Pricing { /// <summary>Holder for reflection information generated from booking/pricing/price_override_night.proto</summary> public static partial class PriceOverrideNightReflection { #region Descriptor /// <summary>File descriptor for booking/pricing/price_override_night.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PriceOverrideNightReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cipib29raW5nL3ByaWNpbmcvcHJpY2Vfb3ZlcnJpZGVfbmlnaHQucHJvdG8S", "G2hvbG1zLnR5cGVzLmJvb2tpbmcucHJpY2luZxodcHJpbWl0aXZlL3BiX2xv", "Y2FsX2RhdGUucHJvdG8aH3ByaW1pdGl2ZS9tb25ldGFyeV9hbW91bnQucHJv", "dG8aK2Jvb2tpbmcvcHJpY2luZy9wcmljZV9vdmVycmlkZV9hY3Rpb24ucHJv", "dG8ivgEKElByaWNlT3ZlcnJpZGVOaWdodBIwCgRkYXRlGAEgASgLMiIuaG9s", "bXMudHlwZXMucHJpbWl0aXZlLlBiTG9jYWxEYXRlEjQKBXByaWNlGAIgASgL", "MiUuaG9sbXMudHlwZXMucHJpbWl0aXZlLk1vbmV0YXJ5QW1vdW50EkAKBmFj", "dGlvbhgDIAEoDjIwLmhvbG1zLnR5cGVzLmJvb2tpbmcucHJpY2luZy5Qcmlj", "ZU92ZXJyaWRlQWN0aW9uQi9aD2Jvb2tpbmcvcHJpY2luZ6oCG0hPTE1TLlR5", "cGVzLkJvb2tpbmcuUHJpY2luZ2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Booking.Pricing.PriceOverrideActionReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Pricing.PriceOverrideNight), global::HOLMS.Types.Booking.Pricing.PriceOverrideNight.Parser, new[]{ "Date", "Price", "Action" }, null, null, null) })); } #endregion } #region Messages public sealed partial class PriceOverrideNight : pb::IMessage<PriceOverrideNight> { private static readonly pb::MessageParser<PriceOverrideNight> _parser = new pb::MessageParser<PriceOverrideNight>(() => new PriceOverrideNight()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PriceOverrideNight> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Pricing.PriceOverrideNightReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceOverrideNight() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceOverrideNight(PriceOverrideNight other) : this() { Date = other.date_ != null ? other.Date.Clone() : null; Price = other.price_ != null ? other.Price.Clone() : null; action_ = other.action_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceOverrideNight Clone() { return new PriceOverrideNight(this); } /// <summary>Field number for the "date" field.</summary> public const int DateFieldNumber = 1; private global::HOLMS.Types.Primitive.PbLocalDate date_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate Date { get { return date_; } set { date_ = value; } } /// <summary>Field number for the "price" field.</summary> public const int PriceFieldNumber = 2; private global::HOLMS.Types.Primitive.MonetaryAmount price_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount Price { get { return price_; } set { price_ = value; } } /// <summary>Field number for the "action" field.</summary> public const int ActionFieldNumber = 3; private global::HOLMS.Types.Booking.Pricing.PriceOverrideAction action_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Pricing.PriceOverrideAction Action { get { return action_; } set { action_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PriceOverrideNight); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PriceOverrideNight other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Date, other.Date)) return false; if (!object.Equals(Price, other.Price)) return false; if (Action != other.Action) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (date_ != null) hash ^= Date.GetHashCode(); if (price_ != null) hash ^= Price.GetHashCode(); if (Action != 0) hash ^= Action.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 (date_ != null) { output.WriteRawTag(10); output.WriteMessage(Date); } if (price_ != null) { output.WriteRawTag(18); output.WriteMessage(Price); } if (Action != 0) { output.WriteRawTag(24); output.WriteEnum((int) Action); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (date_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date); } if (price_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Price); } if (Action != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Action); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PriceOverrideNight other) { if (other == null) { return; } if (other.date_ != null) { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } Date.MergeFrom(other.Date); } if (other.price_ != null) { if (price_ == null) { price_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } Price.MergeFrom(other.Price); } if (other.Action != 0) { Action = other.Action; } } [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: { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(date_); break; } case 18: { if (price_ == null) { price_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(price_); break; } case 24: { action_ = (global::HOLMS.Types.Booking.Pricing.PriceOverrideAction) input.ReadEnum(); break; } } } } } #endregion } #endregion Designer generated code
using System.Drawing; using System.Collections.Generic; namespace GLPaintGameView { public class ShakeMe { public static List <PointF []> Data = new List <PointF []> () { new PointF [] { new PointF (62.000000f, 366.000000f), new PointF (52.000000f, 363.000000f), new PointF (44.000000f, 361.000000f), new PointF (37.000000f, 356.000000f), new PointF (29.000000f, 350.000000f), new PointF (24.000000f, 345.000000f), new PointF (23.000000f, 341.000000f), new PointF (23.000000f, 335.000000f), new PointF (47.000000f, 328.000000f), new PointF (59.000000f, 325.000000f), new PointF (70.000000f, 323.000000f), new PointF (74.000000f, 319.000000f), new PointF (75.000000f, 317.000000f), new PointF (71.000000f, 311.000000f), new PointF (59.000000f, 304.000000f), new PointF (41.000000f, 296.000000f), new PointF (20.000000f, 284.000000f), new PointF (16.000000f, 281.000000f), new PointF (15.000000f, 280.000000f), new PointF (14.000000f, 279.000000f), new PointF (14.000000f, 279.000000f), }, new PointF [] { new PointF (94.000000f, 352.000000f), new PointF (97.000000f, 337.000000f), new PointF (97.000000f, 328.000000f), new PointF (97.000000f, 315.000000f), new PointF (97.000000f, 304.000000f), new PointF (96.000000f, 297.000000f), new PointF (96.000000f, 293.000000f), new PointF (96.000000f, 290.000000f), new PointF (96.000000f, 289.000000f), new PointF (96.000000f, 289.000000f), }, new PointF [] { new PointF (84.000000f, 312.000000f), new PointF (93.000000f, 314.000000f), new PointF (98.000000f, 314.000000f), new PointF (104.000000f, 314.000000f), new PointF (109.000000f, 315.000000f), new PointF (113.000000f, 317.000000f), new PointF (118.000000f, 319.000000f), new PointF (118.000000f, 319.000000f), }, new PointF [] { new PointF (130.000000f, 352.000000f), new PointF (131.000000f, 338.000000f), new PointF (131.000000f, 330.000000f), new PointF (131.000000f, 318.000000f), new PointF (131.000000f, 307.000000f), new PointF (131.000000f, 298.000000f), new PointF (131.000000f, 292.000000f), new PointF (131.000000f, 292.000000f), }, new PointF [] { new PointF (149.000000f, 275.000000f), new PointF (151.000000f, 281.000000f), new PointF (151.000000f, 288.000000f), new PointF (152.000000f, 299.000000f), new PointF (155.000000f, 312.000000f), new PointF (163.000000f, 328.000000f), new PointF (171.000000f, 344.000000f), new PointF (177.000000f, 355.000000f), new PointF (182.000000f, 361.000000f), new PointF (186.000000f, 364.000000f), new PointF (189.000000f, 365.000000f), new PointF (191.000000f, 363.000000f), new PointF (192.000000f, 356.000000f), new PointF (193.000000f, 348.000000f), new PointF (194.000000f, 337.000000f), new PointF (194.000000f, 328.000000f), new PointF (194.000000f, 316.000000f), new PointF (194.000000f, 305.000000f), new PointF (194.000000f, 301.000000f), new PointF (190.000000f, 295.000000f), new PointF (190.000000f, 295.000000f), }, new PointF [] { new PointF (161.000000f, 321.000000f), new PointF (180.000000f, 323.000000f), new PointF (187.000000f, 324.000000f), new PointF (192.000000f, 325.000000f), new PointF (198.000000f, 325.000000f), new PointF (198.000000f, 325.000000f), }, new PointF [] { new PointF (219.000000f, 358.000000f), new PointF (219.000000f, 345.000000f), new PointF (219.000000f, 336.000000f), new PointF (219.000000f, 324.000000f), new PointF (218.000000f, 309.000000f), new PointF (216.000000f, 299.000000f), new PointF (215.000000f, 292.000000f), new PointF (215.000000f, 288.000000f), new PointF (215.000000f, 286.000000f), new PointF (215.000000f, 284.000000f), new PointF (215.000000f, 288.000000f), new PointF (217.000000f, 296.000000f), new PointF (223.000000f, 306.000000f), new PointF (229.000000f, 318.000000f), new PointF (235.000000f, 326.000000f), new PointF (241.000000f, 333.000000f), new PointF (246.000000f, 338.000000f), new PointF (249.000000f, 342.000000f), new PointF (253.000000f, 345.000000f), new PointF (255.000000f, 347.000000f), new PointF (257.000000f, 349.000000f), new PointF (258.000000f, 350.000000f), new PointF (259.000000f, 350.000000f), new PointF (259.000000f, 350.000000f), }, new PointF [] { new PointF (229.000000f, 318.000000f), new PointF (238.000000f, 311.000000f), new PointF (242.000000f, 311.000000f), new PointF (247.000000f, 310.000000f), new PointF (251.000000f, 308.000000f), new PointF (255.000000f, 306.000000f), new PointF (257.000000f, 305.000000f), new PointF (259.000000f, 304.000000f), new PointF (261.000000f, 302.000000f), new PointF (264.000000f, 299.000000f), new PointF (264.000000f, 299.000000f), }, new PointF [] { new PointF (284.000000f, 354.000000f), new PointF (282.000000f, 346.000000f), new PointF (282.000000f, 339.000000f), new PointF (280.000000f, 332.000000f), new PointF (277.000000f, 322.000000f), new PointF (274.000000f, 312.000000f), new PointF (273.000000f, 306.000000f), new PointF (273.000000f, 301.000000f), new PointF (273.000000f, 297.000000f), new PointF (273.000000f, 294.000000f), new PointF (274.000000f, 292.000000f), new PointF (278.000000f, 291.000000f), new PointF (283.000000f, 291.000000f), new PointF (293.000000f, 291.000000f), new PointF (297.000000f, 293.000000f), new PointF (301.000000f, 295.000000f), new PointF (306.000000f, 297.000000f), new PointF (308.000000f, 298.000000f), new PointF (309.000000f, 298.000000f), new PointF (309.000000f, 298.000000f), }, new PointF [] { new PointF (275.000000f, 323.000000f), new PointF (283.000000f, 324.000000f), new PointF (287.000000f, 324.000000f), new PointF (292.000000f, 324.000000f), new PointF (295.000000f, 325.000000f), new PointF (298.000000f, 325.000000f), new PointF (298.000000f, 325.000000f), }, new PointF [] { new PointF (283.000000f, 351.000000f), new PointF (295.000000f, 356.000000f), new PointF (302.000000f, 357.000000f), new PointF (308.000000f, 360.000000f), new PointF (312.000000f, 361.000000f), new PointF (312.000000f, 361.000000f), }, new PointF [] { new PointF (55.000000f, 165.000000f), new PointF (53.000000f, 158.000000f), new PointF (53.000000f, 147.000000f), new PointF (53.000000f, 136.000000f), new PointF (53.000000f, 127.000000f), new PointF (53.000000f, 120.000000f), new PointF (53.000000f, 114.000000f), new PointF (53.000000f, 110.000000f), new PointF (53.000000f, 109.000000f), new PointF (53.000000f, 108.000000f), new PointF (53.000000f, 109.000000f), new PointF (53.000000f, 115.000000f), new PointF (54.000000f, 131.000000f), new PointF (57.000000f, 159.000000f), new PointF (58.000000f, 177.000000f), new PointF (59.000000f, 189.000000f), new PointF (59.000000f, 196.000000f), new PointF (61.000000f, 201.000000f), new PointF (64.000000f, 200.000000f), new PointF (71.000000f, 194.000000f), new PointF (80.000000f, 189.000000f), new PointF (90.000000f, 185.000000f), new PointF (99.000000f, 184.000000f), new PointF (110.000000f, 184.000000f), new PointF (118.000000f, 189.000000f), new PointF (122.000000f, 193.000000f), new PointF (127.000000f, 198.000000f), new PointF (128.000000f, 198.000000f), new PointF (128.000000f, 191.000000f), new PointF (128.000000f, 179.000000f), new PointF (128.000000f, 161.000000f), new PointF (127.000000f, 143.000000f), new PointF (127.000000f, 127.000000f), new PointF (127.000000f, 114.000000f), new PointF (127.000000f, 106.000000f), new PointF (127.000000f, 100.000000f), new PointF (128.000000f, 99.000000f), new PointF (128.000000f, 99.000000f), }, new PointF [] { new PointF (175.000000f, 204.000000f), new PointF (172.000000f, 195.000000f), new PointF (172.000000f, 186.000000f), new PointF (171.000000f, 173.000000f), new PointF (170.000000f, 160.000000f), new PointF (169.000000f, 145.000000f), new PointF (168.000000f, 134.000000f), new PointF (166.000000f, 126.000000f), new PointF (165.000000f, 117.000000f), new PointF (165.000000f, 111.000000f), new PointF (165.000000f, 107.000000f), new PointF (170.000000f, 105.000000f), new PointF (179.000000f, 105.000000f), new PointF (188.000000f, 110.000000f), new PointF (198.000000f, 115.000000f), new PointF (208.000000f, 119.000000f), new PointF (216.000000f, 122.000000f), new PointF (221.000000f, 123.000000f), new PointF (227.000000f, 125.000000f), new PointF (227.000000f, 125.000000f), }, new PointF [] { new PointF (180.000000f, 149.000000f), new PointF (193.000000f, 152.000000f), new PointF (205.000000f, 154.000000f), new PointF (218.000000f, 158.000000f), new PointF (230.000000f, 164.000000f), new PointF (240.000000f, 170.000000f), new PointF (244.000000f, 175.000000f), new PointF (244.000000f, 175.000000f), }, new PointF [] { new PointF (177.000000f, 189.000000f), new PointF (191.000000f, 192.000000f), new PointF (205.000000f, 193.000000f), new PointF (219.000000f, 197.000000f), new PointF (232.000000f, 202.000000f), new PointF (241.000000f, 205.000000f), new PointF (249.000000f, 208.000000f), new PointF (249.000000f, 208.000000f), }, new PointF [] { new PointF (265.000000f, 239.000000f), new PointF (268.000000f, 227.000000f), new PointF (269.000000f, 215.000000f), new PointF (270.000000f, 198.000000f), new PointF (271.000000f, 178.000000f), new PointF (273.000000f, 160.000000f), new PointF (274.000000f, 150.000000f), new PointF (275.000000f, 142.000000f), new PointF (277.000000f, 133.000000f), new PointF (277.000000f, 133.000000f), }, new PointF [] { new PointF (283.000000f, 93.000000f), new PointF (283.000000f, 93.000000f), }, new PointF [] { new PointF (294.000000f, 87.000000f), new PointF (285.000000f, 81.000000f), new PointF (284.000000f, 81.000000f), new PointF (284.000000f, 80.000000f), new PointF (284.000000f, 79.000000f), new PointF (285.000000f, 80.000000f), new PointF (285.000000f, 82.000000f), new PointF (285.000000f, 83.000000f), new PointF (285.000000f, 84.000000f), new PointF (284.000000f, 84.000000f), new PointF (282.000000f, 84.000000f), new PointF (282.000000f, 83.000000f), new PointF (282.000000f, 82.000000f), new PointF (282.000000f, 82.000000f), } }; } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using NodaTime.Text; using NUnit.Framework; namespace NodaTime.Test { public class IntervalTest { private static readonly Instant SampleStart = NodaConstants.UnixEpoch.PlusNanoseconds(-30001); private static readonly Instant SampleEnd = NodaConstants.UnixEpoch.PlusNanoseconds(40001); [Test] public void Construction_Success() { var interval = new Interval(SampleStart, SampleEnd); Assert.AreEqual(SampleStart, interval.Start); Assert.AreEqual(SampleEnd, interval.End); } [Test] public void Construction_EqualStartAndEnd() { var interval = new Interval(SampleStart, SampleStart); Assert.AreEqual(SampleStart, interval.Start); Assert.AreEqual(SampleStart, interval.End); Assert.AreEqual(NodaTime.Duration.Zero, interval.Duration); } [Test] public void Construction_EndBeforeStart() { Assert.Throws<ArgumentOutOfRangeException>(() => new Interval(SampleEnd, SampleStart)); Assert.Throws<ArgumentOutOfRangeException>(() => new Interval((Instant?) SampleEnd, (Instant?) SampleStart)); } [Test] public void Equals() { TestHelper.TestEqualsStruct( new Interval(SampleStart, SampleEnd), new Interval(SampleStart, SampleEnd), new Interval(NodaConstants.UnixEpoch, SampleEnd)); TestHelper.TestEqualsStruct( new Interval(null, SampleEnd), new Interval(null, SampleEnd), new Interval(NodaConstants.UnixEpoch, SampleEnd)); TestHelper.TestEqualsStruct( new Interval(SampleStart, SampleEnd), new Interval(SampleStart, SampleEnd), new Interval(NodaConstants.UnixEpoch, SampleEnd)); TestHelper.TestEqualsStruct( new Interval(null, null), new Interval(null, null), new Interval(NodaConstants.UnixEpoch, SampleEnd)); } [Test] public void Operators() { TestHelper.TestOperatorEquality( new Interval(SampleStart, SampleEnd), new Interval(SampleStart, SampleEnd), new Interval(NodaConstants.UnixEpoch, SampleEnd)); } [Test] public void Duration() { var interval = new Interval(SampleStart, SampleEnd); Assert.AreEqual(NodaTime.Duration.FromNanoseconds(70002), interval.Duration); } /// <summary> /// Using the default constructor is equivalent to a zero duration. /// </summary> [Test] public void DefaultConstructor() { var actual = new Interval(); Assert.AreEqual(NodaTime.Duration.Zero, actual.Duration); } [Test] public void ToStringUsesExtendedIsoFormat() { var start = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789).InUtc().ToInstant(); var end = new LocalDateTime(2013, 10, 12, 17, 1, 2, 120).InUtc().ToInstant(); var value = new Interval(start, end); Assert.AreEqual("2013-04-12T17:53:23.123456789Z/2013-10-12T17:01:02.12Z", value.ToString()); } [Test] public void ToString_Infinite() { var value = new Interval(null, null); Assert.AreEqual("StartOfTime/EndOfTime", value.ToString()); } [Test] public void XmlSerialization() { var start = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789).InUtc().ToInstant(); var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(start, end); TestHelper.AssertXmlRoundtrip(value, "<value start=\"2013-04-12T17:53:23.123456789Z\" end=\"2013-10-12T17:01:02Z\" />"); } [Test] public void XmlSerialization_Extremes() { var value = new Interval(Instant.MinValue, Instant.MaxValue); TestHelper.AssertXmlRoundtrip(value, "<value start=\"-9998-01-01T00:00:00Z\" end=\"9999-12-31T23:59:59.999999999Z\" />"); } [Test] public void XmlSerialization_ExtraContent() { var start = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789).InUtc().ToInstant(); var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(start, end); TestHelper.AssertParsableXml(value, "<value start=\"2013-04-12T17:53:23.123456789Z\" end=\"2013-10-12T17:01:02Z\">Text<child attr=\"value\"/>Text 2</value>"); } [Test] public void XmlSerialization_SwapAttributeOrder() { var start = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789).InUtc().ToInstant(); var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(start, end); TestHelper.AssertParsableXml(value, "<value end=\"2013-10-12T17:01:02Z\" start=\"2013-04-12T17:53:23.123456789Z\" />"); } [Test] public void XmlSerialization_FromBeginningOfTime() { var end = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(null, end); TestHelper.AssertXmlRoundtrip(value, "<value end=\"2013-10-12T17:01:02Z\" />"); } [Test] public void XmlSerialization_ToEndOfTime() { var start = new LocalDateTime(2013, 10, 12, 17, 1, 2).InUtc().ToInstant(); var value = new Interval(start, null); TestHelper.AssertXmlRoundtrip(value, "<value start=\"2013-10-12T17:01:02Z\" />"); } [Test] public void XmlSerialization_AllOfTime() { var value = new Interval(null, null); TestHelper.AssertXmlRoundtrip(value, "<value />"); } [Test] [TestCase("<value start=\"2013-15-12T17:53:23Z\" end=\"2013-11-12T17:53:23Z\"/>", typeof(UnparsableValueException), Description = "Invalid month in start")] [TestCase("<value start=\"2013-11-12T17:53:23Z\" end=\"2013-15-12T17:53:23Z\"/>", typeof(UnparsableValueException), Description = "Invalid month in end")] [TestCase("<value start=\"2013-11-12T17:53:23Z\" end=\"2013-11-12T16:53:23Z\"/>", typeof(ArgumentOutOfRangeException), Description = "End before start")] public void XmlSerialization_Invalid(string xml, Type expectedExceptionType) { TestHelper.AssertXmlInvalid<Interval>(xml, expectedExceptionType); } [Test] [TestCase("1990-01-01T00:00:00Z", false, Description = "Before interval")] [TestCase("2000-01-01T00:00:00Z", true, Description = "Start of interval")] [TestCase("2010-01-01T00:00:00Z", true, Description = "Within interval")] [TestCase("2020-01-01T00:00:00Z", false, Description = "End instant of interval")] [TestCase("2030-01-01T00:00:00Z", false, Description = "After interval")] public void Contains(string candidateText, bool expectedResult) { var start = Instant.FromUtc(2000, 1, 1, 0, 0); var end = Instant.FromUtc(2020, 1, 1, 0, 0); var interval = new Interval(start, end); var candidate = InstantPattern.ExtendedIso.Parse(candidateText).Value; Assert.AreEqual(expectedResult, interval.Contains(candidate)); } [Test] public void Contains_Infinite() { var interval = new Interval(null, null); Assert.IsTrue(interval.Contains(Instant.MaxValue)); Assert.IsTrue(interval.Contains(Instant.MinValue)); } [Test] public void HasStart() { Assert.IsTrue(new Interval(Instant.MinValue, null).HasStart); Assert.IsFalse(new Interval(null, Instant.MinValue).HasStart); } [Test] public void HasEnd() { Assert.IsTrue(new Interval(null, Instant.MaxValue).HasEnd); Assert.IsFalse(new Interval(Instant.MaxValue, null).HasEnd); } [Test] public void Start() { Assert.AreEqual(NodaConstants.UnixEpoch, new Interval(NodaConstants.UnixEpoch, null).Start); Interval noStart = new Interval(null, NodaConstants.UnixEpoch); Assert.Throws<InvalidOperationException>(() => noStart.Start.ToString()); } [Test] public void End() { Assert.AreEqual(NodaConstants.UnixEpoch, new Interval(null, NodaConstants.UnixEpoch).End); Interval noEnd = new Interval(NodaConstants.UnixEpoch, null); Assert.Throws<InvalidOperationException>(() => noEnd.End.ToString()); } [Test] public void Contains_EmptyInterval() { var instant = NodaConstants.UnixEpoch; var interval = new Interval(instant, instant); Assert.IsFalse(interval.Contains(instant)); } [Test] public void Contains_EmptyInterval_MaxValue() { var instant = Instant.MaxValue; var interval = new Interval(instant, instant); // This would have been true under Noda Time 1.x Assert.IsFalse(interval.Contains(instant)); } [Test] public void Deconstruction() { var start = new Instant(); var end = start.PlusTicks(1_000_000); var value = new Interval(start, end); (Instant? actualStart, Instant? actualEnd) = value; Assert.Multiple(() => { Assert.AreEqual(start, actualStart); Assert.AreEqual(end, actualEnd); }); } [Test] public void Deconstruction_IntervalWithoutStart() { Instant? start = null; var end = new Instant(1500, 1_000_000); var value = new Interval(start, end); (Instant? actualStart, Instant? actualEnd) = value; Assert.Multiple(() => { Assert.AreEqual(start, actualStart); Assert.AreEqual(end, actualEnd); }); } [Test] public void Deconstruction_IntervalWithoutEnd() { var start = new Instant(1500, 1_000_000); Instant? end = null; var value = new Interval(start, end); (Instant? actualStart, Instant? actualEnd) = value; Assert.Multiple(() => { Assert.AreEqual(start, actualStart); Assert.AreEqual(end, actualEnd); }); } } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.IO; using System.Text; namespace Aphysoft.Share.Html { /// <summary> /// Represents a document with mixed code and text. ASP, ASPX, JSP, are good example of such documents. /// </summary> public class MixedCodeDocument { #region Fields private int _c; internal MixedCodeDocumentFragmentList _codefragments; private MixedCodeDocumentFragment _currentfragment; internal MixedCodeDocumentFragmentList _fragments; private int _index; private int _line; private int _lineposition; private ParseState _state; private Encoding _streamencoding; internal string _text; internal MixedCodeDocumentFragmentList _textfragments; /// <summary> /// Gets or sets the token representing code end. /// </summary> public string TokenCodeEnd = "%>"; /// <summary> /// Gets or sets the token representing code start. /// </summary> public string TokenCodeStart = "<%"; /// <summary> /// Gets or sets the token representing code directive. /// </summary> public string TokenDirective = "@"; /// <summary> /// Gets or sets the token representing response write directive. /// </summary> public string TokenResponseWrite = "Response.Write "; private string TokenTextBlock = "TextBlock({0})"; #endregion #region Constructors /// <summary> /// Creates a mixed code document instance. /// </summary> public MixedCodeDocument() { _codefragments = new MixedCodeDocumentFragmentList(this); _textfragments = new MixedCodeDocumentFragmentList(this); _fragments = new MixedCodeDocumentFragmentList(this); } #endregion #region Properties /// <summary> /// Gets the code represented by the mixed code document seen as a template. /// </summary> public string Code { get { string s = ""; int i = 0; foreach (MixedCodeDocumentFragment frag in _fragments) { switch (frag._type) { case MixedCodeDocumentFragmentType.Text: s += TokenResponseWrite + string.Format(TokenTextBlock, i) + "\n"; i++; break; case MixedCodeDocumentFragmentType.Code: s += ((MixedCodeDocumentCodeFragment) frag).Code + "\n"; break; } } return s; } } /// <summary> /// Gets the list of code fragments in the document. /// </summary> public MixedCodeDocumentFragmentList CodeFragments { get { return _codefragments; } } /// <summary> /// Gets the list of all fragments in the document. /// </summary> public MixedCodeDocumentFragmentList Fragments { get { return _fragments; } } /// <summary> /// Gets the encoding of the stream used to read the document. /// </summary> public Encoding StreamEncoding { get { return _streamencoding; } } /// <summary> /// Gets the list of text fragments in the document. /// </summary> public MixedCodeDocumentFragmentList TextFragments { get { return _textfragments; } } #endregion #region Public Methods /// <summary> /// Create a code fragment instances. /// </summary> /// <returns>The newly created code fragment instance.</returns> public MixedCodeDocumentCodeFragment CreateCodeFragment() { return (MixedCodeDocumentCodeFragment) CreateFragment(MixedCodeDocumentFragmentType.Code); } /// <summary> /// Create a text fragment instances. /// </summary> /// <returns>The newly created text fragment instance.</returns> public MixedCodeDocumentTextFragment CreateTextFragment() { return (MixedCodeDocumentTextFragment) CreateFragment(MixedCodeDocumentFragmentType.Text); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> public void Load(Stream stream) { Load(new StreamReader(stream)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(Stream stream, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(stream, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> public void Load(Stream stream, Encoding encoding) { Load(new StreamReader(stream, encoding)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, buffersize)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> public void Load(string path) { Load(new StreamReader(path)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(string path, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(path, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> public void Load(string path, Encoding encoding) { Load(new StreamReader(path, encoding)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public void Load(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) { Load(new StreamReader(path, encoding, detectEncodingFromByteOrderMarks)); } /// <summary> /// Loads a mixed code document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public void Load(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { Load(new StreamReader(path, encoding, detectEncodingFromByteOrderMarks, buffersize)); } /// <summary> /// Loads the mixed code document from the specified TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML data into the document.</param> public void Load(TextReader reader) { _codefragments.Clear(); _textfragments.Clear(); // all pseudo constructors get down to this one StreamReader sr = reader as StreamReader; if (sr != null) { _streamencoding = sr.CurrentEncoding; } _text = reader.ReadToEnd(); reader.Close(); Parse(); } /// <summary> /// Loads a mixed document from a text /// </summary> /// <param name="html">The text to load.</param> public void LoadHtml(string html) { Load(new StringReader(html)); } /// <summary> /// Saves the mixed document to the specified stream. /// </summary> /// <param name="outStream">The stream to which you want to save.</param> public void Save(Stream outStream) { StreamWriter sw = new StreamWriter(outStream, GetOutEncoding()); Save(sw); } /// <summary> /// Saves the mixed document to the specified stream. /// </summary> /// <param name="outStream">The stream to which you want to save.</param> /// <param name="encoding">The character encoding to use.</param> public void Save(Stream outStream, Encoding encoding) { StreamWriter sw = new StreamWriter(outStream, encoding); Save(sw); } /// <summary> /// Saves the mixed document to the specified file. /// </summary> /// <param name="filename">The location of the file where you want to save the document.</param> public void Save(string filename) { StreamWriter sw = new StreamWriter(filename, false, GetOutEncoding()); Save(sw); } /// <summary> /// Saves the mixed document to the specified file. /// </summary> /// <param name="filename">The location of the file where you want to save the document.</param> /// <param name="encoding">The character encoding to use.</param> public void Save(string filename, Encoding encoding) { StreamWriter sw = new StreamWriter(filename, false, encoding); Save(sw); } /// <summary> /// Saves the mixed document to the specified StreamWriter. /// </summary> /// <param name="writer">The StreamWriter to which you want to save.</param> public void Save(StreamWriter writer) { Save((TextWriter) writer); } /// <summary> /// Saves the mixed document to the specified TextWriter. /// </summary> /// <param name="writer">The TextWriter to which you want to save.</param> public void Save(TextWriter writer) { writer.Flush(); } #endregion #region Internal Methods internal MixedCodeDocumentFragment CreateFragment(MixedCodeDocumentFragmentType type) { switch (type) { case MixedCodeDocumentFragmentType.Text: return new MixedCodeDocumentTextFragment(this); case MixedCodeDocumentFragmentType.Code: return new MixedCodeDocumentCodeFragment(this); default: throw new NotSupportedException(); } } internal Encoding GetOutEncoding() { if (_streamencoding != null) return _streamencoding; return Encoding.Default; } #endregion #region Private Methods private void IncrementPosition() { _index++; if (_c == 10) { _lineposition = 1; _line++; } else _lineposition++; } private void Parse() { _state = ParseState.Text; _index = 0; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Text); while (_index < _text.Length) { _c = _text[_index]; IncrementPosition(); switch (_state) { case ParseState.Text: if (_index + TokenCodeStart.Length < _text.Length) { if (_text.Substring(_index - 1, TokenCodeStart.Length) == TokenCodeStart) { _state = ParseState.Code; _currentfragment.Length = _index - 1 - _currentfragment.Index; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Code); SetPosition(); continue; } } break; case ParseState.Code: if (_index + TokenCodeEnd.Length < _text.Length) { if (_text.Substring(_index - 1, TokenCodeEnd.Length) == TokenCodeEnd) { _state = ParseState.Text; _currentfragment.Length = _index + TokenCodeEnd.Length - _currentfragment.Index; _index += TokenCodeEnd.Length; _lineposition += TokenCodeEnd.Length; _currentfragment = CreateFragment(MixedCodeDocumentFragmentType.Text); SetPosition(); continue; } } break; } } _currentfragment.Length = _index - _currentfragment.Index; } private void SetPosition() { _currentfragment.Line = _line; _currentfragment._lineposition = _lineposition; _currentfragment.Index = _index - 1; _currentfragment.Length = 0; } #endregion #region Nested type: ParseState private enum ParseState { Text, Code } #endregion } }
// // Puller.cs // // Author: // Zachary Gramana <[email protected]> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Storage; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; using System.Threading.Tasks; using System.Net.Http; using System.Diagnostics; using System.Web; using System.Linq; using Newtonsoft.Json.Linq; namespace Couchbase.Lite.Replicator { internal class Puller : Replication, IChangeTrackerClient { private const int MaxOpenHttpConnections = 16; readonly string Tag = "Puller"; protected internal Batcher<IList<Object>> downloadsToInsert; protected internal IList<RevisionInternal> revsToPull; protected internal ChangeTracker changeTracker; protected internal SequenceMap pendingSequences; protected internal volatile int httpConnectionCount; private readonly Object locker = new object (); /// <summary>Constructor</summary> internal Puller(Database db, Uri remote, bool continuous, TaskFactory workExecutor) : this(db, remote, continuous, null, workExecutor) { } /// <summary>Constructor</summary> internal Puller(Database db, Uri remote, bool continuous, IHttpClientFactory clientFactory, TaskFactory workExecutor) : base(db, remote, continuous, clientFactory, workExecutor) { } #region implemented abstract members of Replication public HttpClientHandler HttpHandler { get { return clientFactory.HttpHandler; } } public override IEnumerable<string> Channels { get; set; } public override IEnumerable<string> DocIds { get; set; } public override Dictionary<string, string> Headers { get; set; } #endregion public override bool IsPull { get { return true; } } public override bool CreateTarget { get { return false; } set { return; /* No-op intended. Only used in Pusher. */ } } internal override void BeginReplicating() { if (downloadsToInsert == null) { const int capacity = 200; const int delay = 1000; downloadsToInsert = new Batcher<IList<Object>> (WorkExecutor, capacity, delay, InsertRevisions); } pendingSequences = new SequenceMap(); Log.W(Tag, this + ": starting ChangeTracker with since=" + LastSequence); var mode = Continuous ? ChangeTracker.ChangeTrackerMode.LongPoll : ChangeTracker.ChangeTrackerMode.OneShot; changeTracker = new ChangeTracker(RemoteUrl, mode, LastSequence, true, this); Log.W(Tag, this + ": started ChangeTracker " + changeTracker); if (Filter != null) { changeTracker.SetFilterName(Filter); if (FilterParams != null) { changeTracker.SetFilterParams(FilterParams.ToDictionary(kvp=>kvp.Key, kvp=>(Object)kvp.Value)); } } if (!continuous) { AsyncTaskStarted(); } changeTracker.Start(); } public override void Stop() { if (!IsRunning) { return; } if (changeTracker != null) { Log.D(Tag, this + ": stopping changetracker " + changeTracker); changeTracker.SetClient(null); // stop it from calling my changeTrackerStopped() changeTracker.Stop(); changeTracker = null; if (!Continuous) { Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": stop() calling asyncTaskFinished()"); AsyncTaskFinished(1); } } // balances asyncTaskStarted() in beginReplicating() lock (locker) { revsToPull = null; } base.Stop(); } internal override void Stopped() { if (downloadsToInsert != null) { downloadsToInsert.Flush(); //downloadsToInsert = null; } base.Stopped(); } // Got a _changes feed entry from the ChangeTracker. public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { var lastSequence = change.Get("seq").ToString(); var docID = (string)change.Get("id"); if (docID == null) { return; } if (!LocalDatabase.IsValidDocumentId(docID)) { Log.W(Tag, string.Format("{0}: Received invalid doc ID from _changes: {1}", this, change)); return; } var deleted = (change.ContainsKey("deleted") && ((bool)change.Get("deleted")).Equals(true)); var changesContainer = change.Get("changes") as JContainer; var changes = changesContainer.ToArray(); foreach (var changeObj in changes) { var changeDict = changeObj.ToObject<IDictionary<string, object>>(); var revID = (string)changeDict.Get("rev"); if (revID == null) { continue; } var rev = new PulledRevision(docID, revID, deleted, LocalDatabase); rev.SetRemoteSequenceID(lastSequence); Log.D(Tag, this + ": adding rev to inbox " + rev); AddToInbox(rev); } ChangesCount = ChangesCount + changes.Length; while (revsToPull != null && revsToPull.Count > 1000) { try { Sharpen.Thread.Sleep(500); } catch (Exception) { // swallow } } } // <-- TODO: why is this here? public void ChangeTrackerStopped(ChangeTracker tracker) { Log.W(Tag, this + ": ChangeTracker " + tracker + " stopped"); if (LastError == null && tracker.GetLastError() != null) { LastError = tracker.GetLastError(); } changeTracker = null; if (Batcher != null) { Log.D(Tag, this + ": calling batcher.flush(). batcher.count() is " + Batcher.Count()); Batcher.Flush(); } if (!Continuous) { var t = Task.Factory.StartNew(() => { Task inner =Task.Factory.StartNew(() => {}); return inner; }); WorkExecutor.StartNew(() => { AsyncTaskFinished(1); }); } } public HttpClient GetHttpClient() { return clientFactory.GetHttpClient(); } /// <summary>Process a bunch of remote revisions from the _changes feed at once</summary> internal override void ProcessInbox(RevisionList inbox) { Debug.Assert(inbox != null); // Ask the local database which of the revs are not known to it: //Log.w(Database.TAG, String.format("%s: Looking up %s", this, inbox)); var lastInboxSequence = ((PulledRevision)inbox[inbox.Count - 1]).GetRemoteSequenceID (); var total = ChangesCount - inbox.Count; if (!LocalDatabase.FindMissingRevisions(inbox)) { Log.W(Tag, string.Format("{0} failed to look up local revs", this)); inbox = null; } //introducing this to java version since inbox may now be null everywhere var inboxCount = 0; if (inbox != null) { inboxCount = inbox.Count; } ChangesCount = total + inboxCount; if (inboxCount == 0) { // Nothing to do. Just bump the lastSequence. Log.W(Tag, string.Format("{0} no new remote revisions to fetch", this)); var seq = pendingSequences.AddValue(lastInboxSequence); pendingSequences.RemoveSequence(seq); LastSequence = pendingSequences.GetCheckpointedValue(); return; } Log.V(Tag, this + " fetching " + inboxCount + " remote revisions..."); //Log.v(Database.TAG, String.format("%s fetching remote revisions %s", this, inbox)); // Dump the revs into the queue of revs to pull from the remote db: lock (locker) { if (revsToPull == null) { revsToPull = new AList<RevisionInternal> (200); } for (int i = 0; i < inbox.Count; i++) { var rev = (PulledRevision)inbox [i]; // FIXME add logic here to pull initial revs in bulk rev.SetSequence (pendingSequences.AddValue (rev.GetRemoteSequenceID ())); revsToPull.AddItem (rev); } } PullRemoteRevisions(); } /// <summary> /// Start up some HTTP GETs, within our limit on the maximum simultaneous number /// The entire method is not synchronized, only the portion pulling work off the list /// Important to not hold the synchronized block while we do network access /// </summary> public void PullRemoteRevisions() { Log.D(Tag, this + ": pullRemoteRevisions() with revsToPull size: " + revsToPull.Count); //find the work to be done in a synchronized block var workToStartNow = new AList<RevisionInternal>(); lock (locker) { while (httpConnectionCount + workToStartNow.Count < MaxOpenHttpConnections && revsToPull != null && revsToPull.Count > 0) { var work = revsToPull.Remove(0); Log.D(Tag, this + ": add " + work + " to workToStartNow"); workToStartNow.AddItem(work); } } //actually run it outside the synchronized block foreach (var rev in workToStartNow) { PullRemoteRevision(rev); } } /// <summary>Fetches the contents of a revision from the remote db, including its parent revision ID. /// </summary> /// <remarks> /// Fetches the contents of a revision from the remote db, including its parent revision ID. /// The contents are stored into rev.properties. /// </remarks> internal void PullRemoteRevision(RevisionInternal rev) { Log.D(Tag, this + "|" + Thread.CurrentThread() + ": pullRemoteRevision with rev: " + rev); Log.D(Tag, this + "|" + Thread.CurrentThread() + ": pullRemoteRevision() calling asyncTaskStarted()"); AsyncTaskStarted(); httpConnectionCount++; // Construct a query. We want the revision history, and the bodies of attachments that have // been added since the latest revisions we have locally. // See: http://wiki.apache.org/couchdb/HTTP_Document_API#Getting_Attachments_With_a_Document var path = new StringBuilder("/" + HttpUtility.UrlEncode(rev.GetDocId()) + "?rev=" + HttpUtility.UrlEncode(rev.GetRevId()) + "&revs=true&attachments=true"); var knownRevs = KnownCurrentRevIDs(rev); if (knownRevs == null) { //this means something is wrong, possibly the replicator has shut down Log.D(Tag, this + "|" + Thread.CurrentThread() + ": pullRemoteRevision() calling asyncTaskFinished()"); AsyncTaskFinished(1); httpConnectionCount--; return; } if (knownRevs.Count > 0) { path.Append("&atts_since="); path.Append(JoinQuotedEscaped(knownRevs)); } //create a final version of this variable for the log statement inside //FIXME find a way to avoid this var pathInside = path.ToString(); SendAsyncMultipartDownloaderRequest(HttpMethod.Get, pathInside, null, LocalDatabase, (result, e) => { try { // OK, now we've got the response revision: Log.D (Tag, this + ": pullRemoteRevision got response for rev: " + rev); if (result != null) { var properties = ((JObject)result).ToObject<IDictionary<string, object>>(); var history = Database.ParseCouchDBRevisionHistory (properties); if (history != null) { rev.SetProperties (properties); // Add to batcher ... eventually it will be fed to -insertRevisions:. var toInsert = new AList<object> (); toInsert.AddItem (rev); toInsert.AddItem (history); Log.D (Tag, this + ": pullRemoteRevision add rev: " + rev + " to batcher"); downloadsToInsert.QueueObject (toInsert); Log.D (Tag, this + "|" + Thread.CurrentThread() + ": pullRemoteRevision.onCompletion() calling asyncTaskStarted()"); AsyncTaskStarted (); } else { Log.W (Tag, this + ": Missing revision history in response from " + pathInside); CompletedChangesCount += 1; } } else { if (e != null) { Log.E (Tag, "Error pulling remote revision", e); LastError = e; } CompletedChangesCount += 1; } } finally { Log.D (Tag, this + "|" + Thread.CurrentThread() + ": pullRemoteRevision.onCompletion() calling asyncTaskFinished()"); AsyncTaskFinished (1); } // Note that we've finished this task; then start another one if there // are still revisions waiting to be pulled: --httpConnectionCount; PullRemoteRevisions (); }); } /// <summary>This will be called when _revsToInsert fills up:</summary> public void InsertRevisions(IList<IList<Object>> revs) { Log.I(Tag, this + " inserting " + revs.Count + " revisions..."); //Log.v(Database.TAG, String.format("%s inserting %s", this, revs)); revs.Sort(new RevisionComparer()); if (LocalDatabase == null) { AsyncTaskFinished(revs.Count); return; } LocalDatabase.BeginTransaction(); var success = false; try { foreach (var revAndHistory in revs) { var rev = (PulledRevision)revAndHistory[0]; var fakeSequence = rev.GetSequence(); var history = (IList<String>)revAndHistory[1]; // Insert the revision: try { LocalDatabase.ForceInsert(rev, history, RemoteUrl); } catch (CouchbaseLiteException e) { if (e.GetCBLStatus().GetCode() == StatusCode.Forbidden) { Log.I(Tag, this + ": Remote rev failed validation: " + rev); } else { Log.W(Tag, this + " failed to write " + rev + ": status=" + e.GetCBLStatus().GetCode()); LastError = new HttpException((Int32)e.GetCBLStatus().GetCode(), null); continue; } } pendingSequences.RemoveSequence(fakeSequence); } Log.W(Tag, this + " finished inserting " + revs.Count + " revisions"); LastSequence = pendingSequences.GetCheckpointedValue(); success = true; } catch (SQLException e) { Log.E(Tag, this + ": Exception inserting revisions", e); } finally { LocalDatabase.EndTransaction(success); Log.D(Tag, this + "|" + Thread.CurrentThread() + ": insertRevisions() calling asyncTaskFinished()"); AsyncTaskFinished(revs.Count); } CompletedChangesCount += revs.Count; } private sealed class RevisionComparer : IComparer<IList<Object>> { public RevisionComparer() { } public int Compare(IList<Object> list1, IList<Object> list2) { var reva = (RevisionInternal)list1[0]; var revb = (RevisionInternal)list2[0]; return Misc.TDSequenceCompare(reva.GetSequence(), revb.GetSequence()); } } private IList<String> KnownCurrentRevIDs(RevisionInternal rev) { if (LocalDatabase != null) { return LocalDatabase.GetAllRevisionsOfDocumentID(rev.GetDocId(), true).GetAllRevIds(); } return null; } public string JoinQuotedEscaped(IList<string> strings) { if (strings.Count == 0) { return "[]"; } IEnumerable<Byte> json = null; try { json = Manager.GetObjectMapper().WriteValueAsBytes(strings); } catch (Exception e) { Log.W(Tag, "Unable to serialize json", e); } return HttpUtility.UrlEncode(Runtime.GetStringForBytes(json)); } public Boolean GoOffline() { Log.D(Tag, this + " goOffline() called, stopping changeTracker: " + changeTracker); if (!base.GoOffline()) { return false; } if (changeTracker != null) { changeTracker.Stop(); } return true; } } }
// Copyright (c) 2017 Yoshifumi Kawai // 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.Linq; using System.Reflection; using System.Reflection.Emit; namespace MessagePack.Internal { internal struct ArgumentField { private readonly int i; private readonly bool @ref; private readonly ILGenerator il; public ArgumentField(ILGenerator il, int i, bool @ref = false) { this.il = il; this.i = i; this.@ref = @ref; } public ArgumentField(ILGenerator il, int i, Type type) { this.il = il; this.i = i; TypeInfo ti = type.GetTypeInfo(); this.@ref = (ti.IsClass || ti.IsInterface || ti.IsAbstract) ? false : true; } public void EmitLoad() { if (this.@ref) { this.il.EmitLdarga(this.i); } else { this.il.EmitLdarg(this.i); } } public void EmitLdarg() { this.il.EmitLdarg(this.i); } public void EmitLdarga() { this.il.EmitLdarga(this.i); } public void EmitStore() { this.il.EmitStarg(this.i); } } /// <summary> /// Provides optimized generation code and helpers. /// </summary> internal static class ILGeneratorExtensions { /// <summary> /// Loads the local variable at a specific index onto the evaluation stack. /// </summary> public static void EmitLdloc(this ILGenerator il, int index) { switch (index) { case 0: il.Emit(OpCodes.Ldloc_0); break; case 1: il.Emit(OpCodes.Ldloc_1); break; case 2: il.Emit(OpCodes.Ldloc_2); break; case 3: il.Emit(OpCodes.Ldloc_3); break; default: if (index <= 255) { il.Emit(OpCodes.Ldloc_S, (byte)index); } else { il.Emit(OpCodes.Ldloc, (short)index); } break; } } public static void EmitLdloc(this ILGenerator il, LocalBuilder local) { EmitLdloc(il, local.LocalIndex); } /// <summary> /// Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index. /// </summary> public static void EmitStloc(this ILGenerator il, int index) { switch (index) { case 0: il.Emit(OpCodes.Stloc_0); break; case 1: il.Emit(OpCodes.Stloc_1); break; case 2: il.Emit(OpCodes.Stloc_2); break; case 3: il.Emit(OpCodes.Stloc_3); break; default: if (index <= 255) { il.Emit(OpCodes.Stloc_S, (byte)index); } else { il.Emit(OpCodes.Stloc, (short)index); } break; } } public static void EmitStloc(this ILGenerator il, LocalBuilder local) { EmitStloc(il, local.LocalIndex); } /// <summary> /// Loads the address of the local variable at a specific index onto the evaluation statck. /// </summary> public static void EmitLdloca(this ILGenerator il, int index) { if (index <= 255) { il.Emit(OpCodes.Ldloca_S, (byte)index); } else { il.Emit(OpCodes.Ldloca, (short)index); } } public static void EmitLdloca(this ILGenerator il, LocalBuilder local) { EmitLdloca(il, local.LocalIndex); } public static void EmitTrue(this ILGenerator il) { EmitBoolean(il, true); } public static void EmitFalse(this ILGenerator il) { EmitBoolean(il, false); } public static void EmitBoolean(this ILGenerator il, bool value) { EmitLdc_I4(il, value ? 1 : 0); } /// <summary> /// Pushes a supplied value of type int32 onto the evaluation stack as an int32. /// </summary> public static void EmitLdc_I4(this ILGenerator il, int value) { switch (value) { case -1: il.Emit(OpCodes.Ldc_I4_M1); break; case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; default: if (value >= -128 && value <= 127) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } break; } } public static void EmitUnboxOrCast(this ILGenerator il, Type type) { if (type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Unbox_Any, type); } else { il.Emit(OpCodes.Castclass, type); } } public static void EmitBoxOrDoNothing(this ILGenerator il, Type type) { if (type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Box, type); } } public static void EmitLdarg(this ILGenerator il, int index) { switch (index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (index <= 255) { il.Emit(OpCodes.Ldarg_S, (byte)index); } else { il.Emit(OpCodes.Ldarg, index); } break; } } public static void EmitLoadThis(this ILGenerator il) { EmitLdarg(il, 0); } public static void EmitLdarga(this ILGenerator il, int index) { if (index <= 255) { il.Emit(OpCodes.Ldarga_S, (byte)index); } else { il.Emit(OpCodes.Ldarga, index); } } public static void EmitStarg(this ILGenerator il, int index) { if (index <= 255) { il.Emit(OpCodes.Starg_S, (byte)index); } else { il.Emit(OpCodes.Starg, index); } } /// <summary> /// Helper for Pop op. /// </summary> public static void EmitPop(this ILGenerator il, int count) { for (int i = 0; i < count; i++) { il.Emit(OpCodes.Pop); } } public static void EmitCall(this ILGenerator il, MethodInfo methodInfo) { if (methodInfo.IsFinal || !methodInfo.IsVirtual) { il.Emit(OpCodes.Call, methodInfo); } else { il.Emit(OpCodes.Callvirt, methodInfo); } } public static void EmitLdfld(this ILGenerator il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldfld, fieldInfo); } public static void EmitLdsfld(this ILGenerator il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldsfld, fieldInfo); } public static void EmitRet(this ILGenerator il) { il.Emit(OpCodes.Ret); } public static void EmitIntZeroReturn(this ILGenerator il) { il.EmitLdc_I4(0); il.Emit(OpCodes.Ret); } public static void EmitNullReturn(this ILGenerator il) { il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Ret); } public static void EmitULong(this ILGenerator il, ulong value) { il.Emit(OpCodes.Ldc_I8, unchecked((long)value)); } public static void EmitThrowNotimplemented(this ILGenerator il) { il.Emit(OpCodes.Newobj, typeof(System.NotImplementedException).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0)); il.Emit(OpCodes.Throw); } /// <summary>for var i = 0, i ..., i++. </summary> public static void EmitIncrementFor(this ILGenerator il, LocalBuilder conditionGreater, Action<LocalBuilder> emitBody) { Label loopBegin = il.DefineLabel(); Label condtionLabel = il.DefineLabel(); // var i = 0 LocalBuilder forI = il.DeclareLocal(typeof(int)); il.EmitLdc_I4(0); il.EmitStloc(forI); il.Emit(OpCodes.Br, condtionLabel); il.MarkLabel(loopBegin); emitBody(forI); // i++ il.EmitLdloc(forI); il.EmitLdc_I4(1); il.Emit(OpCodes.Add); il.EmitStloc(forI); //// i < *** il.MarkLabel(condtionLabel); il.EmitLdloc(forI); il.EmitLdloc(conditionGreater); il.Emit(OpCodes.Blt, loopBegin); } } }
namespace SharpLib.Audio { internal enum Manufacturers { Microsoft = 1, Creative = 2, Mediavision = 3, Fujitsu = 4, Artisoft = 20, TurtleBeach = 21, Ibm = 22, Vocaltec = 23, Roland = 24, DspSolutions = 25, Nec = 26, Ati = 27, Wanglabs = 28, Tandy = 29, Voyetra = 30, Antex = 31, IclPS = 32, Intel = 33, Gravis = 34, Val = 35, Interactive = 36, Yamaha = 37, Everex = 38, Echo = 39, Sierra = 40, Cat = 41, Apps = 42, DspGroup = 43, Melabs = 44, ComputerFriends = 45, Ess = 46, Audiofile = 47, Motorola = 48, Canopus = 49, Epson = 50, Truevision = 51, Aztech = 52, Videologic = 53, Scalacs = 54, Korg = 55, Apt = 56, Ics = 57, Iteratedsys = 58, Metheus = 59, Logitech = 60, Winnov = 61, Ncr = 62, Exan = 63, Ast = 64, Willowpond = 65, Sonicfoundry = 66, Vitec = 67, Moscom = 68, Siliconsoft = 69, Supermac = 73, Audiopt = 74, Speechcomp = 76, Ahead = 77, Dolby = 78, Oki = 79, Auravision = 80, Olivetti = 81, Iomagic = 82, Matsushita = 83, Controlres = 84, Xebec = 85, Newmedia = 86, Nms = 87, Lyrrus = 88, Compusic = 89, Opti = 90, Adlacc = 91, Compaq = 92, Dialogic = 93, Insoft = 94, Mptus = 95, Weitek = 96, LernoutAndHauspie = 97, Qciar = 98, Apple = 99, Digital = 100, Motu = 101, Workbit = 102, Ositech = 103, Miro = 104, Cirruslogic = 105, Isolution = 106, Horizons = 107, Concepts = 108, Vtg = 109, Radius = 110, Rockwell = 111, Xyz = 112, Opcode = 113, Voxware = 114, NorthernTelecom = 115, Apicom = 116, Grande = 117, Addx = 118, Wildcat = 119, Rhetorex = 120, Brooktree = 121, Ensoniq = 125, Fast = 126, Nvidia = 127, Oksori = 128, Diacoustics = 129, Gulbransen = 130, KayElemetrics = 131, Crystal = 132, SplashStudios = 133, Quarterdeck = 134, Tdk = 135, DigitalAudioLabs = 136, Seersys = 137, Picturetel = 138, AttMicroelectronics = 139, Osprey = 140, Mediatrix = 141, Soundesigns = 142, Aldigital = 143, SpectrumSignalProcessing = 144, Ecs = 145, Amd = 146, Coredynamics = 147, Canam = 148, Softsound = 149, Norris = 150, Ddd = 151, Euphonics = 152, Precept = 153, CrystalNet = 154, Chromatic = 155, Voiceinfo = 156, Viennasys = 157, Connectix = 158, Gadgetlabs = 159, Frontier = 160, Viona = 161, Casio = 162, Diamondmm = 163, S3 = 164, FraunhoferIis = 172, } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace EditingUsingCustomForm { partial class EditorForm { /// <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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditorForm)); this.cmdModify = new System.Windows.Forms.Button(); this.cmdReshape = new System.Windows.Forms.Button(); this.cmdCreate = new System.Windows.Forms.Button(); this.panel1 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.txtInfo = new System.Windows.Forms.TextBox(); this.cmdEdit = new System.Windows.Forms.Button(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.axModifyToolbar = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axReshapeToolbar = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axBlankToolBar = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axUndoRedoToolbar = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.axCreateToolbar = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axModifyToolbar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axReshapeToolbar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axBlankToolBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axUndoRedoToolbar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axCreateToolbar)).BeginInit(); this.SuspendLayout(); // // cmdModify // this.cmdModify.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmdModify.Location = new System.Drawing.Point(8, 44); this.cmdModify.Name = "cmdModify"; this.cmdModify.Size = new System.Drawing.Size(110, 32); this.cmdModify.TabIndex = 1; this.cmdModify.Text = "Modify"; this.cmdModify.UseVisualStyleBackColor = true; this.cmdModify.Click += new System.EventHandler(this.cmdModify_Click); // // cmdReshape // this.cmdReshape.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmdReshape.Location = new System.Drawing.Point(8, 83); this.cmdReshape.Name = "cmdReshape"; this.cmdReshape.Size = new System.Drawing.Size(110, 30); this.cmdReshape.TabIndex = 2; this.cmdReshape.Text = "Reshape"; this.cmdReshape.UseVisualStyleBackColor = true; this.cmdReshape.Click += new System.EventHandler(this.cmdReshape_Click); // // cmdCreate // this.cmdCreate.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmdCreate.Location = new System.Drawing.Point(8, 6); this.cmdCreate.Name = "cmdCreate"; this.cmdCreate.Size = new System.Drawing.Size(110, 31); this.cmdCreate.TabIndex = 4; this.cmdCreate.Text = "Create"; this.cmdCreate.UseVisualStyleBackColor = true; this.cmdCreate.Click += new System.EventHandler(this.cmdCreate_Click); // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.flowLayoutPanel2); this.panel1.Controls.Add(this.txtInfo); this.panel1.Controls.Add(this.cmdEdit); this.panel1.Controls.Add(this.flowLayoutPanel1); this.panel1.Controls.Add(this.cmdCreate); this.panel1.Controls.Add(this.cmdReshape); this.panel1.Controls.Add(this.cmdModify); this.panel1.Location = new System.Drawing.Point(2, 6); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(228, 160); this.panel1.TabIndex = 5; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.Red; this.label1.Location = new System.Drawing.Point(124, 134); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(51, 16); this.label1.TabIndex = 15; this.label1.Text = "label1"; // // flowLayoutPanel2 // this.flowLayoutPanel2.Location = new System.Drawing.Point(124, 38); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; this.flowLayoutPanel2.Size = new System.Drawing.Size(95, 30); this.flowLayoutPanel2.TabIndex = 14; // // txtInfo // this.txtInfo.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.txtInfo.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtInfo.Location = new System.Drawing.Point(124, 67); this.txtInfo.Multiline = true; this.txtInfo.Name = "txtInfo"; this.txtInfo.Size = new System.Drawing.Size(99, 59); this.txtInfo.TabIndex = 13; // // cmdEdit // this.cmdEdit.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmdEdit.Location = new System.Drawing.Point(8, 120); this.cmdEdit.Name = "cmdEdit"; this.cmdEdit.Size = new System.Drawing.Size(110, 32); this.cmdEdit.TabIndex = 8; this.cmdEdit.Text = "Edit"; this.cmdEdit.UseVisualStyleBackColor = true; this.cmdEdit.Click += new System.EventHandler(this.cmdEdit_Click); // // flowLayoutPanel1 // this.flowLayoutPanel1.Location = new System.Drawing.Point(124, 6); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(95, 33); this.flowLayoutPanel1.TabIndex = 10; // // axModifyToolbar // this.axModifyToolbar.Location = new System.Drawing.Point(290, 93); this.axModifyToolbar.Name = "axModifyToolbar"; this.axModifyToolbar.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axModifyToolbar.OcxState"))); this.axModifyToolbar.Size = new System.Drawing.Size(221, 28); this.axModifyToolbar.TabIndex = 6; this.axModifyToolbar.OnItemClick += new ESRI.ArcGIS.Controls.IToolbarControlEvents_Ax_OnItemClickEventHandler(this.axModifyToolbar_OnItemClick); // // axReshapeToolbar // this.axReshapeToolbar.Location = new System.Drawing.Point(289, 183); this.axReshapeToolbar.Name = "axReshapeToolbar"; this.axReshapeToolbar.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axReshapeToolbar.OcxState"))); this.axReshapeToolbar.Size = new System.Drawing.Size(222, 28); this.axReshapeToolbar.TabIndex = 7; this.axReshapeToolbar.OnItemClick += new ESRI.ArcGIS.Controls.IToolbarControlEvents_Ax_OnItemClickEventHandler(this.axReshapeToolbar_OnItemClick); // // axBlankToolBar // this.axBlankToolBar.Location = new System.Drawing.Point(290, 55); this.axBlankToolBar.Name = "axBlankToolBar"; this.axBlankToolBar.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axBlankToolBar.OcxState"))); this.axBlankToolBar.Size = new System.Drawing.Size(221, 28); this.axBlankToolBar.TabIndex = 9; // // axUndoRedoToolbar // this.axUndoRedoToolbar.Location = new System.Drawing.Point(290, 127); this.axUndoRedoToolbar.Name = "axUndoRedoToolbar"; this.axUndoRedoToolbar.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axUndoRedoToolbar.OcxState"))); this.axUndoRedoToolbar.Size = new System.Drawing.Size(221, 28); this.axUndoRedoToolbar.TabIndex = 10; // // axCreateToolbar // this.axCreateToolbar.Location = new System.Drawing.Point(290, 18); this.axCreateToolbar.Name = "axCreateToolbar"; this.axCreateToolbar.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axCreateToolbar.OcxState"))); this.axCreateToolbar.Size = new System.Drawing.Size(221, 28); this.axCreateToolbar.TabIndex = 12; // // EditorForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.ClientSize = new System.Drawing.Size(532, 265); this.Controls.Add(this.axCreateToolbar); this.Controls.Add(this.axUndoRedoToolbar); this.Controls.Add(this.axBlankToolBar); this.Controls.Add(this.axReshapeToolbar); this.Controls.Add(this.axModifyToolbar); this.Controls.Add(this.panel1); this.Name = "EditorForm"; this.Text = "EditorForm"; this.TopMost = true; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.EditorForm_FormClosing); this.Load += new System.EventHandler(this.EditorForm_Load); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.axModifyToolbar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axReshapeToolbar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axBlankToolBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axUndoRedoToolbar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axCreateToolbar)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button cmdModify; private System.Windows.Forms.Button cmdReshape; private System.Windows.Forms.Button cmdCreate; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button cmdEdit; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private ESRI.ArcGIS.Controls.AxToolbarControl axModifyToolbar; private ESRI.ArcGIS.Controls.AxToolbarControl axReshapeToolbar; private ESRI.ArcGIS.Controls.AxToolbarControl axBlankToolBar; private System.Windows.Forms.TextBox txtInfo; private ESRI.ArcGIS.Controls.AxToolbarControl axUndoRedoToolbar; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; private System.Windows.Forms.Label label1; private ESRI.ArcGIS.Controls.AxToolbarControl axCreateToolbar; } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Infrastructure; using MSBuildConstruction = Microsoft.Build.Construction; using MSBuildExecution = Microsoft.Build.Execution; namespace Microsoft.VisualStudioTools.Project { [ComVisible(true)] internal abstract class ProjectConfig : IVsCfg, IVsProjectCfg, IVsProjectCfg2, IVsProjectFlavorCfg, IVsDebuggableProjectCfg, ISpecifyPropertyPages, IVsSpecifyProjectDesignerPages, IVsCfgBrowseObject { internal const string Debug = "Debug"; internal const string AnyCPU = "AnyCPU"; private ProjectNode project; private string configName; private MSBuildExecution.ProjectInstance currentConfig; private IVsProjectFlavorCfg flavoredCfg; private List<OutputGroup> outputGroups; private BuildableProjectConfig buildableCfg; private string platformName; #region properties internal ProjectNode ProjectMgr { get { return this.project; } } public string ConfigName { get { return this.configName; } set { this.configName = value; } } public string PlatformName { get { return platformName; } set { platformName = value; } } internal IList<OutputGroup> OutputGroups { get { if (null == this.outputGroups) { // Initialize output groups this.outputGroups = new List<OutputGroup>(); // If the project is not buildable (no CoreCompile target) // then don't bother getting the output groups. if (this.project.BuildProject != null && this.project.BuildProject.Targets.ContainsKey("CoreCompile")) { // Get the list of group names from the project. // The main reason we get it from the project is to make it easier for someone to modify // it by simply overriding that method and providing the correct MSBuild target(s). IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames(); if (groupNames != null) { // Populate the output array foreach (KeyValuePair<string, string> group in groupNames) { OutputGroup outputGroup = CreateOutputGroup(project, group); this.outputGroups.Add(outputGroup); } } } } return this.outputGroups; } } #endregion #region ctors internal ProjectConfig(ProjectNode project, string configuration) { this.project = project; if (configuration.Contains("|")) { // If configuration is in the form "<Configuration>|<Platform>" string[] configStrArray = configuration.Split('|'); if (2 == configStrArray.Length) { this.configName = configStrArray[0]; this.platformName = configStrArray[1]; } else { throw new Exception(string.Format(CultureInfo.InvariantCulture, "Invalid configuration format: {0}", configuration)); } } else { // If configuration is in the form "<Configuration>" this.configName = configuration; } var flavoredCfgProvider = ProjectMgr.GetOuterInterface<IVsProjectFlavorCfgProvider>(); Utilities.ArgumentNotNull("flavoredCfgProvider", flavoredCfgProvider); ErrorHandler.ThrowOnFailure(flavoredCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg)); Utilities.ArgumentNotNull("flavoredCfg", flavoredCfg); // if the flavored object support XML fragment, initialize it IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment; if (null != persistXML) { this.project.LoadXmlFragment(persistXML, configName, platformName); } } #endregion #region methods internal virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group) { OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this); return outputGroup; } public void PrepareBuild(bool clean) { project.PrepareBuild(this.configName, clean); } public virtual string GetConfigurationProperty(string propertyName, bool resetCache) { MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache); if (property == null) return null; return property.EvaluatedValue; } public virtual void SetConfigurationProperty(string propertyName, string propertyValue) { if (!this.project.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName); SetPropertyUnderCondition(propertyName, propertyValue, condition); // property cache will need to be updated this.currentConfig = null; return; } /// <summary> /// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model. /// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there. /// </summary> private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition) { string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim(); if (conditionTrimmed.Length == 0) { this.project.BuildProject.SetProperty(propertyName, propertyValue); return; } // New OM doesn't have a convenient equivalent for setting a property with a particular property group condition. // So do it ourselves. MSBuildConstruction.ProjectPropertyGroupElement newGroup = null; foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups) { if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase)) { newGroup = group; break; } } if (newGroup == null) { newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project newGroup.Condition = condition; } foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win { if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0) { property.Value = propertyValue; return; } } newGroup.AddProperty(propertyName, propertyValue); } /// <summary> /// If flavored, and if the flavor config can be dirty, ask it if it is dirty /// </summary> /// <param name="storageType">Project file or user file</param> /// <returns>0 = not dirty</returns> internal int IsFlavorDirty(_PersistStorageType storageType) { int isDirty = 0; if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment) { ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty)); } return isDirty; } /// <summary> /// If flavored, ask the flavor if it wants to provide an XML fragment /// </summary> /// <param name="flavor">Guid of the flavor</param> /// <param name="storageType">Project file or user file</param> /// <param name="fragment">Fragment that the flavor wants to save</param> /// <returns>HRESULT</returns> internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment) { fragment = null; int hr = VSConstants.S_OK; if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment) { Guid flavorGuid = flavor; hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1); } return hr; } #endregion #region IVsSpecifyPropertyPages public void GetPages(CAUUID[] pages) { this.GetCfgPropertyPages(pages); } #endregion #region IVsSpecifyProjectDesignerPages /// <summary> /// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent. /// </summary> /// <param name="pages">The pages to return.</param> /// <returns>VSConstants.S_OK</returns> public virtual int GetProjectDesignerPages(CAUUID[] pages) { this.GetCfgPropertyPages(pages); return VSConstants.S_OK; } #endregion #region IVsCfg methods /// <summary> /// The display name is a two part item /// first part is the config name, 2nd part is the platform name /// </summary> public virtual int get_DisplayName(out string name) { if (!string.IsNullOrEmpty(PlatformName)) { name = ConfigName + "|" + PlatformName; } else { name = DisplayName; } return VSConstants.S_OK; } private string DisplayName { get { string name; string[] platform = new string[1]; uint[] actual = new uint[1]; name = this.configName; // currently, we only support one platform, so just add it.. IVsCfgProvider provider; ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider)); ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual)); if (!string.IsNullOrEmpty(platform[0])) { name += "|" + platform[0]; } return name; } } public virtual int get_IsDebugOnly(out int fDebug) { fDebug = 0; if (this.configName == "Debug") { fDebug = 1; } return VSConstants.S_OK; } public virtual int get_IsReleaseOnly(out int fRelease) { fRelease = 0; if (this.configName == "Release") { fRelease = 1; } return VSConstants.S_OK; } #endregion #region IVsProjectCfg methods public virtual int EnumOutputs(out IVsEnumOutputs eo) { eo = null; return VSConstants.E_NOTIMPL; } public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb) { if (project.BuildProject == null || !project.BuildProject.Targets.ContainsKey("CoreCompile")) { // The project is not buildable, so don't return a config. This // will hide the 'Build' commands from the VS UI. pb = null; return VSConstants.E_NOTIMPL; } if (buildableCfg == null) { buildableCfg = new BuildableProjectConfig(this); } pb = buildableCfg; return VSConstants.S_OK; } public virtual int get_CanonicalName(out string name) { name = configName; return VSConstants.S_OK; } public virtual int get_IsPackaged(out int pkgd) { pkgd = 0; return VSConstants.S_OK; } public virtual int get_IsSpecifyingOutputSupported(out int f) { f = 1; return VSConstants.S_OK; } public virtual int get_Platform(out Guid platform) { platform = Guid.Empty; return VSConstants.E_NOTIMPL; } public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p) { p = null; IVsCfgProvider cfgProvider = null; this.project.GetCfgProvider(out cfgProvider); if (cfgProvider != null) { p = cfgProvider as IVsProjectCfgProvider; } return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK; } public virtual int get_RootURL(out string root) { root = null; return VSConstants.S_OK; } public virtual int get_TargetCodePage(out uint target) { target = (uint)System.Text.Encoding.Default.CodePage; return VSConstants.S_OK; } public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li) { Utilities.ArgumentNotNull("li", li); li[0] = new ULARGE_INTEGER(); li[0].QuadPart = 0; return VSConstants.S_OK; } public virtual int OpenOutput(string name, out IVsOutput output) { output = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsProjectCfg2 Members public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup) { ppIVsOutputGroup = null; // Search through our list of groups to find the one they are looking forgroupName foreach (OutputGroup group in OutputGroups) { string groupName; group.get_CanonicalName(out groupName); if (String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0) { ppIVsOutputGroup = group; break; } } return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL; } public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot) { pfRequiresAppRoot = 0; return VSConstants.E_NOTIMPL; } public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) { // Delegate to the flavored configuration (to enable a flavor to take control) // Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg); return hr; } public virtual int get_IsPrivate(out int pfPrivate) { pfPrivate = 0; return VSConstants.S_OK; } public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual) { // Are they only asking for the number of groups? if (celt == 0) { if ((null == pcActual) || (0 == pcActual.Length)) { throw new ArgumentNullException("pcActual"); } pcActual[0] = (uint)OutputGroups.Count; return VSConstants.S_OK; } // Check that the array of output groups is not null if ((null == rgpcfg) || (rgpcfg.Length == 0)) { throw new ArgumentNullException("rgpcfg"); } // Fill the array with our output groups uint count = 0; foreach (OutputGroup group in OutputGroups) { if (rgpcfg.Length > count && celt > count && group != null) { rgpcfg[count] = group; ++count; } } if (pcActual != null && pcActual.Length > 0) pcActual[0] = count; // If the number asked for does not match the number returned, return S_FALSE return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE; } public virtual int get_VirtualRoot(out string pbstrVRoot) { pbstrVRoot = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsDebuggableProjectCfg methods /// <summary> /// Called by the vs shell to start debugging (managed or unmanaged). /// Override this method to support other debug engines. /// </summary> /// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns> public abstract int DebugLaunch(uint grfLaunch); /// <summary> /// Determines whether the debugger can be launched, given the state of the launch flags. /// </summary> /// <param name="flags">Flags that determine the conditions under which to launch the debugger. /// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param> /// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param> /// <returns>S_OK if the method succeeds, otherwise an error code</returns> public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch) { string assembly = this.project.GetAssemblyName(this.ConfigName); fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0; if (fCanLaunch == 0) { string property = GetConfigurationProperty("StartProgram", true); fCanLaunch = (property != null && property.Length > 0) ? 1 : 0; } return VSConstants.S_OK; } #endregion #region IVsCfgBrowseObject /// <summary> /// Maps back to the configuration corresponding to the browse object. /// </summary> /// <param name="cfg">The IVsCfg object represented by the browse object</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetCfg(out IVsCfg cfg) { cfg = this; return VSConstants.S_OK; } /// <summary> /// Maps back to the hierarchy or project item object corresponding to the browse object. /// </summary> /// <param name="hier">Reference to the hierarchy object.</param> /// <param name="itemid">Reference to the project item.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) { Utilities.CheckNotNull(this.project); Utilities.CheckNotNull(this.project.NodeProperties); return this.project.NodeProperties.GetProjectItem(out hier, out itemid); } #endregion #region helper methods private MSBuildExecution.ProjectInstance GetCurrentConfig(bool resetCache = false) { if (resetCache || currentConfig == null) { // Get properties for current configuration from project file and cache it project.SetConfiguration(ConfigName); project.BuildProject.ReevaluateIfNecessary(); // Create a snapshot of the evaluated project in its current state currentConfig = project.BuildProject.CreateProjectInstance(); // Restore configuration project.SetCurrentConfiguration(); } return currentConfig; } private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache) { var current = GetCurrentConfig(resetCache); if (current == null) throw new Exception("Failed to retrieve properties"); // return property asked for return current.GetProperty(propertyName); } /// <summary> /// Retrieves the configuration dependent property pages. /// </summary> /// <param name="pages">The pages to return.</param> private void GetCfgPropertyPages(CAUUID[] pages) { // We do not check whether the supportsProjectDesigner is set to true on the ProjectNode. // We rely that the caller knows what to call on us. Utilities.ArgumentNotNull("pages", pages); if (pages.Length == 0) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), "pages"); } // Retrive the list of guids from hierarchy properties. // Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy string guidsList = String.Empty; IVsHierarchy hierarchy = project.GetOuterInterface<IVsHierarchy>(); object variant = null; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL }); guidsList = (string)variant; Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList); if (guids == null || guids.Length == 0) { pages[0] = new CAUUID(); pages[0].cElems = 0; } else { pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids); } } internal virtual bool IsInputGroup(string groupName) { return groupName == "SourceFiles"; } private static DateTime? TryGetLastWriteTimeUtc(string path, Redirector output = null) { try { return File.GetLastWriteTimeUtc(path); } catch (UnauthorizedAccessException ex) { if (output != null) { output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message)); #if DEBUG output.WriteErrorLine(ex.ToString()); #endif } } catch (ArgumentException ex) { if (output != null) { output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message)); #if DEBUG output.WriteErrorLine(ex.ToString()); #endif } } catch (PathTooLongException ex) { if (output != null) { output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message)); #if DEBUG output.WriteErrorLine(ex.ToString()); #endif } } catch (NotSupportedException ex) { if (output != null) { output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message)); #if DEBUG output.WriteErrorLine(ex.ToString()); #endif } } return null; } internal virtual bool IsUpToDate() { var outputWindow = OutputWindowRedirector.GetGeneral(ProjectMgr.Site); #if DEBUG outputWindow.WriteLine(string.Format("Checking whether {0} needs to be rebuilt:", ProjectMgr.Caption)); #endif var latestInput = DateTime.MinValue; var earliestOutput = DateTime.MaxValue; bool mustRebuild = false; var allInputs = new HashSet<string>(OutputGroups .Where(g => IsInputGroup(g.Name)) .SelectMany(x => x.EnumerateOutputs()) .Select(input => input.CanonicalName), StringComparer.OrdinalIgnoreCase ); foreach (var group in OutputGroups.Where(g => !IsInputGroup(g.Name))) { foreach (var output in group.EnumerateOutputs()) { var path = output.CanonicalName; #if DEBUG var dt = TryGetLastWriteTimeUtc(path); outputWindow.WriteLine(string.Format( " Out: {0}: {1} [{2}]", group.Name, path, dt.HasValue ? dt.Value.ToString("s") : "err" )); #endif DateTime? modifiedTime; if (!File.Exists(path) || !(modifiedTime = TryGetLastWriteTimeUtc(path, outputWindow)).HasValue) { mustRebuild = true; break; } string inputPath; if (File.Exists(inputPath = output.GetMetadata("SourceFile"))) { var inputModifiedTime = TryGetLastWriteTimeUtc(inputPath, outputWindow); if (inputModifiedTime.HasValue && inputModifiedTime.Value > modifiedTime.Value) { mustRebuild = true; break; } else { continue; } } // output is an input, ignore it... if (allInputs.Contains(path)) { continue; } if (modifiedTime.Value < earliestOutput) { earliestOutput = modifiedTime.Value; } } if (mustRebuild) { // Early exit if we know we're going to have to rebuild break; } } if (mustRebuild) { #if DEBUG outputWindow.WriteLine(string.Format( "Rebuilding {0} because mustRebuild is true", ProjectMgr.Caption )); #endif return false; } foreach (var group in OutputGroups.Where(g => IsInputGroup(g.Name))) { foreach (var input in group.EnumerateOutputs()) { var path = input.CanonicalName; #if DEBUG var dt = TryGetLastWriteTimeUtc(path); outputWindow.WriteLine(string.Format( " In: {0}: {1} [{2}]", group.Name, path, dt.HasValue ? dt.Value.ToString("s") : "err" )); #endif if (!File.Exists(path)) { continue; } var modifiedTime = TryGetLastWriteTimeUtc(path, outputWindow); if (modifiedTime.HasValue && modifiedTime.Value > latestInput) { latestInput = modifiedTime.Value; if (earliestOutput < latestInput) { break; } } } if (earliestOutput < latestInput) { // Early exit if we know we're going to have to rebuild break; } } if (earliestOutput < latestInput) { #if DEBUG outputWindow.WriteLine(string.Format( "Rebuilding {0} because {1:s} < {2:s}", ProjectMgr.Caption, earliestOutput, latestInput )); #endif return false; } else { #if DEBUG outputWindow.WriteLine(string.Format( "Not rebuilding {0} because {1:s} >= {2:s}", ProjectMgr.Caption, earliestOutput, latestInput )); #endif return true; } } #endregion #region IVsProjectFlavorCfg Members /// <summary> /// This is called to let the flavored config let go /// of any reference it may still be holding to the base config /// </summary> /// <returns></returns> int IVsProjectFlavorCfg.Close() { // This is used to release the reference the flavored config is holding // on the base config, but in our scenario these 2 are the same object // so we have nothing to do here. return VSConstants.S_OK; } /// <summary> /// Actual implementation of get_CfgType. /// When not flavored or when the flavor delegate to use /// we end up creating the requested config if we support it. /// </summary> /// <param name="iidCfg">IID representing the type of config object we should create</param> /// <param name="ppCfg">Config object that the method created</param> /// <returns>HRESULT</returns> int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg) { ppCfg = IntPtr.Zero; // See if this is an interface we support if (iidCfg == typeof(IVsDebuggableProjectCfg).GUID) { ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg)); } else if (iidCfg == typeof(IVsBuildableProjectCfg).GUID) { IVsBuildableProjectCfg buildableConfig; this.get_BuildableProjectCfg(out buildableConfig); // //In some cases we've intentionally shutdown the build options // If buildableConfig is null then don't try to get the BuildableProjectCfg interface // if (null != buildableConfig) { ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg)); } } // If not supported if (ppCfg == IntPtr.Zero) return VSConstants.E_NOINTERFACE; return VSConstants.S_OK; } #endregion } [ComVisible(true)] internal class BuildableProjectConfig : IVsBuildableProjectCfg { #region fields ProjectConfig config = null; EventSinkCollection callbacks = new EventSinkCollection(); #endregion #region ctors public BuildableProjectConfig(ProjectConfig config) { this.config = config; } #endregion #region IVsBuildableProjectCfg methods public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie) { cookie = callbacks.Add(callback); return VSConstants.S_OK; } public virtual int get_ProjectCfg(out IVsProjectCfg p) { p = config; return VSConstants.S_OK; } public virtual int QueryStartBuild(uint options, int[] supported, int[] ready) { if (supported != null && supported.Length > 0) supported[0] = 1; if (ready != null && ready.Length > 0) ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1; return VSConstants.S_OK; } public virtual int QueryStartClean(uint options, int[] supported, int[] ready) { if (supported != null && supported.Length > 0) supported[0] = 1; if (ready != null && ready.Length > 0) ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1; return VSConstants.S_OK; } public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready) { if (supported != null && supported.Length > 0) supported[0] = 1; if (ready != null && ready.Length > 0) ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1; return VSConstants.S_OK; } public virtual int QueryStatus(out int done) { done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1; return VSConstants.S_OK; } public virtual int StartBuild(IVsOutputWindowPane pane, uint options) { config.PrepareBuild(false); // Current version of MSBuild wish to be called in an STA uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD; // If we are not asked for a rebuild, then we build the default target (by passing null) this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null); return VSConstants.S_OK; } public virtual int StartClean(IVsOutputWindowPane pane, uint options) { config.PrepareBuild(true); // Current version of MSBuild wish to be called in an STA this.Build(options, pane, MsBuildTarget.Clean); return VSConstants.S_OK; } public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options) { return config.IsUpToDate() ? VSConstants.S_OK : VSConstants.E_FAIL; } public virtual int Stop(int fsync) { return VSConstants.S_OK; } public virtual int UnadviseBuildStatusCallback(uint cookie) { callbacks.RemoveAt(cookie); return VSConstants.S_OK; } public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty) { return VSConstants.E_NOTIMPL; } #endregion #region helpers [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private bool NotifyBuildBegin() { int shouldContinue = 1; foreach (IVsBuildStatusCallback cb in callbacks) { try { ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue)); if (shouldContinue == 0) { return false; } } catch (Exception e) { // If those who ask for status have bugs in their code it should not prevent the build/notification from happening Debug.Fail(SR.GetString(SR.BuildEventError, e.Message)); } } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void NotifyBuildEnd(MSBuildResult result, string buildTarget) { int success = ((result == MSBuildResult.Successful) ? 1 : 0); foreach (IVsBuildStatusCallback cb in callbacks) { try { ErrorHandler.ThrowOnFailure(cb.BuildEnd(success)); } catch (Exception e) { // If those who ask for status have bugs in their code it should not prevent the build/notification from happening Debug.Fail(SR.GetString(SR.BuildEventError, e.Message)); } finally { // We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only. bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild); // Now repaint references if that is needed. // We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build. // One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable, // but msbuild can actually resolve it. // Another one if the project was opened only for browsing and now the user chooses to build or rebuild. if (shouldRepaintReferences && (result == MSBuildResult.Successful)) { this.RefreshReferences(); } } } } private void Build(uint options, IVsOutputWindowPane output, string target) { if (!this.NotifyBuildBegin()) { return; } try { config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget)); } catch (Exception e) { if (e.IsCriticalException()) { throw; } Trace.WriteLine("Exception : " + e.Message); ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n")); this.NotifyBuildEnd(MSBuildResult.Failed, target); throw; } finally { ErrorHandler.ThrowOnFailure(output.FlushToTaskList()); } } /// <summary> /// Refreshes references and redraws them correctly. /// </summary> private void RefreshReferences() { // Refresh the reference container node for assemblies that could be resolved. IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer(); if (referenceContainer != null) { foreach (ReferenceNode referenceNode in referenceContainer.EnumReferences()) { referenceNode.RefreshReference(); } } } #endregion } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenMetaverse; using OpenSim.Framework; using OpenMetaverse.StructuredData; namespace InWorldz.Testing { public class MockClientAPI : IClientAPI { public OpenMetaverse.Vector3 StartPos { get { return OpenMetaverse.Vector3.Zero; } set { } } public OpenMetaverse.UUID AgentId { get; set; } public OpenMetaverse.UUID SessionId { get; set; } public OpenMetaverse.UUID SecureSessionId { get { return OpenMetaverse.UUID.Zero; } } public OpenMetaverse.UUID ActiveGroupId { get { return OpenMetaverse.UUID.Zero; } } public string ActiveGroupName { get { return String.Empty; } } public ulong ActiveGroupPowers { get { return 0; } } public ulong GetGroupPowers(OpenMetaverse.UUID groupID) { return 0; } public ulong? GetGroupPowersOrNull(OpenMetaverse.UUID groupID) { return null; } public bool IsGroupMember(OpenMetaverse.UUID GroupID) { return true; } public string FirstName { get { return "Mock"; } } public string LastName { get { return "User"; } } public IScene Scene { get { return null; } } public int NextAnimationSequenceNumber { get { return 0; } } public string Name { get { return "Mock User"; } } public bool IsActive { get { return true; } } public bool SendLogoutPacketWhenClosing { set { } } public bool DebugCrossings { get { return false; } set { } } public uint NeighborsRange { get { return 1; } set { } } public uint CircuitCode { get; set; } #pragma warning disable 0067 // disable "X is never used" public event Action<int> OnSetThrottles; public event GenericMessage OnGenericMessage; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event RestoreObject OnRestoreObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event EstateChangeInfo OnEstateChangeInfo; public event SimWideDeletesDelegate OnSimWideDeletes; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event RequestAvatarInterests OnRequestAvatarInterests; public event SetAlwaysRun OnSetAlwaysRun; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event DeRezObjects OnDeRezObjects; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall2 OnRequestWearables; public event GenericCall2 OnCompleteMovementToRegion; public event UpdateAgent OnAgentUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event ObjectRequest OnObjectRequest; public event ObjectSelect OnObjectSelect; public event ObjectDeselect OnObjectDeselect; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event UpdateVectorWithUndoSupport OnUpdatePrimGroupPosition; public event UpdateVectorWithUndoSupport OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<OpenMetaverse.UUID> OnRemoveAvatar; public event ObjectPermissions OnObjectPermissions; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event LinkInventoryItem OnLinkInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event RemoveInventoryItem OnPreRemoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event UUIDNameRequest OnNameFromUUIDRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event MoneyTransferRequest OnMoneyTransferRequest; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event AvatarInterestsUpdate OnAvatarInterestsUpdate; public event ParcelBuy OnParcelBuy; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event AgentSit OnUndo; public event AgentSit OnRedo; public event LandUndo OnLandUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event UpdateVector OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event ActivateGestures OnActivateGestures; public event DeactivateGestures OnDeactivateGestures; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event MuteListEntryUpdate OnUpdateMuteListEntry; public event MuteListEntryRemove OnRemoveMuteListEntry; public event PlacesQuery OnPlacesQuery; public event GrantUserRights OnGrantUserRights; public event FreezeUserUpdate OnParcelFreezeUser; public event EjectUserUpdate OnParcelEjectUser; public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest; public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest; public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest; public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest; public event AgentCachedTextureRequest OnAgentCachedTextureRequest; public event ActivateGroup OnActivateGroup; public event GodlikeMessage OnGodlikeMessage; public event GodlikeMessage OnEstateTelehubRequest; #pragma warning restore 0067 public System.Net.IPEndPoint RemoteEndPoint { get { return new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 18374); } } public bool IsLoggingOut { get { return false; } set { } } public void SetDebugPacketLevel(int newDebug) { } public void ProcessInPacket(OpenMetaverse.Packets.Packet NewPack) { } public void Close() { var connClosed = this.OnConnectionClosed; if (connClosed != null) { connClosed(this); } } public void Kick(string message) { } public void Start() { } public void SendWearables(AvatarWearable[] wearables, int serial) { } public void SendAppearance(AvatarAppearance app, Vector3 hover) { } public void SendStartPingCheck(byte seq) { } public void SendKillObject(ulong regionHandle, uint localID) { } public void SendKillObjects(ulong regionHandle, uint[] localIDs) { } public void SendNonPermanentKillObject(ulong regionHandle, uint localID) { } public void SendNonPermanentKillObjects(ulong regionHandle, uint[] localIDs) { } public void SendAnimations(OpenMetaverse.UUID[] animID, int[] seqs, OpenMetaverse.UUID sourceAgentId, OpenMetaverse.UUID[] objectIDs) { } public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { } public void SendChatMessage(string message, byte type, OpenMetaverse.Vector3 fromPos, string fromName, OpenMetaverse.UUID fromAgentID, OpenMetaverse.UUID ownerID, byte source, byte audible) { } public void SendInstantMessage(GridInstantMessage im) { } public void SendGenericMessage(string method, List<string> message) { } public void SendLayerData(float[] map) { } public void SendLayerData(int px, int py, float[] map) { } public void SendWindData(OpenMetaverse.Vector2[] windSpeeds) { } public void SendCloudData(float[] cloudCover) { } public void MoveAgentIntoRegion(RegionInfo regInfo, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 look) { } public void InformClientOfNeighbour(ulong neighbourHandle, System.Net.IPEndPoint neighbourExternalEndPoint) { } public AgentCircuitData RequestClientInfo() { AgentCircuitData agentData = new AgentCircuitData(); agentData.AgentID = AgentId; // agentData.Appearance // agentData.BaseFolder agentData.CapsPath = OpenMetaverse.UUID.Random().ToString(); agentData.child = false; agentData.CircuitCode = 100; agentData.ClientVersion = "Test Client"; agentData.FirstName = "Mock"; // agentData.InventoryFolder agentData.LastName = "User"; agentData.SecureSessionID = OpenMetaverse.UUID.Random(); agentData.SessionID = OpenMetaverse.UUID.Random(); return agentData; } public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public void SendLocalTeleport(OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 lookAt, uint flags) { } public void SendTeleportFailed(string reason) { } public void SendTeleportLocationStart() { } public void SendPayPrice(OpenMetaverse.UUID objectID, int[] payPrice) { } public void SendAvatarData(ulong regionHandle, string firstName, string lastName, string grouptitle, OpenMetaverse.UUID avatarID, uint avatarLocalID, OpenMetaverse.Vector3 Pos, byte[] textureEntry, uint parentID, OpenMetaverse.Quaternion rotation, OpenMetaverse.Vector4 collisionPlane, OpenMetaverse.Vector3 velocity, bool immediate) { } public void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 velocity, OpenMetaverse.Vector3 acceleration, OpenMetaverse.Quaternion rotation, OpenMetaverse.UUID agentid, OpenMetaverse.Vector4 collisionPlane) { } public void SendCoarseLocationUpdate(List<OpenMetaverse.UUID> users, List<OpenMetaverse.Vector3> CoarseLocations) { } public void AttachObject(uint localID, OpenMetaverse.Quaternion rotation, byte attachPoint, OpenMetaverse.UUID ownerID) { } public void SetChildAgentThrottle(byte[] throttle) { } public void SendPrimitiveToClient(object sop, uint clientFlags, OpenMetaverse.Vector3 lpos, PrimUpdateFlags updateFlags) { } public void SendPrimitiveToClientImmediate(object sop, uint clientFlags, OpenMetaverse.Vector3 lpos) { } public void SendPrimTerseUpdate(object sop) { } public void SendInventoryFolderDetails(OpenMetaverse.UUID ownerID, InventoryFolderBase folder, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems) { } public void FlushPrimUpdates() { } public void SendInventoryItemDetails(OpenMetaverse.UUID ownerID, InventoryItemBase item) { } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId) { } public void SendRemoveInventoryItem(OpenMetaverse.UUID itemID) { } public void SendTakeControls(int controls, bool TakeControls, bool passToAgent) { } public void SendTakeControls2(int controls1, bool takeControls1, bool passToAgent1, int controls2, bool takeControls2, bool passToAgent2) { } public void SendTaskInventory(OpenMetaverse.UUID taskID, short serial, byte[] fileName) { } public void SendBulkUpdateInventory(InventoryNodeBase node) { } public void SendXferPacket(ulong xferID, uint packet, byte[] data) { } public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public void SendAgentDataUpdate(OpenMetaverse.UUID agentid, OpenMetaverse.UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public void SendPreLoadSound(OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, OpenMetaverse.UUID soundID) { } public void SendPlayAttachedSound(OpenMetaverse.UUID soundID, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(OpenMetaverse.UUID soundID, OpenMetaverse.UUID ownerID, OpenMetaverse.UUID objectID, OpenMetaverse.UUID parentID, ulong handle, OpenMetaverse.Vector3 position, float gain) { } public void SendAttachedSoundGainChange(OpenMetaverse.UUID objectID, float gain) { } public void SendNameReply(OpenMetaverse.UUID profileId, string firstname, string lastname) { } public void SendAlertMessage(string message) { } public void SendAlertMessage(string message, string infoMessage, OSD extraParams) { /* no op */ } public void SendAgentAlertMessage(string message, bool modal) { } public void SendLoadURL(string objectname, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, bool groupOwned, string message, string url) { } public void SendDialog(string objectname, OpenMetaverse.UUID objectID, OpenMetaverse.UUID ownerID, string ownerFirstname, string ownerLastname, string msg, OpenMetaverse.UUID textureID, int ch, string[] buttonlabels) { } public bool AddMoney(int debit) { return true; } public void SendSunPos(OpenMetaverse.Vector3 sunPos, OpenMetaverse.Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition) { } public void SendViewerEffect(OpenMetaverse.Packets.ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public OpenMetaverse.UUID GetDefaultAnimation(string name) { return OpenMetaverse.UUID.Zero; } public void SendAvatarProperties(OpenMetaverse.UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, OpenMetaverse.UUID flImageID, OpenMetaverse.UUID imageID, string profileURL, OpenMetaverse.UUID partnerID) { } public void SendAvatarInterests(OpenMetaverse.UUID avatarID, uint skillsMask, string skillsText, uint wantToMask, string wantToText, string languagesText) { } public void SendScriptQuestion(OpenMetaverse.UUID taskID, string taskName, string ownerName, OpenMetaverse.UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateUUIDList(OpenMetaverse.UUID invoice, int whichList, OpenMetaverse.UUID[] UUIDList, uint estateID) { } public void SendBannedUserList(OpenMetaverse.UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(OpenMetaverse.UUID covenant, uint lastUpdated) { } public void SendDetailedEstateData(OpenMetaverse.UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, OpenMetaverse.UUID covenant, uint covenantLastUpdated, string abuseEmail, OpenMetaverse.UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<OpenMetaverse.UUID> avatars, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendLandObjectOwners(LandData land, List<OpenMetaverse.UUID> groups, Dictionary<OpenMetaverse.UUID, int> ownersAndCount) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, OpenMetaverse.UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, OpenMetaverse.UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, OpenMetaverse.UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, OpenMetaverse.UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { } public void SendImageNextPart(ushort partNumber, OpenMetaverse.UUID imageUuid, byte[] imageData) { } public void SendImageNotFound(OpenMetaverse.UUID imageid) { } public void SendDisableSimulator() { } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(uint RequestFlags, OpenMetaverse.UUID ObjectUUID, OpenMetaverse.UUID OwnerID, OpenMetaverse.UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, OpenMetaverse.UUID LastOwnerID, string ObjectName, string Description) { } public void SendObjectPropertiesReply(OpenMetaverse.UUID ItemID, ulong CreationDate, OpenMetaverse.UUID CreatorUUID, OpenMetaverse.UUID FolderUUID, OpenMetaverse.UUID FromTaskUUID, OpenMetaverse.UUID GroupUUID, short InventorySerial, OpenMetaverse.UUID LastOwnerUUID, OpenMetaverse.UUID ObjectUUID, OpenMetaverse.UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, uint FoldedOwnerMask, uint FoldedNextOwnerMask, byte saleType, int salePrice) { } public void SendAgentOffline(OpenMetaverse.UUID[] agentIDs) { } public void SendAgentOnline(OpenMetaverse.UUID[] agentIDs) { } public void SendSitResponse(OpenMetaverse.UUID TargetID, OpenMetaverse.Vector3 OffsetPos, OpenMetaverse.Quaternion SitOrientation, bool autopilot, OpenMetaverse.Vector3 CameraAtOffset, OpenMetaverse.Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(OpenMetaverse.UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } public void SendGroupNameReply(OpenMetaverse.UUID groupLLUID, string GroupName) { } public void SendJoinGroupReply(OpenMetaverse.UUID groupID, bool success) { } public void SendEjectGroupMemberReply(OpenMetaverse.UUID agentID, OpenMetaverse.UUID groupID, bool success) { } public void SendLeaveGroupReply(OpenMetaverse.UUID groupID, bool success) { } public void SendCreateGroupReply(OpenMetaverse.UUID groupID, bool success, string message) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, List<LandStatReportItem> lsrpl) { } public void SendScriptRunningReply(OpenMetaverse.UUID objectID, OpenMetaverse.UUID itemID, bool running) { } public void SendAsset(AssetBase asset, AssetRequestInfo req) { } public void SendTexture(AssetBase TextureAsset) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } public event ViewerEffectEventHandler OnViewerEffect; public event Action<IClientAPI> OnLogout; public event Action<IClientAPI> OnConnectionClosed; public void SendBlueBoxMessage(OpenMetaverse.UUID FromAvatarID, string FromAvatarName, string Message) { } public void SendLogoutPacket() { } public void SetClientInfo(ClientInfo info) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return String.Empty; } public void SendSetFollowCamProperties(OpenMetaverse.UUID objectID, Dictionary<int, float> parameters) { } public void SendClearFollowCamProperties(OpenMetaverse.UUID objectID) { } public void SendRegionHandle(OpenMetaverse.UUID regoinID, ulong handle) { } public void SendParcelInfo(RegionInfo info, LandData land, OpenMetaverse.UUID parcelID, uint x, uint y) { } public void SendScriptTeleportRequest(string objName, string simName, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 lookAt) { } public void SendDirPlacesReply(OpenMetaverse.UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(OpenMetaverse.UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(OpenMetaverse.UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(OpenMetaverse.UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(OpenMetaverse.UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(OpenMetaverse.UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(OpenMetaverse.UUID queryID, DirPopularReplyData[] data) { } public void SendEventInfoReply(EventData info) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void SendAvatarGroupsReply(OpenMetaverse.UUID avatarID, GroupMembershipData[] data) { } public void SendOfferCallingCard(OpenMetaverse.UUID srcID, OpenMetaverse.UUID transactionID) { } public void SendAcceptCallingCard(OpenMetaverse.UUID transactionID) { } public void SendDeclineCallingCard(OpenMetaverse.UUID transactionID) { } public void SendTerminateFriend(OpenMetaverse.UUID exFriendID) { } public void SendAvatarClassifiedReply(OpenMetaverse.UUID targetID, OpenMetaverse.UUID[] classifiedID, string[] name) { } public void SendAvatarInterestsReply(OpenMetaverse.UUID avatarID, uint skillsMask, string skillsText, uint wantToMask, string wantToTask, string languagesText) { } public void SendClassifiedInfoReply(OpenMetaverse.UUID classifiedID, OpenMetaverse.UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, OpenMetaverse.UUID parcelID, uint parentEstate, OpenMetaverse.UUID snapshotID, string simName, OpenMetaverse.Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(OpenMetaverse.UUID groupID) { } public void RefreshGroupMembership() { } public void SendAvatarNotesReply(OpenMetaverse.UUID targetID, string text) { } public void SendAvatarPicksReply(OpenMetaverse.UUID targetID, Dictionary<OpenMetaverse.UUID, string> picks) { } public void SendPickInfoReply(OpenMetaverse.UUID pickID, OpenMetaverse.UUID creatorID, bool topPick, OpenMetaverse.UUID parcelID, string name, string desc, OpenMetaverse.UUID snapshotID, string user, string originalName, string simName, OpenMetaverse.Vector3 posGlobal, int sortOrder, bool enabled) { } public void SendAvatarClassifiedReply(OpenMetaverse.UUID targetID, Dictionary<OpenMetaverse.UUID, string> classifieds) { } public void SendParcelDwellReply(int localID, OpenMetaverse.UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public void KillEndDone() { } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { return true; } public void SendChangeUserRights(OpenMetaverse.UUID agent, OpenMetaverse.UUID agentRelated, int relatedRights) { } public void SendTextBoxRequest(string message, int chatChannel, string objectname, OpenMetaverse.UUID ownerID, string firstName, string lastName, OpenMetaverse.UUID objectId) { } public void FreezeMe(uint flags, OpenMetaverse.UUID whoKey, string who) { } public void SendAbortXfer(ulong id, int result) { } public void RunAttachmentOperation(Action action) { } public void SendAgentCachedTexture(List<CachedAgentArgs> args) { } public void SendTelehubInfo(OpenMetaverse.Vector3 TelehubPos, OpenMetaverse.Quaternion TelehubRot, List<OpenMetaverse.Vector3> SpawnPoint, OpenMetaverse.UUID ObjectID, string nameT) { } public void HandleWithInventoryWriteThread(Action toHandle) { } public Task PauseUpdatesAndFlush() { return null; } public void ResumeUpdates(IEnumerable<uint> excludeObjectIds) { } public void WaitForClose() { } public void AfterAttachedToConnection(OpenSim.Framework.AgentCircuitData c) { } public void SendMoneyBalance(OpenMetaverse.UUID transaction, bool success, string description, int balance, OpenMetaverse.Packets.MoneyBalanceReplyPacket.TransactionInfoBlock transInfo) { } public List<AgentGroupData> GetAllGroupPowers() { return new List<AgentGroupData>(); } public void SetGroupPowers(IEnumerable<AgentGroupData> groupPowers) { } public int GetThrottleTotal() { return 0; } public void SetActiveGroupInfo(AgentGroupData activeGroup) { } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Drawing; using System.IO; using System.Windows.Forms; namespace VisualWget { struct Preset { public string name; public string value; public Preset(string name, string value) { this.name = name; this.value = value; } } public enum JobOptionCategory { General = 0, Http, Advanced, } public partial class JobDialog : Form { List<Preset> presets; bool savePresets; StringCollection urls; StringDictionary opts; public JobDialog(StringCollection urls, StringDictionary opts) { InitializeComponent(); presets = new List<Preset>(); savePresets = false; this.urls = urls; this.opts = opts; } public string GetUrlsString() { string s = ""; for (int i = 0; i < urls.Count; i++) s += " " + Util.AddQuotes(urls[i]); return s.Trim(); } public string GetOptsString() { string s = ""; string[] keys = new string[opts.Keys.Count]; opts.Keys.CopyTo(keys, 0); Array.Sort(keys); foreach (string t in keys) { s += "--" + t; if (opts[t] != null) { s += "=" + Util.AddQuotes(opts[t]); } s += " "; } return s.Trim(); } public bool StartOnOk { get { return startOnOkCheckBox.Checked; } } public bool ShowStartOnOk { set { startOnOkCheckBox.Visible = value; } } public bool ShowOutputDocument { set { outputDocumentLabel.Visible = value; outputDocumentTextBox.Visible = value; outputDocumentButton.Visible = value; } } public bool ShowNote { set { noteLabel.Visible = value; noteTextBox.Visible = value; } } public bool EnableUrls { set { urlsLabel.Enabled = value; urlsTextBox.Enabled = value; } } public bool ShowReferer { set { refererLabel.Visible = value; refererTextBox.Visible = value; } } public string UrlsLabelText { set { urlsLabel.Text = value; } } private void okButton_Click(object sender, EventArgs e) { urls.Clear(); urls.AddRange(Util.CmdLineArgsToArgs(urlsTextBox.Text.Trim())); string s = directoryPrefixComboBox.Text; Util.PutSetting("DirPrefix0", s); int i = directoryPrefixComboBox.FindStringExact(s); if (i == -1) { i = directoryPrefixComboBox.Items.Count; if (i == directoryPrefixComboBox.MaxDropDownItems) { i--; } } for (int j = 0; j < i; j++) { Util.PutSetting("DirPrefix" + (j + 1).ToString(), directoryPrefixComboBox.Items[j].ToString()); } DialogResult = DialogResult.OK; Close(); } void LoadPresets() { string[] lines; try { string dir; if (Util.IsPortableApp()) { dir = Util.AppDir; } else { dir = Util.AppDataDir; } lines = File.ReadAllLines(Path.Combine(dir, "OptionPresets.cfg")); } catch (FileNotFoundException) { return; } catch (DirectoryNotFoundException) { return; } catch (Exception ex) { Util.MsgBox(ex.Message, MessageBoxIcon.Error); return; } foreach (string line in lines) { string[] args = Util.CmdLineArgsToArgs(line); if (args.Length > 1) { presets.Add(new Preset(args[0], args[1])); } } } private void JobDialog_Load(object sender, EventArgs e) { this.jobCatListBox.SelectedIndex = 0; string[] userAgentLines = File.ReadAllLines(Path.Combine(Util.AppDir, "UserAgents.cfg")); for (int i = 0; i < userAgentLines.Length; i++) { string userAgentLine = userAgentLines[i]; if (userAgentLine.Contains("=")) { string[] userAgentParts = userAgentLine.Split('='); string userAgentName = userAgentParts[0].Trim(); string userAgentValue = userAgentParts[1].Trim(); UserAgentItem userAgentItem = new UserAgentItem(userAgentName, userAgentValue); this.userAgentComboBox.Items.Add(userAgentItem); } } SyncHttpOpts(); urlsTextBox.Text = GetUrlsString(); if (Text == "New Job" && urlsTextBox.Text == "") { string clipboardText = Util.GetTextFromClipboard(); if (Util.IsDownloadable(clipboardText)) { urlsTextBox.Text = "\"" + clipboardText + "\""; } } SyncGeneralOpts(); autoStartNumDaysNumericUpDown.Enabled = autoStartCheckBox.Checked; autoStartNumHoursNumericUpDown.Enabled = (autoStartCheckBox.Checked && (autoStartNumDaysNumericUpDown.Value == 0)); LoadPresets(); UpdateOptionsPresetComboBox(); optionsCategoryListBox.Items.AddRange(Util.GetArrayOfOptCats()); optionsCategoryListBox.SelectedIndex = 0; startOnOkCheckBox.Checked = bool.Parse(Util.GetSetting("JobDialogStartOnOk")); for (int i = 0; i < directoryPrefixComboBox.MaxDropDownItems; i++) { string dirPrefix = Util.GetSetting("DirPrefix" + i.ToString()); if (dirPrefix == "") { break; } if (directoryPrefixComboBox.FindStringExact(dirPrefix) == -1) { directoryPrefixComboBox.Items.Add(dirPrefix); } } Translate(); autoStartCheckBox.SendToBack(); startOnOkCheckBox.SendToBack(); Util.SetToolTip(toolTip1, Controls); this.SetInterFaceFont(); } void Translate() { if (Text == "New Job") { Text = Util.translationList["000037"]; urlsLabel.Text = Util.translationList["000041"]; } else if (Text == "Edit Job") { Text = Util.translationList["000038"]; urlsLabel.Text = Util.translationList["000041"]; } else if (Text == "Default Download Properties") { Text = Util.translationList["000039"]; urlsLabel.Text = Util.translationList["000041"]; } jobCatListBox.Items[(int)JobOptionCategory.General] = Util.translationList["000040"]; directoryPrefixLabel.Text = Util.translationList["000043"]; resumingGroupBox.Text = Util.translationList["000247"]; continueCheckBox.Text = Util.translationList["000044"]; timestampingCheckBox.Text = Util.translationList["000045"]; //recursiveCheckBox.Text = Util.translationList["000046"]; //noClobberCheckBox.Text = Util.translationList["000047"]; schedulerGroupBox.Text = Util.translationList["000048"]; autoStartCheckBox.Text = Util.translationList["000049"]; autoStartDaysLabel.Text = Util.translationList["000050"]; autoStartHoursLabel.Text = Util.translationList["000208"]; outputDocumentLabel.Text = Util.translationList["000051"]; noteLabel.Text = Util.translationList["000210"]; jobCatListBox.Items[(int)JobOptionCategory.Advanced] = Util.translationList["000052"]; presetsGroupBox.Text = Util.translationList["000053"]; //loadButton.Text = Util.translationList["000054"]; //saveButton.Text = Util.translationList["000055"]; loadEmptyButton.Text = Util.translationList["000209"]; saveAsButton.Text = Util.translationList["000056"]; deleteButton.Text = Util.translationList["000057"]; //resetLinkLabel.Text = Util.translationList["000058"]; //resetLinkLabel.Location = new Point(panel4.Width - resetLinkLabel.Width - 3, panel4.Height - resetLinkLabel.Height - 3); startOnOkCheckBox.Text = Util.translationList["000059"]; okButton.Text = Util.translationList["000060"]; cancelButton.Text = Util.translationList["000061"]; jobCatListBox.Items[(int)JobOptionCategory.Http] = Util.translationList["000214"]; userAgentLabel.Text = Util.translationList["000215"]; refererLabel.Text = Util.translationList["000216"]; } private void JobDialog_Shown(object sender, EventArgs e) { urlsTextBox.Focus(); urlsTextBox.SelectAll(); } private void UpdatePreset(Preset p) { for (int i = 0; i < presets.Count; i++) { if (string.Compare(presets[i].name, p.name, true) == 0) { presets[i] = p; break; } } } /*private void saveButton_Click(object sender, EventArgs e) { Debug.Assert(optionsPresetComboBox.SelectedItem != null); Preset p; p.name = optionsPresetComboBox.SelectedItem.ToString(); p.value = GetOptsString(); int i = SearchPresetsValue(p.value); if (i != -1) { if (Util.MsgBox(string.Format(Util.translationList["000179"], presets[i].name), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return; } presets.RemoveAt(i); } UpdatePreset(p); UpdateOptionsPresetComboBox(); savePresets = true; }*/ private void DeletePreset(string presetName) { for (int i = 0; i < presets.Count; i++) { if (string.Compare(presets[i].name, presetName, true) == 0) { presets.RemoveAt(i); break; } } } private void deleteButton_Click(object sender, EventArgs e) { Debug.Assert(optionsPresetComboBox.SelectedItem != null); DeletePreset(optionsPresetComboBox.SelectedItem.ToString()); UpdateOptionsPresetComboBox(); savePresets = true; } void SavePresets() { List<string> lines = new List<string>(); foreach (Preset p in presets) { lines.Add(Util.AddQuotes(p.name) + " " + Util.AddQuotes(p.value)); } string dir; if (Util.IsPortableApp()) { dir = Util.AppDir; } else { dir = Util.AppDataDir; Directory.CreateDirectory(dir); } try { File.WriteAllLines(Path.Combine(dir, "OptionPresets.cfg"), lines.ToArray()); } catch (Exception ex) { Util.MsgBox(string.Format(Util.translationList["000182"], ex.Message), MessageBoxIcon.Error); } } void UpdateOptionsPresetComboBox() { optionsPresetComboBox.Items.Clear(); foreach (Preset p in presets) { optionsPresetComboBox.Items.Add(p.name); } int i = SearchPresetsValue(GetOptsString()); if (i != -1) { string s = presets[i].name; Debug.Assert(s != ""); int j = optionsPresetComboBox.FindStringExact(s); if (j != -1) { optionsPresetComboBox.SelectedIndexChanged -= new EventHandler(optionsPresetComboBox_SelectedIndexChanged); optionsPresetComboBox.SelectedIndex = j; optionsPresetComboBox.SelectedIndexChanged += new EventHandler(optionsPresetComboBox_SelectedIndexChanged); } } EnableDisableButtons(); } void SetChecked() { int i = optionsCategoryListBox.SelectedIndex; for (int j = 0; j < optionsListView.Items.Count; j++) { int index = Util.GetOptIndex(i, j); if (index == -1) { Debug.Assert(false, string.Format("Opt not found, i={0}, j={1}.", i, j)); continue; } optionsListView.ItemCheck -= new ItemCheckEventHandler(optionsListView_ItemCheck); optionsListView.Items[j].Checked = opts.ContainsKey(Util.GetOptByIndex(index).name); optionsListView.ItemCheck += new ItemCheckEventHandler(optionsListView_ItemCheck); } } void SetText() { int i = optionsCategoryListBox.SelectedIndex; if (optionsListView.SelectedIndices.Count == 0) { return; } int j = optionsListView.SelectedIndices[0]; int index = Util.GetOptIndex(i, j); if (index == -1) { Debug.Assert(false, string.Format("Opt not found, i={0}, j={1}.", i, j)); return; } if (Util.GetOptByIndex(index).needArg) { argumentTextBox.TextChanged -= new EventHandler(argumentTextBox_TextChanged); if (opts.ContainsKey(Util.GetOptByIndex(index).name)) { argumentTextBox.Text = opts[Util.GetOptByIndex(index).name]; } else { argumentTextBox.Text = ""; } argumentTextBox.TextChanged += new EventHandler(argumentTextBox_TextChanged); } } void UpdateOpts(string optsString) { StringCollection tmpUrls; StringDictionary tmpOpts; Util.GetOpt(optsString, out tmpUrls, out tmpOpts); opts.Clear(); foreach (string optName in tmpOpts.Keys) { opts.Add(optName, tmpOpts[optName]); } } void HideArgumentControls() { argumentLabel.Hide(); argumentTextBox.Hide(); argumentButton.Hide(); } private void optionsCategoryListBox_SelectedIndexChanged(object sender, EventArgs e) { optionsListView.Items.Clear(); foreach (string s in Util.GetArrayOfOpts(optionsCategoryListBox.SelectedIndex)) { optionsListView.Items.Add(s); } optionsListView.SelectedIndices.Clear(); HideArgumentControls(); descriptionLabel.Text = ""; SetChecked(); } private void argumentTextBox_TextChanged(object sender, EventArgs e) { int i = optionsCategoryListBox.SelectedIndex; if (optionsListView.SelectedIndices.Count == 0) { return; } int j = optionsListView.SelectedIndices[0]; int index = Util.GetOptIndex(i, j); if (index == -1) { Debug.Assert(false, string.Format("Opt not found, i={0}, j={1}.", i, j)); return; } Debug.Assert(Util.GetOptByIndex(index).needArg); if (!optionsListView.CheckedIndices.Contains(j)) { optionsListView.Items[j].Checked = true; } if (!opts.ContainsKey(Util.GetOptByIndex(index).name)) { opts.Add(Util.GetOptByIndex(index).name, argumentTextBox.Text); } else { opts[Util.GetOptByIndex(index).name] = argumentTextBox.Text; } EnableDisableButtons(); } void ShowDir() { folderBrowserDialog1.Description = "Please select a folder."; if (Directory.Exists(argumentTextBox.Text)) { folderBrowserDialog1.SelectedPath = argumentTextBox.Text; } if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK) { argumentTextBox.Text = folderBrowserDialog1.SelectedPath; } } void ShowOpen() { openFileDialog1.Filter = "All Files (*.*)|*.*"; if (File.Exists(argumentTextBox.Text)) { openFileDialog1.FileName = Path.GetFileName(argumentTextBox.Text); openFileDialog1.InitialDirectory = Path.GetDirectoryName(argumentTextBox.Text); } if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { argumentTextBox.Text = openFileDialog1.FileName; } } void ShowSave() { saveFileDialog1.Filter = "All Files (*.*)|*.*"; if (File.Exists(argumentTextBox.Text)) { saveFileDialog1.FileName = Path.GetFileName(argumentTextBox.Text); saveFileDialog1.InitialDirectory = Path.GetDirectoryName(argumentTextBox.Text); } if (saveFileDialog1.ShowDialog(this) == DialogResult.OK) { argumentTextBox.Text = saveFileDialog1.FileName; } } private void argumentButton_Click(object sender, EventArgs e) { int i = optionsCategoryListBox.SelectedIndex; if (optionsListView.SelectedIndices.Count == 0) { return; } int j = optionsListView.SelectedIndices[0]; int index = Util.GetOptIndex(i, j); if (index == -1) { Debug.Assert(false, string.Format("Opt not found, i={0}, j={1}.", i, j)); return; } Debug.Assert(Util.GetOptByIndex(index).needArg); string action = Util.GetOptByIndex(index).action; if (action == "ShowDir") { ShowDir(); } else if (action == "ShowOpen") { ShowOpen(); } else if (action == "ShowSave") { ShowSave(); } } private void optionsListView_ItemCheck(object sender, ItemCheckEventArgs e) { int i = optionsCategoryListBox.SelectedIndex; int j = e.Index; int index = Util.GetOptIndex(i, j); if (index == -1) { Debug.Assert(false, string.Format("Opt not found, i={0}, j={1}.", i, j)); return; } if (optionsListView.CheckedIndices.Contains(j)) { if (opts.ContainsKey(Util.GetOptByIndex(index).name)) { opts.Remove(Util.GetOptByIndex(index).name); SetText(); EnableDisableButtons(); } } else { if (!opts.ContainsKey(Util.GetOptByIndex(index).name)) { string optName = Util.GetOptByIndex(index).name; string optArg = null; if (Util.GetOptByIndex(index).needArg) { optArg = ""; } opts.Add(optName, optArg); EnableDisableButtons(); } } } private void optionsListView_SelectedIndexChanged(object sender, EventArgs e) { int i = optionsCategoryListBox.SelectedIndex; if (optionsListView.SelectedIndices.Count == 0) { HideArgumentControls(); descriptionLabel.Text = ""; return; } int j = optionsListView.SelectedIndices[0]; int index = Util.GetOptIndex(i, j); if (index == -1) { Debug.Assert(false, string.Format("Opt not found, i={0}, j={1}.", i, j)); return; } descriptionLabel.Text = Util.GetOptByIndex(index).description; HideArgumentControls(); if (Util.GetOptByIndex(index).needArg) { argumentLabel.Text = Util.GetOptByIndex(index).argumentLabel + ":"; argumentLabel.Show(); argumentTextBox.Show(); string action = Util.GetOptByIndex(index).action; if (action == "ShowDir" || action == "ShowOpen" || action == "ShowSave") { argumentButton.Show(); } } SetText(); } private void startOnOkCheckBox_CheckedChanged(object sender, EventArgs e) { Util.PutSetting("JobDialogStartOnOk", startOnOkCheckBox.Checked.ToString()); } private string GetPresetValue(string presetName) { int i = SearchPresets(presetName); return (i != -1) ? presets[i].value : null; } void SyncGeneralOpts() { directoryPrefixComboBox.TextChanged -= new EventHandler(directoryPrefixComboBox_TextChanged); directoryPrefixComboBox.Text = opts.ContainsKey("directory-prefix") ? opts["directory-prefix"] : ""; directoryPrefixComboBox.TextChanged += new EventHandler(directoryPrefixComboBox_TextChanged); continueCheckBox.CheckedChanged -= new EventHandler(continueCheckBox_CheckedChanged); continueCheckBox.Checked = opts.ContainsKey("continue"); continueCheckBox.CheckedChanged += new EventHandler(continueCheckBox_CheckedChanged); timestampingCheckBox.CheckedChanged -= new EventHandler(timestampingCheckBox_CheckedChanged); timestampingCheckBox.Checked = opts.ContainsKey("timestamping"); timestampingCheckBox.CheckedChanged += new EventHandler(timestampingCheckBox_CheckedChanged); outputDocumentTextBox.TextChanged -= new EventHandler(outputDocumentTextBox_TextChanged); outputDocumentTextBox.Text = opts.ContainsKey("output-document") ? opts["output-document"] : ""; outputDocumentTextBox.TextChanged += new EventHandler(outputDocumentTextBox_TextChanged); } void EnableDisableButtons() { if (optionsPresetComboBox.SelectedItem == null) { deleteButton.Enabled = false; } else { string presetValue = GetPresetValue(optionsPresetComboBox.SelectedItem.ToString()); Debug.Assert(presetValue != null); deleteButton.Enabled = true; } } private void optionsPresetComboBox_SelectedIndexChanged(object sender, EventArgs e) { Debug.Assert(optionsPresetComboBox.SelectedItem != null); string presetValue = GetPresetValue(optionsPresetComboBox.SelectedItem.ToString()); Debug.Assert(presetValue != null); UpdateOpts(presetValue); SetChecked(); SetText(); EnableDisableButtons(); } private int SearchPresets(string presetName) { for (int i = 0; i < presets.Count; i++) { if (string.Compare(presets[i].name, presetName, true) == 0) { return i; } } return -1; } private int SearchPresetsValue(string presetValue) { for (int i = 0; i < presets.Count; i++) { if (string.Compare(presets[i].value, presetValue, false) == 0) { return i; } } return -1; } private void saveAsButton_Click(object sender, EventArgs e) { string presetValue = GetOptsString(); int i = SearchPresetsValue(presetValue); if (i != -1) { if (Util.MsgBox(string.Format(Util.translationList["000179"], presets[i].name), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return; } } SavePresetInfo savePresetInfo = new SavePresetInfo("", optionsPresetComboBox); SavePresetDialog savePresetDialog = new SavePresetDialog(savePresetInfo); if (savePresetDialog.ShowDialog(this) == DialogResult.OK) { if (i != -1) { presets.RemoveAt(i); } i = SearchPresets(savePresetDialog.PresetName); if (i != -1) { presets.RemoveAt(i); } Preset p; p.name = savePresetDialog.PresetName; p.value = presetValue; presets.Add(p); UpdateOptionsPresetComboBox(); savePresets = true; } savePresetDialog.Dispose(); } private void directoryPrefixButton_Click(object sender, EventArgs e) { folderBrowserDialog1.Description = "Please select a folder."; if (Directory.Exists(directoryPrefixComboBox.Text)) { folderBrowserDialog1.SelectedPath = directoryPrefixComboBox.Text; } if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK) { directoryPrefixComboBox.Text = folderBrowserDialog1.SelectedPath; } } private void continueCheckBox_CheckedChanged(object sender, EventArgs e) { if (!continueCheckBox.Checked) { if (opts.ContainsKey("continue")) { opts.Remove("continue"); } } else { if (!opts.ContainsKey("continue")) { opts.Add("continue", null); } } } private void timestampingCheckBox_CheckedChanged(object sender, EventArgs e) { if (!timestampingCheckBox.Checked) { if (opts.ContainsKey("timestamping")) { opts.Remove("timestamping"); } } else { if (!opts.ContainsKey("timestamping")) { opts.Add("timestamping", null); } } } private void resetLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { UpdateOpts(""); SetChecked(); SetText(); EnableDisableButtons(); } private void directoryPrefixComboBox_TextChanged(object sender, EventArgs e) { if (directoryPrefixComboBox.Text == "") { opts.Remove("directory-prefix"); } else { opts["directory-prefix"] = directoryPrefixComboBox.Text; } } private void JobDialog_FormClosing(object sender, FormClosingEventArgs e) { if (savePresets) { SavePresets(); } } private void outputDocumentTextBox_TextChanged(object sender, EventArgs e) { if (outputDocumentTextBox.Text == "") { opts.Remove("output-document"); } else { opts["output-document"] = outputDocumentTextBox.Text; } } private void outputDocumentButton_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "All Files (*.*)|*.*"; if (File.Exists(outputDocumentTextBox.Text)) { saveFileDialog1.FileName = Path.GetFileName(outputDocumentTextBox.Text); saveFileDialog1.InitialDirectory = Path.GetDirectoryName(outputDocumentTextBox.Text); } if (saveFileDialog1.ShowDialog(this) == DialogResult.OK) { outputDocumentTextBox.Text = saveFileDialog1.FileName; } } private void scheduleCheckBox_CheckedChanged(object sender, EventArgs e) { autoStartNumDaysNumericUpDown.Enabled = autoStartCheckBox.Checked; autoStartNumHoursNumericUpDown.Enabled = (autoStartCheckBox.Checked && (autoStartNumDaysNumericUpDown.Value == 0)); } public int AutoStartNumDays { get { if (autoStartCheckBox.Checked) { return Convert.ToInt32(autoStartNumDaysNumericUpDown.Value); } else { return 0; } } set { if (value >= 1 && value <= 365) { // Please set AutoStartNumHours after AutoStartNumDays to enable the checkbox //autoStartCheckBox.Checked = true; autoStartNumDaysNumericUpDown.Value = Convert.ToDecimal(value); } else { // Please set AutoStartNumHours after AutoStartNumDays to disble the checkbox //autoStartCheckBox.Checked = false; } } } public int AutoStartNumHours { get { if (autoStartCheckBox.Checked) { return Convert.ToInt32(autoStartNumHoursNumericUpDown.Value); } else { return 0; } } set { if (value >= 1 && value <= 168) { autoStartCheckBox.Checked = true; autoStartNumHoursNumericUpDown.Value = Convert.ToDecimal(value); } else { int daysValue = Convert.ToInt32(autoStartNumDaysNumericUpDown.Value); if (daysValue >= 1 && daysValue <= 365) { autoStartCheckBox.Checked = true; } else { autoStartCheckBox.Checked = false; } } } } public string NoteText { get { return noteTextBox.Text; } set { noteTextBox.Text = value; } } private void autoStartNumDaysNumericUpDown_ValueChanged(object sender, EventArgs e) { autoStartNumHoursNumericUpDown.Enabled = (autoStartNumDaysNumericUpDown.Value == 0); } private void SetInterFaceFont() { this.Font = Util.GetInterfaceFont(); } private void jobCatListBox_SelectedIndexChanged(object sender, EventArgs e) { if (this.jobCatListBox.SelectedIndex == (int)JobOptionCategory.General) { DisableAllPanels(); this.generalPanel.Enabled = true; this.generalPanel.BringToFront(); SyncGeneralOpts(); } else if (this.jobCatListBox.SelectedIndex == (int)JobOptionCategory.Http) { DisableAllPanels(); this.httpPanel.Enabled = true; this.httpPanel.BringToFront(); SyncHttpOpts(); } else if (this.jobCatListBox.SelectedIndex == (int)JobOptionCategory.Advanced) { DisableAllPanels(); this.advancedPanel.Enabled = true; this.advancedPanel.BringToFront(); EnableDisableButtons(); SetChecked(); SetText(); } } private void SyncHttpOpts() { userAgentComboBox.SelectedIndexChanged -= new EventHandler(userAgentComboBox_SelectedIndexChanged); int i; for (i = 0; i < userAgentComboBox.Items.Count; i++) { UserAgentItem userAgentItem = (UserAgentItem)userAgentComboBox.Items[i]; if (opts.ContainsKey("user-agent") && opts["user-agent"] == userAgentItem.value) { userAgentComboBox.SelectedItem = userAgentItem; break; } } if (i == userAgentComboBox.Items.Count) { userAgentComboBox.SelectedIndex = -1; } userAgentComboBox.SelectedIndexChanged += new EventHandler(userAgentComboBox_SelectedIndexChanged); refererTextBox.TextChanged -= new EventHandler(refererTextBox_TextChanged); refererTextBox.Text = opts.ContainsKey("referer") ? opts["referer"] : ""; refererTextBox.TextChanged += new EventHandler(refererTextBox_TextChanged); } private void DisableAllPanels() { this.generalPanel.Enabled = false; this.httpPanel.Enabled = false; this.advancedPanel.Enabled = false; } private void loadEmptyButton_Click(object sender, EventArgs e) { UpdateOpts(""); SetChecked(); SetText(); EnableDisableButtons(); } private void outputDocumentTextBox_Leave(object sender, EventArgs e) { string directoryPrefixText = directoryPrefixComboBox.Text.Trim(); string outputDocumentText = outputDocumentTextBox.Text.Trim(); if (directoryPrefixText.Length > 0 && outputDocumentText.Length > 0) { if (Path.GetDirectoryName(outputDocumentText).Length == 0) { outputDocumentTextBox.Text = Path.Combine(directoryPrefixText, outputDocumentText); } } } private void userAgentComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (userAgentComboBox.SelectedIndex == -1) { opts.Remove("user-agent"); } else { opts["user-agent"] = ((UserAgentItem)userAgentComboBox.SelectedItem).value; } } private void refererTextBox_TextChanged(object sender, EventArgs e) { if (refererTextBox.Text == "") { opts.Remove("referer"); } else { opts["referer"] = refererTextBox.Text; } } } }
using System.Collections.Generic; using System.IO; using System.Text; using MirrorSharp.Advanced; using SharpLab.Runtime.Internal; namespace SharpLab.Server.Execution.Internal { public class ExecutionResultSerializer { public void Serialize(ExecutionResult result, IFastJsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyStartArray("output"); SerializeOutput(result.Output, writer); writer.WriteEndArray(); writer.WritePropertyStartArray("flow"); foreach (var step in result.Flow) { SerializeFlowStep(step, writer); } writer.WriteEndArray(); writer.WriteEndObject(); } private void SerializeFlowStep(Flow.Step step, IFastJsonWriter writer) { if (step.Notes == null && step.Exception == null) { writer.WriteValue(step.LineNumber); return; } writer.WriteStartObject(); writer.WriteProperty("line", step.LineNumber); if (step.LineSkipped) writer.WriteProperty("skipped", true); if (step.Notes != null) writer.WriteProperty("notes", step.Notes); if (step.Exception != null) writer.WriteProperty("exception", step.Exception.GetType().Name); writer.WriteEndObject(); } private void SerializeOutput(IReadOnlyList<object> output, IFastJsonWriter writer) { TextWriter? openStringWriter = null; void CloseStringWriter() { if (openStringWriter != null) { openStringWriter.Close(); openStringWriter = null; } } foreach (var item in output) { switch (item) { case IInspection inspection: CloseStringWriter(); SerializeInspection(inspection, writer); break; case string @string: if (openStringWriter == null) openStringWriter = writer.OpenString(); openStringWriter.Write(@string); break; case char[] chars: if (openStringWriter == null) openStringWriter = writer.OpenString(); openStringWriter.Write(chars); break; case null: break; default: CloseStringWriter(); writer.WriteValue("Unsupported output object type: " + item.GetType().Name); break; } } openStringWriter?.Close(); } private void SerializeInspection(IInspection inspection, IFastJsonWriter writer) { switch (inspection) { case SimpleInspection simple: SerializeSimpleInspection(simple, writer); break; case MemoryInspection memory: SerializeMemoryInspection(memory, writer); break; case MemoryGraphInspection graph: SerializeMemoryGraphInspection(graph, writer); break; case InspectionGroup group: SerializeInspectionGroup(group, writer); break; default: writer.WriteValue("Unsupported inspection type: " + inspection.GetType().Name); break; } } private void SerializeSimpleInspection(SimpleInspection inspection, IFastJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("type", "inspection:simple"); writer.WriteProperty("title", inspection.Title); if (inspection.HasValue) { writer.WritePropertyName("value"); if (inspection.Value is StringBuilder builder) { writer.WriteValue(builder); } else { writer.WriteValue((string)inspection.Value!); } } writer.WriteEndObject(); } private void SerializeMemoryInspection(MemoryInspection memory, IFastJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("type", "inspection:memory"); writer.WriteProperty("title", memory.Title); writer.WritePropertyStartArray("labels"); foreach (var label in memory.Labels) { SerializeMemoryInspectionLabel(writer, label); } writer.WriteEndArray(); writer.WritePropertyStartArray("data"); foreach (var @byte in memory.Data) { writer.WriteValue(@byte); } writer.WriteEndArray(); writer.WriteEndObject(); } private void SerializeMemoryInspectionLabel(IFastJsonWriter writer, MemoryInspectionLabel label) { writer.WriteStartObject(); writer.WriteProperty("name", label.Name); writer.WriteProperty("offset", label.Offset); writer.WriteProperty("length", label.Length); if (label.Nested.Count > 0) { writer.WritePropertyStartArray("nested"); foreach (var nested in label.Nested) { SerializeMemoryInspectionLabel(writer, nested); } writer.WriteEndArray(); } writer.WriteEndObject(); } private void SerializeMemoryGraphInspection(MemoryGraphInspection graph, IFastJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("type", "inspection:memory-graph"); writer.WritePropertyStartArray("stack"); foreach (var node in graph.Stack) { SerializeMemoryGraphNode(writer, node); } writer.WriteEndArray(); writer.WritePropertyStartArray("heap"); foreach (var node in graph.Heap) { SerializeMemoryGraphNode(writer, node); } writer.WriteEndArray(); writer.WritePropertyStartArray("references"); foreach (var reference in graph.References) { SerializeMemoryGraphReference(writer, reference); } writer.WriteEndArray(); writer.WriteEndObject(); } private void SerializeMemoryGraphNode(IFastJsonWriter writer, MemoryGraphNode node) { writer.WriteStartObject(); writer.WriteProperty("id", node.Id); if (node.StackOffset != null) { writer.WriteProperty("offset", node.StackOffset.Value); writer.WriteProperty("size", node.StackSize!.Value); } writer.WriteProperty("title", node.Title); writer.WritePropertyName("value"); if (node.Value is StringBuilder builder) { writer.WriteValue(builder); } else { writer.WriteValue((string)node.Value); } if (node.NestedNodes.Count > 0) { writer.WritePropertyStartArray("nestedNodes"); foreach (var nested in node.NestedNodes) { SerializeMemoryGraphNode(writer, nested); } writer.WriteEndArray(); if (node.NestedNodesLimitReached) writer.WriteProperty("nestedNodesLimit", true); } writer.WriteEndObject(); } private void SerializeMemoryGraphReference(IFastJsonWriter writer, MemoryGraphReference reference) { writer.WriteStartObject(); writer.WriteProperty("from", reference.From.Id); writer.WriteProperty("to", reference.To.Id); writer.WriteEndObject(); } private void SerializeInspectionGroup(InspectionGroup group, IFastJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("type", "inspection:group"); writer.WriteProperty("title", group.Title); writer.WritePropertyStartArray("inspections"); foreach (var inspection in group.Inspections) { SerializeInspection(inspection, writer); } writer.WriteEndArray(); if (group.LimitReached) writer.WriteProperty("limitReached", true); writer.WriteEndObject(); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Diagnostics; using System.IO; using System.Reflection; namespace Microsoft.PythonTools.Interpreter { public sealed class InterpreterConfiguration { readonly string _prefixPath, _id, _description, _descriptionSuffix; readonly string _interpreterPath; readonly string _windowsInterpreterPath; readonly string _libraryPath; readonly string _pathEnvironmentVariable; readonly ProcessorArchitecture _architecture; readonly Version _version; readonly InterpreterUIMode _uiMode; /// <summary> /// <para>Constructs a new interpreter configuration based on the /// provided values.</para> /// <para>No validation is performed on the parameters.</para> /// <para>If winPath is null or empty, /// <see cref="WindowsInterpreterPath"/> will be set to path.</para> /// <para>If libraryPath is null or empty and prefixPath is a valid /// file system path, <see cref="LibraryPath"/> will be set to /// prefixPath plus "Lib".</para> /// </summary> public InterpreterConfiguration( string id, string description, string prefixPath = null, string path = null, string winPath = "", string libraryPath = "", string pathVar = "", ProcessorArchitecture arch = ProcessorArchitecture.None, Version version = null, InterpreterUIMode uiMode = InterpreterUIMode.Normal, string descriptionSuffix = "" ) { _id = id; _description = description; _prefixPath = prefixPath; _interpreterPath = path; _windowsInterpreterPath = string.IsNullOrEmpty(winPath) ? path : winPath; _libraryPath = libraryPath; if (string.IsNullOrEmpty(_libraryPath) && !string.IsNullOrEmpty(_prefixPath)) { try { _libraryPath = Path.Combine(_prefixPath, "Lib"); } catch (ArgumentException) { } } _pathEnvironmentVariable = pathVar; _architecture = arch; _version = version; _uiMode = uiMode; _descriptionSuffix = descriptionSuffix; } /// <summary> /// Gets a unique and stable identifier for this interpreter. /// </summary> public string Id => _id; /// <summary> /// Gets a friendly description of the interpreter /// </summary> public string Description => _description; public string FullDescription { get { string res = _description; var arch = _architecture; if (arch == ProcessorArchitecture.Amd64) { res += " 64-bit"; } else if (arch == ProcessorArchitecture.X86) { res += " 32-bit"; } if (_version != null && _version != new Version()) { res += " " + _version.ToString(); } if (!string.IsNullOrEmpty(_descriptionSuffix)) { res += " " + _descriptionSuffix; } return res; } } /// <summary> /// Returns the prefix path of the Python installation. All files /// related to the installation should be underneath this path. /// </summary> public string PrefixPath { get { return _prefixPath; } } /// <summary> /// Returns the path to the interpreter executable for launching Python /// applications. /// </summary> public string InterpreterPath { get { return _interpreterPath; } } /// <summary> /// Returns the path to the interpreter executable for launching Python /// applications which are windows applications (pythonw.exe, ipyw.exe). /// </summary> public string WindowsInterpreterPath { get { return _windowsInterpreterPath; } } /// <summary> /// The path to the standard library associated with this interpreter. /// This may be null if the interpreter does not support standard /// library analysis. /// </summary> public string LibraryPath { get { return _libraryPath; } } /// <summary> /// Gets the environment variable which should be used to set sys.path. /// </summary> public string PathEnvironmentVariable { get { return _pathEnvironmentVariable; } } /// <summary> /// The architecture of the interpreter executable. /// </summary> public ProcessorArchitecture Architecture { get { return _architecture; } } public string ArchitectureString { get { switch (Architecture) { case ProcessorArchitecture.Amd64: return "x64"; case ProcessorArchitecture.X86: return "x86"; default: return string.Empty; } } } /// <summary> /// The language version of the interpreter (e.g. 2.7). /// </summary> public Version Version { get { return _version; } } /// <summary> /// The UI behavior of the interpreter. /// </summary> /// <remarks> /// New in 2.2 /// </remarks> public InterpreterUIMode UIMode { get { return _uiMode; } } public override bool Equals(object obj) { var other = obj as InterpreterConfiguration; if (other == null) { return false; } var cmp = StringComparer.OrdinalIgnoreCase; return cmp.Equals(PrefixPath, other.PrefixPath) && string.Equals(Id, other.Id) && cmp.Equals(InterpreterPath, other.InterpreterPath) && cmp.Equals(WindowsInterpreterPath, other.WindowsInterpreterPath) && cmp.Equals(LibraryPath, other.LibraryPath) && cmp.Equals(PathEnvironmentVariable, other.PathEnvironmentVariable) && Architecture == other.Architecture && Version == other.Version && UIMode == other.UIMode; } public override int GetHashCode() { var cmp = StringComparer.OrdinalIgnoreCase; return cmp.GetHashCode(PrefixPath ?? "") ^ Id.GetHashCode() ^ cmp.GetHashCode(InterpreterPath ?? "") ^ cmp.GetHashCode(WindowsInterpreterPath ?? "") ^ cmp.GetHashCode(LibraryPath ?? "") ^ cmp.GetHashCode(PathEnvironmentVariable ?? "") ^ Architecture.GetHashCode() ^ Version.GetHashCode() ^ UIMode.GetHashCode(); } public override string ToString() { return FullDescription; } } }
// // SecureMimeContext.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013 Jeffrey Stedfast // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Collections; using System.Collections.Generic; using Org.BouncyCastle.Cms; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Pkix; using Org.BouncyCastle.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.X509.Store; using Org.BouncyCastle.Utilities.Date; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Asn1.Smime; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.Ntt; namespace MimeKit.Cryptography { /// <summary> /// A Secure MIME (S/MIME) cryptography context. /// </summary> /// <remarks> /// Generally speaking, applications should not use a <see cref="SecureMimeContext"/> /// directly, but rather via higher level APIs such as <see cref="MultipartSigned"/> /// and <see cref="ApplicationPkcs7Mime"/>. /// </remarks> public abstract class SecureMimeContext : CryptographyContext { static readonly int EncryptionAlgorithmCount = Enum.GetValues (typeof (EncryptionAlgorithm)).Length; static readonly EncryptionAlgorithm[] DefaultEncryptionAlgorithmRank; int enabled; static SecureMimeContext () { DefaultEncryptionAlgorithmRank = new EncryptionAlgorithm[] { EncryptionAlgorithm.Camellia256, EncryptionAlgorithm.Aes256, EncryptionAlgorithm.Camellia192, EncryptionAlgorithm.Aes192, EncryptionAlgorithm.Camellia128, EncryptionAlgorithm.Aes128, EncryptionAlgorithm.Idea, EncryptionAlgorithm.Cast5, EncryptionAlgorithm.TripleDes, EncryptionAlgorithm.RC2128, EncryptionAlgorithm.RC264, EncryptionAlgorithm.Des, EncryptionAlgorithm.RC240 }; } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.SecureMimeContext"/> class. /// </summary> /// <remarks> /// <para>Enables the following encryption algorithms by default:</para> /// <list type="bullet"> /// <item><term><see cref="EncryptionAlgorithm.Camellia256"/></term></item> /// <item><term><see cref="EncryptionAlgorithm.Camellia192"/></term></item> /// <item><term><see cref="EncryptionAlgorithm.Camellia128"/></term></item> /// <item><term><see cref="EncryptionAlgorithm.Aes256"/></term></item> /// <item><term><see cref="EncryptionAlgorithm.Aes192"/></term></item> /// <item><term><see cref="EncryptionAlgorithm.Aes128"/></term></item> /// <item><term><see cref="EncryptionAlgorithm.Cast5"/></term></item> /// <item><term><see cref="EncryptionAlgorithm.Idea"/></term></item> /// <item><term><see cref="EncryptionAlgorithm.TripleDes"/></term></item> /// </list> /// </remarks> protected SecureMimeContext () { foreach (var algorithm in DefaultEncryptionAlgorithmRank) { Enable (algorithm); // Don't enable anything weaker than Triple-DES by default if (algorithm == EncryptionAlgorithm.TripleDes) break; } } /// <summary> /// Gets the signature protocol. /// </summary> /// <remarks> /// <para>The signature protocol is used by <see cref="MultipartSigned"/> /// in order to determine what the protocol parameter of the Content-Type /// header should be.</para> /// </remarks> /// <value>The signature protocol.</value> public override string SignatureProtocol { get { return "application/pkcs7-signature"; } } /// <summary> /// Gets the encryption protocol. /// </summary> /// <remarks> /// <para>The encryption protocol is used by <see cref="MultipartEncrypted"/> /// in order to determine what the protocol parameter of the Content-Type /// header should be.</para> /// </remarks> /// <value>The encryption protocol.</value> public override string EncryptionProtocol { get { return "application/pkcs7-mime"; } } /// <summary> /// Gets the key exchange protocol. /// </summary> /// <value>The key exchange protocol.</value> public override string KeyExchangeProtocol { get { return "application/pkcs7-mime"; } } /// <summary> /// Checks whether or not the specified protocol is supported by the <see cref="CryptographyContext"/>. /// </summary> /// <returns><c>true</c> if the protocol is supported; otherwise <c>false</c></returns> /// <param name="protocol">The protocol.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="protocol"/> is <c>null</c>. /// </exception> public override bool Supports (string protocol) { if (protocol == null) throw new ArgumentNullException ("protocol"); var type = protocol.ToLowerInvariant ().Split (new char[] { '/' }); if (type.Length != 2 || type[0] != "application") return false; if (type[1].StartsWith ("x-", StringComparison.Ordinal)) type[1] = type[1].Substring (2); return type[1] == "pkcs7-signature" || type[1] == "pkcs7-mime" || type[1] == "pkcs7-keys"; } /// <summary> /// Gets the string name of the digest algorithm for use with the micalg parameter of a multipart/signed part. /// </summary> /// <remarks> /// <para>Maps the <see cref="DigestAlgorithm"/> to the appropriate string identifier /// as used by the micalg parameter value of a multipart/signed Content-Type /// header. For example:</para> /// <list type="table"> /// <listheader><term>Algorithm</term><description>Name</description></listheader> /// <item><term><see cref="DigestAlgorithm.MD5"/></term><description>md5</description></item> /// <item><term><see cref="DigestAlgorithm.Sha1"/></term><description>sha-1</description></item> /// <item><term><see cref="DigestAlgorithm.Sha224"/></term><description>sha-224</description></item> /// <item><term><see cref="DigestAlgorithm.Sha256"/></term><description>sha-256</description></item> /// <item><term><see cref="DigestAlgorithm.Sha384"/></term><description>sha-384</description></item> /// <item><term><see cref="DigestAlgorithm.Sha512"/></term><description>sha-512</description></item> /// </list> /// </remarks> /// <returns>The micalg value.</returns> /// <param name="micalg">The digest algorithm.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="micalg"/> is out of range. /// </exception> public override string GetDigestAlgorithmName (DigestAlgorithm micalg) { switch (micalg) { case DigestAlgorithm.MD5: return "md5"; case DigestAlgorithm.Sha1: return "sha-1"; case DigestAlgorithm.RipeMD160: return "ripemd160"; case DigestAlgorithm.MD2: return "md2"; case DigestAlgorithm.Tiger192: return "tiger192"; case DigestAlgorithm.Haval5160: return "haval-5-160"; case DigestAlgorithm.Sha256: return "sha-256"; case DigestAlgorithm.Sha384: return "sha-384"; case DigestAlgorithm.Sha512: return "sha-512"; case DigestAlgorithm.Sha224: return "sha-224"; case DigestAlgorithm.MD4: return "md4"; default: throw new ArgumentOutOfRangeException ("micalg"); } } /// <summary> /// Gets the digest algorithm from the micalg parameter value in a multipart/signed part. /// </summary> /// <remarks> /// Maps the micalg parameter value string back to the appropriate <see cref="DigestAlgorithm"/>. /// </remarks> /// <returns>The digest algorithm.</returns> /// <param name="micalg">The micalg parameter value.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="micalg"/> is <c>null</c>. /// </exception> public override DigestAlgorithm GetDigestAlgorithm (string micalg) { if (micalg == null) throw new ArgumentNullException ("micalg"); switch (micalg.ToLowerInvariant ()) { case "md5": return DigestAlgorithm.MD5; case "sha-1": return DigestAlgorithm.Sha1; case "ripemd160": return DigestAlgorithm.RipeMD160; case "md2": return DigestAlgorithm.MD2; case "tiger192": return DigestAlgorithm.Tiger192; case "haval-5-160": return DigestAlgorithm.Haval5160; case "sha-256": return DigestAlgorithm.Sha256; case "sha-384": return DigestAlgorithm.Sha384; case "sha-512": return DigestAlgorithm.Sha512; case "sha-224": return DigestAlgorithm.Sha224; case "md4": return DigestAlgorithm.MD4; default: return DigestAlgorithm.None; } } /// <summary> /// Gets the preferred rank order for the encryption algorithms; from the strongest to the weakest. /// </summary> /// <value>The preferred encryption algorithm ranking.</value> protected virtual EncryptionAlgorithm[] EncryptionAlgorithmRank { get { return DefaultEncryptionAlgorithmRank; } } /// <summary> /// Gets the enabled encryption algorithms in ranked order. /// </summary> /// <value>The enabled encryption algorithms.</value> protected EncryptionAlgorithm[] EnabledEncryptionAlgorithms { get { var algorithms = new List<EncryptionAlgorithm> (); foreach (var algorithm in EncryptionAlgorithmRank) { if (IsEnabled (algorithm)) algorithms.Add (algorithm); } return algorithms.ToArray (); } } /// <summary> /// Enables the encryption algorithm. /// </summary> /// <param name="algorithm">The encryption algorithm.</param> public void Enable (EncryptionAlgorithm algorithm) { enabled |= 1 << (int) algorithm; } /// <summary> /// Disables the encryption algorithm. /// </summary> /// <param name="algorithm">The encryption algorithm.</param> public void Disable (EncryptionAlgorithm algorithm) { enabled &= ~(1 << (int) algorithm); } /// <summary> /// Determines whether the specified encryption algorithm is enabled. /// </summary> /// <returns><c>true</c> if the specified encryption algorithm is enabled; otherwise, <c>false</c>.</returns> /// <param name="algorithm">Algorithm.</param> public bool IsEnabled (EncryptionAlgorithm algorithm) { return (enabled & (1 << (int) algorithm)) != 0; } /// <summary> /// Gets the X.509 certificate matching the specified selector. /// </summary> /// <returns>The certificate on success; otherwise <c>null</c>.</returns> /// <param name="selector">The search criteria for the certificate.</param> protected abstract X509Certificate GetCertificate (IX509Selector selector); /// <summary> /// Gets the private key for the certificate matching the specified selector. /// </summary> /// <returns>The private key on success; otherwise <c>null</c>.</returns> /// <param name="selector">The search criteria for the private key.</param> protected abstract AsymmetricKeyParameter GetPrivateKey (IX509Selector selector); /// <summary> /// Gets the trusted anchors. /// </summary> /// <remarks> /// A trusted anchor is a trusted root-level X.509 certificate, /// generally issued by a certificate authority (CA). /// </remarks> /// <returns>The trusted anchors.</returns> protected abstract HashSet GetTrustedAnchors (); /// <summary> /// Gets the intermediate certificates. /// </summary> /// <remarks> /// An intermediate certificate is any certificate that exists between the root /// certificate issued by a Certificate Authority (CA) and the certificate at /// the end of the chain. /// </remarks> /// <returns>The intermediate certificates.</returns> protected abstract IX509Store GetIntermediateCertificates (); /// <summary> /// Gets the certificate revocation lists. /// </summary> /// <remarks> /// A Certificate Revocation List (CRL) is a list of certificate serial numbers issued /// by a particular Certificate Authority (CA) that have been revoked, either by the CA /// itself or by the owner of the revoked certificate. /// </remarks> /// <returns>The certificate revocation lists.</returns> protected abstract IX509Store GetCertificateRevocationLists (); /// <summary> /// Gets the <see cref="CmsRecipient"/> for the specified mailbox. /// </summary> /// <remarks> /// <para>Constructs a <see cref="CmsRecipient"/> with the appropriate certificate and /// <see cref="CmsRecipient.EncryptionAlgorithms"/> for the specified mailbox.</para> /// <para>If the mailbox is a <see cref="SecureMailboxAddress"/>, the /// <see cref="SecureMailboxAddress.Fingerprint"/> property will be used instead of /// the mailbox address.</para> /// </remarks> /// <returns>A <see cref="CmsRecipient"/>.</returns> /// <param name="mailbox">The mailbox.</param> /// <exception cref="CertificateNotFoundException"> /// A certificate for the specified <paramref name="mailbox"/> could not be found. /// </exception> protected abstract CmsRecipient GetCmsRecipient (MailboxAddress mailbox); /// <summary> /// Gets the <see cref="CmsRecipient"/>s for the specified <see cref="MimeKit.MailboxAddress"/>es. /// </summary> /// <returns>The <see cref="CmsRecipient"/>s.</returns> /// <param name="mailboxes">The mailboxes.</param> /// <exception cref="CertificateNotFoundException"> /// A certificate for one or more of the specified <paramref name="mailboxes"/> could not be found. /// </exception> protected CmsRecipientCollection GetCmsRecipients (IEnumerable<MailboxAddress> mailboxes) { var recipients = new CmsRecipientCollection (); foreach (var mailbox in mailboxes) recipients.Add (GetCmsRecipient (mailbox)); return recipients; } /// <summary> /// Gets the <see cref="CmsSigner"/> for the specified mailbox. /// </summary> /// <returns>A <see cref="CmsSigner"/>.</returns> /// <param name="mailbox">The mailbox.</param> /// <param name="digestAlgo">The preferred digest algorithm.</param> /// <exception cref="CertificateNotFoundException"> /// A certificate for the specified <paramref name="mailbox"/> could not be found. /// </exception> protected abstract CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo); /// <summary> /// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate. /// </summary> /// <param name="certificate">The certificate.</param> /// <param name="algorithms">The encryption algorithm capabilities of the client (in preferred order).</param> /// <param name="timestamp">The timestamp.</param> protected abstract void UpdateSecureMimeCapabilities (X509Certificate certificate, EncryptionAlgorithm[] algorithms, DateTime timestamp); /// <summary> /// Gets the digest oid. /// </summary> /// <returns>The digest oid.</returns> /// <param name="digestAlgo">The digest algorithm.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="digestAlgo"/> is out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// The specified <see cref="DigestAlgorithm"/> is not supported by this context. /// </exception> protected static string GetDigestOid (DigestAlgorithm digestAlgo) { switch (digestAlgo) { case DigestAlgorithm.MD5: return PkcsObjectIdentifiers.MD5.Id; case DigestAlgorithm.Sha1: return PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id; case DigestAlgorithm.MD2: return PkcsObjectIdentifiers.MD2.Id; case DigestAlgorithm.Sha256: return PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id; case DigestAlgorithm.Sha384: return PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id; case DigestAlgorithm.Sha512: return PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id; case DigestAlgorithm.Sha224: return PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id; case DigestAlgorithm.MD4: return PkcsObjectIdentifiers.MD4.Id; case DigestAlgorithm.RipeMD160: case DigestAlgorithm.DoubleSha: case DigestAlgorithm.Tiger192: case DigestAlgorithm.Haval5160: throw new NotSupportedException (); default: throw new ArgumentOutOfRangeException (); } } /// <summary> /// Compress the specified stream. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance /// containing the compressed content.</returns> /// <param name="stream">The stream to compress.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public ApplicationPkcs7Mime Compress (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); var compresser = new CmsCompressedDataGenerator (); var processable = new CmsProcessableInputStream (stream); var compressed = compresser.Generate (processable, CmsCompressedDataGenerator.ZLib); var encoded = compressed.GetEncoded (); return new ApplicationPkcs7Mime (SecureMimeType.CompressedData, new MemoryStream (encoded, false)); } /// <summary> /// Decompress the specified stream. /// </summary> /// <returns>The decompressed mime part.</returns> /// <param name="stream">The stream to decompress.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public MimeEntity Decompress (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); var parser = new CmsCompressedDataParser (stream); var content = parser.GetContent (); return MimeEntity.Load (content.ContentStream); } Org.BouncyCastle.Asn1.Cms.AttributeTable AddSecureMimeCapabilities (Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttributes) { var capabilities = new SmimeCapabilityVector (); foreach (var algorithm in EncryptionAlgorithmRank) { if (!IsEnabled (algorithm)) continue; switch (algorithm) { case EncryptionAlgorithm.Camellia256: capabilities.AddCapability (NttObjectIdentifiers.IdCamellia256Cbc); break; case EncryptionAlgorithm.Camellia192: capabilities.AddCapability (NttObjectIdentifiers.IdCamellia192Cbc); break; case EncryptionAlgorithm.Camellia128: capabilities.AddCapability (NttObjectIdentifiers.IdCamellia128Cbc); break; case EncryptionAlgorithm.Aes256: capabilities.AddCapability (SmimeCapabilities.Aes256Cbc); break; case EncryptionAlgorithm.Aes192: capabilities.AddCapability (SmimeCapabilities.Aes192Cbc); break; case EncryptionAlgorithm.Aes128: capabilities.AddCapability (SmimeCapabilities.Aes128Cbc); break; case EncryptionAlgorithm.Idea: capabilities.AddCapability (SmimeCapabilities.IdeaCbc); break; case EncryptionAlgorithm.Cast5: capabilities.AddCapability (SmimeCapabilities.Cast5Cbc); break; case EncryptionAlgorithm.TripleDes: capabilities.AddCapability (SmimeCapabilities.DesEde3Cbc); break; case EncryptionAlgorithm.RC2128: capabilities.AddCapability (SmimeCapabilities.RC2Cbc, 128); break; case EncryptionAlgorithm.RC264: capabilities.AddCapability (SmimeCapabilities.RC2Cbc, 64); break; case EncryptionAlgorithm.RC240: capabilities.AddCapability (SmimeCapabilities.RC2Cbc, 40); break; case EncryptionAlgorithm.Des: capabilities.AddCapability (SmimeCapabilities.DesCbc); break; } } var attr = new SmimeCapabilitiesAttribute (capabilities); // populate our signed attributes with some S/MIME capabilities return signedAttributes.Add (attr.AttrType, attr.AttrValues[0]); } Stream Sign (CmsSigner signer, Stream content, bool encapsulate) { var signedData = new CmsSignedDataStreamGenerator (); signedData.AddSigner (signer.PrivateKey, signer.Certificate, GetDigestOid (signer.DigestAlgorithm), AddSecureMimeCapabilities (signer.SignedAttributes), signer.UnsignedAttributes); var memory = new MemoryStream (); using (var stream = signedData.Open (memory, encapsulate)) { content.CopyTo (stream, 4096); } memory.Position = 0; return memory; } /// <summary> /// Sign and encapsulate the content using the specified signer. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance /// containing the detached signature data.</returns> /// <param name="signer">The signer.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public ApplicationPkcs7Mime EncapsulatedSign (CmsSigner signer, Stream content) { if (signer == null) throw new ArgumentNullException ("signer"); if (signer.Certificate == null) throw new ArgumentException ("No signer certificate specified.", "signer"); if (signer.PrivateKey == null) throw new ArgumentException ("No private key specified.", "signer"); if (content == null) throw new ArgumentNullException ("content"); return new ApplicationPkcs7Mime (SecureMimeType.SignedData, Sign (signer, content, true)); } /// <summary> /// Sign and encapsulate the content using the specified signer. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance /// containing the detached signature data.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="digestAlgo"/> is out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// The specified <see cref="DigestAlgorithm"/> is not supported by this context. /// </exception> /// <exception cref="CertificateNotFoundException"> /// A signing certificate could not be found for <paramref name="signer"/>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public virtual ApplicationPkcs7Mime EncapsulatedSign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content) { if (signer == null) throw new ArgumentNullException ("signer"); if (content == null) throw new ArgumentNullException ("content"); var cmsSigner = GetCmsSigner (signer, digestAlgo); return EncapsulatedSign (cmsSigner, content); } /// <summary> /// Sign the content using the specified signer. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Signature"/> instance /// containing the detached signature data.</returns> /// <param name="signer">The signer.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public ApplicationPkcs7Signature Sign (CmsSigner signer, Stream content) { if (signer == null) throw new ArgumentNullException ("signer"); if (signer.Certificate == null) throw new ArgumentException ("No signer certificate specified.", "signer"); if (signer.PrivateKey == null) throw new ArgumentException ("No private key specified.", "signer"); if (content == null) throw new ArgumentNullException ("content"); return new ApplicationPkcs7Signature (Sign (signer, content, false)); } /// <summary> /// Sign the content using the specified signer. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the detached signature data.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="digestAlgo"/> is out of range. /// </exception> /// <exception cref="System.NotSupportedException"> /// The specified <see cref="DigestAlgorithm"/> is not supported by this context. /// </exception> /// <exception cref="CertificateNotFoundException"> /// A signing certificate could not be found for <paramref name="signer"/>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content) { if (signer == null) throw new ArgumentNullException ("signer"); if (content == null) throw new ArgumentNullException ("content"); var cmsSigner = GetCmsSigner (signer, digestAlgo); return Sign (cmsSigner, content); } X509Certificate GetCertificate (IX509Store store, SignerID signer) { var matches = store.GetMatches (signer); foreach (X509Certificate certificate in matches) { return certificate; } return GetCertificate (signer); } PkixCertPath BuildCertPath (HashSet anchors, IX509Store certificates, IX509Store crls, X509Certificate certificate, DateTime? signingTime) { var intermediate = new X509CertificateStore (); foreach (X509Certificate cert in certificates.GetMatches (null)) intermediate.Add (cert); var selector = new X509CertStoreSelector (); selector.Certificate = certificate; var parameters = new PkixBuilderParameters (anchors, selector); parameters.AddStore (GetIntermediateCertificates ()); parameters.AddStore (intermediate); var localCrls = GetCertificateRevocationLists (); parameters.AddStore (localCrls); parameters.AddStore (crls); parameters.ValidityModel = PkixParameters.ChainValidityModel; parameters.IsRevocationEnabled = true; if (signingTime.HasValue) parameters.Date = new DateTimeObject (signingTime.Value); var result = new PkixCertPathBuilder ().Build (parameters); return result.CertPath; } /// <summary> /// Attempts to map a <see cref="Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier"/> /// to a <see cref="EncryptionAlgorithm"/>. /// </summary> /// <returns><c>true</c> if the algorithm identifier was successfully mapped; <c>false</c> otherwise.</returns> /// <param name="identifier">The algorithm identifier.</param> /// <param name="algorithm">The encryption algorithm.</param> protected static bool TryGetEncryptionAlgorithm (AlgorithmIdentifier identifier, out EncryptionAlgorithm algorithm) { if (identifier.ObjectID.Id == CmsEnvelopedGenerator.Aes256Cbc) { algorithm = EncryptionAlgorithm.Aes256; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.Aes192Cbc) { algorithm = EncryptionAlgorithm.Aes192; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.Aes128Cbc) { algorithm = EncryptionAlgorithm.Aes128; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.Camellia256Cbc) { algorithm = EncryptionAlgorithm.Camellia256; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.Camellia192Cbc) { algorithm = EncryptionAlgorithm.Camellia192; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.Camellia128Cbc) { algorithm = EncryptionAlgorithm.Camellia128; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.Cast5Cbc) { algorithm = EncryptionAlgorithm.Cast5; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.DesEde3Cbc) { algorithm = EncryptionAlgorithm.TripleDes; return true; } if (identifier.ObjectID.Id == SmimeCapability.DesCbc.Id) { algorithm = EncryptionAlgorithm.Des; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.IdeaCbc) { algorithm = EncryptionAlgorithm.Idea; return true; } if (identifier.ObjectID.Id == CmsEnvelopedGenerator.RC2Cbc) { var param = (DerInteger) identifier.Parameters; int bits = param.Value.IntValue; switch (bits) { case 128: algorithm = EncryptionAlgorithm.RC2128; return true; case 64: algorithm = EncryptionAlgorithm.RC264; return true; case 40: algorithm = EncryptionAlgorithm.RC240; return true; } } algorithm = EncryptionAlgorithm.RC240; return false; } DigitalSignatureCollection GetDigitalSignatures (CmsSignedDataParser parser) { var certificates = parser.GetCertificates ("Collection"); var signatures = new List<IDigitalSignature> (); var crls = parser.GetCrls ("Collection"); var store = parser.GetSignerInfos (); // FIXME: validate the certificates before importing them? foreach (X509Certificate certificate in certificates.GetMatches (null)) Import (certificate); // FIXME: validate the CRLs before importing them? foreach (X509Crl crl in crls.GetMatches (null)) Import (crl); foreach (SignerInformation signerInfo in store.GetSigners ()) { var certificate = GetCertificate (certificates, signerInfo.SignerID); var signature = new SecureMimeDigitalSignature (signerInfo); var algorithms = new List<EncryptionAlgorithm> (); DateTime? signedDate = null; if (signerInfo.SignedAttributes != null) { Asn1EncodableVector vector = signerInfo.SignedAttributes.GetAll (CmsAttributes.SigningTime); foreach (Org.BouncyCastle.Asn1.Cms.Attribute attr in vector) { var signingTime = (DerUtcTime) ((DerSet) attr.AttrValues)[0]; signature.CreationDate = signingTime.ToAdjustedDateTime (); signedDate = signature.CreationDate; break; } vector = signerInfo.SignedAttributes.GetAll (SmimeAttributes.SmimeCapabilities); foreach (Org.BouncyCastle.Asn1.Cms.Attribute attr in vector) { foreach (Asn1Sequence sequence in attr.AttrValues) { for (int i = 0; i < sequence.Count; i++) { var identifier = AlgorithmIdentifier.GetInstance (sequence[i]); EncryptionAlgorithm algorithm; if (TryGetEncryptionAlgorithm (identifier, out algorithm)) algorithms.Add (algorithm); } } } signature.EncryptionAlgorithms = algorithms.ToArray (); } if (certificate != null) { signature.SignerCertificate = new SecureMimeDigitalCertificate (certificate); if (algorithms.Count > 0 && signedDate.HasValue) UpdateSecureMimeCapabilities (certificate, signature.EncryptionAlgorithms, signedDate.Value); } var anchors = GetTrustedAnchors (); try { signature.Chain = BuildCertPath (anchors, certificates, crls, certificate, signedDate); } catch (Exception ex) { signature.ChainException = ex; } signatures.Add (signature); } return new DigitalSignatureCollection (signatures); } /// <summary> /// Verify the digital signatures of the specified content using the detached signatureData. /// </summary> /// <returns>A list of the digital signatures.</returns> /// <param name="content">The content.</param> /// <param name="signatureData">The detached signature data.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="content"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="signatureData"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override DigitalSignatureCollection Verify (Stream content, Stream signatureData) { if (content == null) throw new ArgumentNullException ("content"); if (signatureData == null) throw new ArgumentNullException ("signatureData"); var parser = new CmsSignedDataParser (new CmsTypedStream (content), signatureData); parser.GetSignedContent ().Drain (); return GetDigitalSignatures (parser); } /// <summary> /// Verify the digital signatures of the specified signedData and extract the original content. /// </summary> /// <returns>The list of digital signatures.</returns> /// <param name="signedData">The signed data.</param> /// <param name="entity">The unencapsulated entity.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="signedData"/> is <c>null</c>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public DigitalSignatureCollection Verify (Stream signedData, out MimeEntity entity) { if (signedData == null) throw new ArgumentNullException ("signedData"); var parser = new CmsSignedDataParser (signedData); var signed = parser.GetSignedContent (); entity = MimeEntity.Load (signed.ContentStream); return GetDigitalSignatures (parser); } class VoteComparer : IComparer<int> { #region IComparer implementation public int Compare (int x, int y) { return y - x; } #endregion } EncryptionAlgorithm GetPreferredEncryptionAlgorithm (CmsRecipientCollection recipients) { var votes = new int[EncryptionAlgorithmCount]; foreach (var recipient in recipients) { int cast = EncryptionAlgorithmCount; foreach (var algorithm in recipient.EncryptionAlgorithms) { votes[(int) algorithm] += cast; cast--; } } // Starting with S/MIME v3 (published in 1999), Triple-DES is a REQUIRED algorithm. // S/MIME v2.x and older only required RC2/40, but SUGGESTED Triple-DES. // Considering the fact that Bruce Schneier was able to write a // screensaver that could crack RC2/40 back in the late 90's, let's // not default to anything weaker than Triple-DES... EncryptionAlgorithm chosen = EncryptionAlgorithm.TripleDes; int nvotes = 0; // iterate through the algorithms, from strongest to weakest, keeping track // of the algorithm with the most amount of votes (between algorithms with // the same number of votes, choose the strongest of the 2 - i.e. the one // that we arrive at first). var algorithms = EncryptionAlgorithmRank; for (int i = 0; i < algorithms.Length; i++) { var algorithm = algorithms[i]; if (!IsEnabled (algorithm)) continue; if (votes[(int) algorithm] > nvotes) { nvotes = votes[(int) algorithm]; chosen = algorithm; } } return chosen; } Stream Envelope (CmsRecipientCollection recipients, Stream content) { var cms = new CmsEnvelopedDataGenerator (); int count = 0; foreach (var recipient in recipients) { cms.AddKeyTransRecipient (recipient.Certificate); count++; } if (count == 0) throw new ArgumentException ("No recipients specified.", "recipients"); var input = new CmsProcessableInputStream (content); CmsEnvelopedData envelopedData; switch (GetPreferredEncryptionAlgorithm (recipients)) { case EncryptionAlgorithm.Camellia256: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.Camellia256Cbc); break; case EncryptionAlgorithm.Camellia192: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.Camellia192Cbc); break; case EncryptionAlgorithm.Camellia128: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.Camellia128Cbc); break; case EncryptionAlgorithm.Aes256: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.Aes256Cbc); break; case EncryptionAlgorithm.Aes192: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.Aes192Cbc); break; case EncryptionAlgorithm.Aes128: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.Aes128Cbc); break; case EncryptionAlgorithm.Cast5: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.Cast5Cbc); break; case EncryptionAlgorithm.Idea: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.IdeaCbc); break; case EncryptionAlgorithm.RC2128: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.RC2Cbc, 128); break; case EncryptionAlgorithm.RC264: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.RC2Cbc, 64); break; case EncryptionAlgorithm.RC240: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.RC2Cbc, 40); break; default: envelopedData = cms.Generate (input, CmsEnvelopedGenerator.DesEde3Cbc); break; } return new MemoryStream (envelopedData.GetEncoded (), false); } /// <summary> /// Encrypt the specified content for the specified recipients. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance /// containing the encrypted content.</returns> /// <param name="recipients">The recipients.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public ApplicationPkcs7Mime Encrypt (CmsRecipientCollection recipients, Stream content) { if (recipients == null) throw new ArgumentNullException ("recipients"); if (content == null) throw new ArgumentNullException ("content"); return new ApplicationPkcs7Mime (SecureMimeType.EnvelopedData, Envelope (recipients, content)); } /// <summary> /// Encrypts the specified content for the specified recipients. /// </summary> /// <returns>A new <see cref="MimeKit.MimePart"/> instance /// containing the encrypted data.</returns> /// <param name="recipients">The recipients.</param> /// <param name="content">The content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="content"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// A certificate for one or more of the <paramref name="recipients"/> could not be found. /// </exception> /// <exception cref="CertificateNotFoundException"> /// A certificate could not be found for one or more of the <paramref name="recipients"/>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override MimePart Encrypt (IEnumerable<MailboxAddress> recipients, Stream content) { if (recipients == null) throw new ArgumentNullException ("recipients"); if (content == null) throw new ArgumentNullException ("content"); return Encrypt (GetCmsRecipients (recipients), content); } /// <summary> /// Decrypt the specified encryptedData. /// </summary> /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns> /// <param name="encryptedData">The encrypted data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="encryptedData"/> is <c>null</c>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override MimeEntity Decrypt (Stream encryptedData) { if (encryptedData == null) throw new ArgumentNullException ("encryptedData"); var parser = new CmsEnvelopedDataParser (encryptedData); var recipients = parser.GetRecipientInfos (); var algorithm = parser.EncryptionAlgorithmID; AsymmetricKeyParameter key; foreach (RecipientInformation recipient in recipients.GetRecipients ()) { if ((key = GetPrivateKey (recipient.RecipientID)) == null) continue; var content = recipient.GetContent (key); using (var memory = new MemoryStream (content, false)) { return MimeEntity.Load (memory); } } throw new CmsException ("A suitable private key could not be found for decrypting."); } /// <summary> /// Imports certificates and keys from a pkcs12-encoded stream. /// </summary> /// <param name="stream">The raw certificate and key data.</param> /// <param name="password">The password to unlock the stream.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// Importing keys is not supported by this cryptography context. /// </exception> public abstract void Import (Stream stream, string password); /// <summary> /// Exports the certificates for the specified mailboxes. /// </summary> /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance containing /// the exported keys.</returns> /// <param name="mailboxes">The mailboxes.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="mailboxes"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// No mailboxes were specified. /// </exception> /// <exception cref="CertificateNotFoundException"> /// A certificate for one or more of the <paramref name="mailboxes"/> could not be found. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override MimePart Export (IEnumerable<MailboxAddress> mailboxes) { if (mailboxes == null) throw new ArgumentNullException ("mailboxes"); var certificates = new X509CertificateStore (); int count = 0; foreach (var mailbox in mailboxes) { var recipient = GetCmsRecipient (mailbox); certificates.Add (recipient.Certificate); count++; } if (count == 0) throw new ArgumentException ("No mailboxes specified.", "mailboxes"); var cms = new CmsSignedDataStreamGenerator (); var memory = new MemoryStream (); cms.AddCertificates (certificates); cms.Open (memory).Close (); memory.Position = 0; return new ApplicationPkcs7Mime (SecureMimeType.CertsOnly, memory); } /// <summary> /// Import the specified certificate. /// </summary> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public abstract void Import (X509Certificate certificate); /// <summary> /// Import the specified certificate revocation list. /// </summary> /// <param name="crl">The certificate revocation list.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="crl"/> is <c>null</c>. /// </exception> public abstract void Import (X509Crl crl); /// <summary> /// Imports certificates (as from a certs-only application/pkcs-mime part) /// from the specified stream. /// </summary> /// <param name="stream">The raw key data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override void Import (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); var parser = new CmsSignedDataParser (stream); var certificates = parser.GetCertificates ("Collection"); foreach (X509Certificate certificate in certificates.GetMatches (null)) Import (certificate); var crls = parser.GetCrls ("Collection"); foreach (X509Crl crl in crls.GetMatches (null)) Import (crl); } } }
using System; using System.Numerics; using System.Globalization; using System.Collections.Generic; namespace ipaddress { class IpV6 { /// =Name /// /// IPAddress::IPv6 - IP version 6 address manipulation library /// /// =Synopsis /// /// require 'ipaddress' /// /// =Description /// /// Class IPAddress::IPv6 is used to handle IPv6 type addresses. /// /// == IPv6 addresses /// /// IPv6 addresses are 128 bits long, in contrast with IPv4 addresses /// which are only 32 bits long. An IPv6 address is generally written as /// eight groups of four hexadecimal digits, each group representing 16 /// bits or two octect. For example, the following is a valid IPv6 /// address: /// /// 2001:0db8:0000:0000:0008:0800:200c:417a /// /// Letters in an IPv6 address are usually written downcase, as per /// RFC. You can create a new IPv6 object using uppercase letters, but /// they will be converted. /// /// === Compression /// /// Since IPv6 addresses are very long to write, there are some /// semplifications and compressions that you can use to shorten them. /// /// * Leading zeroes: all the leading zeroes within a group can be /// omitted: "0008" would become "8" /// /// * A string of consecutive zeroes can be replaced by the string /// "::". This can be only applied once. /// /// Using compression, the IPv6 address written above can be shorten into /// the following, equivalent, address /// /// 2001:db8::8:800:200c:417a /// /// This short version is often used in human representation. /// /// === Network Mask /// /// As we used to do with IPv4 addresses, an IPv6 address can be written /// using the prefix notation to specify the subnet mask: /// /// 2001:db8::8:800:200c:417a/64 /// /// The /64 part means that the first 64 bits of the address are /// representing the network portion, and the last 64 bits are the host /// portion. /// /// public static IPAddress ipv6_to_ipv6(IPAddress my) { return my.clone(); } public static bool ipv6_is_loopback(IPAddress my) { return my.host_address == new BigInteger(1); } public static bool ipv6_is_private(IPAddress my) { return IPAddress.parse("fd00::/8").unwrap().includes(my); } public static Result<IPAddress> from_str(String str, int radix, uint prefix) { try { NumberStyles tmp = NumberStyles.Integer; if (radix == 16) { tmp = NumberStyles.HexNumber; } var num = BigInteger.Parse(str, tmp); return from_int(num, prefix); } catch (Exception ) { return Result<IPAddress>.Err("unparsable <<str>>"); } } public static Result<IPAddress> enhance_if_mapped(IPAddress ip) { // println!("real mapped {:x} {:x}", &ip.host_address, ip.host_address.clone().shr(32)); if (ip.is_mapped()) { return Result<IPAddress>.Ok(ip); } var ipv6_top_96bit = ip.host_address >> 32; if (ipv6_top_96bit == 0xffff) { // println!("enhance_if_mapped-1:{}", ); var num = ip.host_address % (new BigInteger(1) << 32); if (num == 0) { return Result<IPAddress>.Ok(ip); } //println!("ip:{},{:x}", ip.to_string(), num); var ipv4_bits = IpBits.V4; if (ipv4_bits.bits < ip.prefix.host_prefix()) { //println!("enhance_if_mapped-2:{}:{}", ip.to_string(), ip.prefix.host_prefix()); return Result<IPAddress>.Err("enhance_if_mapped prefix not ipv4 compatible <<ip.prefix.host_prefix()>>"); } var mapped = IpV4.from_u32((UInt32)num, (ipv4_bits.bits - ip.prefix.host_prefix())); if (mapped.isErr()) { //println!("enhance_if_mapped-3"); return mapped; } // println!("real mapped!!!!!={}", mapped.clone().unwrap().to_string()); return Result<IPAddress>.Ok(ip.setMapped(mapped.unwrap())); } return Result<IPAddress>.Ok(ip); } public static Result<IPAddress> from_int(BigInteger bi, uint prefixNum) { var prefix = Prefix128.create(prefixNum); if (prefix.isErr()) { return Result<IPAddress>.Err(prefix.unwrapErr()); } return enhance_if_mapped(new IPAddress( IpBits.V6, bi, prefix.unwrap(), null, ipv6_is_private, ipv6_is_loopback, ipv6_to_ipv6)); } /// Creates a new IPv6 address object. /// /// An IPv6 address can be expressed in any of the following forms: /// /// * "2001:0db8:0000:0000:0008:0800:200C:417A": IPv6 address with no compression /// * "2001:db8:0:0:8:800:200C:417A": IPv6 address with leading zeros compression /// * "2001:db8::8:800:200C:417A": IPv6 address with full compression /// /// In all these 3 cases, a new IPv6 address object will be created, using the default /// subnet mask /128 /// /// You can also specify the subnet mask as with IPv4 addresses: /// /// ip6 = IPAddress "2001:db8::8:800:200c:417a/64" /// public static Result<IPAddress> create(String str) { var splitted = IPAddress.Split_at_slash(str); if (IPAddress.is_valid_ipv6(splitted.addr)) { var o_num = IPAddress.split_to_num(splitted.addr); if (o_num.isErr()) { return Result<IPAddress>.Err(o_num.unwrapErr()); } var netmask = 128u; if (splitted.netmask != null) { var network = splitted.netmask; var num_mask = IPAddress.parseInt(network, 10); if (!num_mask.HasValue) { return Result<IPAddress>.Err("Invalid Netmask <<str>>"); } netmask = num_mask.Value; } var prefix = Prefix128.create(netmask); if (prefix.isErr()) { return Result<IPAddress>.Err(prefix.unwrapErr()); } return enhance_if_mapped(new IPAddress( IpBits.V6, o_num.unwrap(), prefix.unwrap(), null, ipv6_is_private, ipv6_is_loopback, ipv6_to_ipv6)); } return Result<IPAddress>.Err("Invalid IP <<str>>"); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.42. // namespace WebsitePanel.EnterpriseServer { using System.Diagnostics; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Xml.Serialization; using System.Data; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name = "esUsersSoap", Namespace = "http://smbsaas/websitepanel/enterpriseserver")] public partial class esUsers : Microsoft.Web.Services3.WebServicesClientProtocol { private System.Threading.SendOrPostCallback UserExistsOperationCompleted; private System.Threading.SendOrPostCallback GetUserByIdOperationCompleted; private System.Threading.SendOrPostCallback GetUserByUsernameOperationCompleted; private System.Threading.SendOrPostCallback GetUsersOperationCompleted; private System.Threading.SendOrPostCallback GetRawUsersOperationCompleted; private System.Threading.SendOrPostCallback GetUsersPagedOperationCompleted; private System.Threading.SendOrPostCallback GetUsersPagedRecursiveOperationCompleted; private System.Threading.SendOrPostCallback GetUsersSummaryOperationCompleted; private System.Threading.SendOrPostCallback GetUserDomainsPagedOperationCompleted; private System.Threading.SendOrPostCallback GetRawUserPeersOperationCompleted; private System.Threading.SendOrPostCallback GetUserPeersOperationCompleted; private System.Threading.SendOrPostCallback GetUserParentsOperationCompleted; private System.Threading.SendOrPostCallback AddUserOperationCompleted; private System.Threading.SendOrPostCallback UpdateUserTaskOperationCompleted; private System.Threading.SendOrPostCallback UpdateUserTaskAsynchronouslyOperationCompleted; private System.Threading.SendOrPostCallback UpdateUserOperationCompleted; private System.Threading.SendOrPostCallback DeleteUserOperationCompleted; private System.Threading.SendOrPostCallback ChangeUserPasswordOperationCompleted; private System.Threading.SendOrPostCallback ChangeUserStatusOperationCompleted; private System.Threading.SendOrPostCallback GetUserSettingsOperationCompleted; private System.Threading.SendOrPostCallback UpdateUserSettingsOperationCompleted; /// <remarks/> public esUsers() { this.Url = "http://localhost/EnterpriseServer/esUsers.asmx"; } /// <remarks/> public event UserExistsCompletedEventHandler UserExistsCompleted; /// <remarks/> public event GetUserByIdCompletedEventHandler GetUserByIdCompleted; /// <remarks/> public event GetUserByUsernameCompletedEventHandler GetUserByUsernameCompleted; /// <remarks/> public event GetUsersCompletedEventHandler GetUsersCompleted; /// <remarks/> public event GetRawUsersCompletedEventHandler GetRawUsersCompleted; /// <remarks/> public event GetUsersPagedCompletedEventHandler GetUsersPagedCompleted; /// <remarks/> public event GetUsersPagedRecursiveCompletedEventHandler GetUsersPagedRecursiveCompleted; /// <remarks/> public event GetUsersSummaryCompletedEventHandler GetUsersSummaryCompleted; /// <remarks/> public event GetUserDomainsPagedCompletedEventHandler GetUserDomainsPagedCompleted; /// <remarks/> public event GetRawUserPeersCompletedEventHandler GetRawUserPeersCompleted; /// <remarks/> public event GetUserPeersCompletedEventHandler GetUserPeersCompleted; /// <remarks/> public event GetUserParentsCompletedEventHandler GetUserParentsCompleted; /// <remarks/> public event AddUserCompletedEventHandler AddUserCompleted; /// <remarks/> public event UpdateUserTaskCompletedEventHandler UpdateUserTaskCompleted; /// <remarks/> public event UpdateUserTaskAsynchronouslyCompletedEventHandler UpdateUserTaskAsynchronouslyCompleted; /// <remarks/> public event UpdateUserCompletedEventHandler UpdateUserCompleted; /// <remarks/> public event DeleteUserCompletedEventHandler DeleteUserCompleted; /// <remarks/> public event ChangeUserPasswordCompletedEventHandler ChangeUserPasswordCompleted; /// <remarks/> public event ChangeUserStatusCompletedEventHandler ChangeUserStatusCompleted; /// <remarks/> public event GetUserSettingsCompletedEventHandler GetUserSettingsCompleted; /// <remarks/> public event UpdateUserSettingsCompletedEventHandler UpdateUserSettingsCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/UserExists", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool UserExists(string username) { object[] results = this.Invoke("UserExists", new object[] { username}); return ((bool)(results[0])); } /// <remarks/> public System.IAsyncResult BeginUserExists(string username, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UserExists", new object[] { username}, callback, asyncState); } /// <remarks/> public bool EndUserExists(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((bool)(results[0])); } /// <remarks/> public void UserExistsAsync(string username) { this.UserExistsAsync(username, null); } /// <remarks/> public void UserExistsAsync(string username, object userState) { if ((this.UserExistsOperationCompleted == null)) { this.UserExistsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUserExistsOperationCompleted); } this.InvokeAsync("UserExists", new object[] { username}, this.UserExistsOperationCompleted, userState); } private void OnUserExistsOperationCompleted(object arg) { if ((this.UserExistsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UserExistsCompleted(this, new UserExistsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUserById", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UserInfo GetUserById(int userId) { object[] results = this.Invoke("GetUserById", new object[] { userId}); return ((UserInfo)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUserById(int userId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUserById", new object[] { userId}, callback, asyncState); } /// <remarks/> public UserInfo EndGetUserById(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((UserInfo)(results[0])); } /// <remarks/> public void GetUserByIdAsync(int userId) { this.GetUserByIdAsync(userId, null); } /// <remarks/> public void GetUserByIdAsync(int userId, object userState) { if ((this.GetUserByIdOperationCompleted == null)) { this.GetUserByIdOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUserByIdOperationCompleted); } this.InvokeAsync("GetUserById", new object[] { userId}, this.GetUserByIdOperationCompleted, userState); } private void OnGetUserByIdOperationCompleted(object arg) { if ((this.GetUserByIdCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUserByIdCompleted(this, new GetUserByIdCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUserByUsername", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UserInfo GetUserByUsername(string username) { object[] results = this.Invoke("GetUserByUsername", new object[] { username}); return ((UserInfo)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUserByUsername(string username, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUserByUsername", new object[] { username}, callback, asyncState); } /// <remarks/> public UserInfo EndGetUserByUsername(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((UserInfo)(results[0])); } /// <remarks/> public void GetUserByUsernameAsync(string username) { this.GetUserByUsernameAsync(username, null); } /// <remarks/> public void GetUserByUsernameAsync(string username, object userState) { if ((this.GetUserByUsernameOperationCompleted == null)) { this.GetUserByUsernameOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUserByUsernameOperationCompleted); } this.InvokeAsync("GetUserByUsername", new object[] { username}, this.GetUserByUsernameOperationCompleted, userState); } private void OnGetUserByUsernameOperationCompleted(object arg) { if ((this.GetUserByUsernameCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUserByUsernameCompleted(this, new GetUserByUsernameCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUsers", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UserInfo[] GetUsers(int ownerId, bool recursive) { object[] results = this.Invoke("GetUsers", new object[] { ownerId, recursive}); return ((UserInfo[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUsers(int ownerId, bool recursive, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUsers", new object[] { ownerId, recursive}, callback, asyncState); } /// <remarks/> public UserInfo[] EndGetUsers(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((UserInfo[])(results[0])); } /// <remarks/> public void GetUsersAsync(int ownerId, bool recursive) { this.GetUsersAsync(ownerId, recursive, null); } /// <remarks/> public void GetUsersAsync(int ownerId, bool recursive, object userState) { if ((this.GetUsersOperationCompleted == null)) { this.GetUsersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUsersOperationCompleted); } this.InvokeAsync("GetUsers", new object[] { ownerId, recursive}, this.GetUsersOperationCompleted, userState); } private void OnGetUsersOperationCompleted(object arg) { if ((this.GetUsersCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUsersCompleted(this, new GetUsersCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/AddUserVLan", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void AddUserVLan(int userId, UserVlan vLan) { object[] results = this.Invoke("AddUserVLan", new object[] { userId, vLan}); } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteUserVLan", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void DeleteUserVLan(int userId, ushort vLanId) { object[] results = this.Invoke("DeleteUserVLan", new object[] { userId, vLanId}); } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetRawUsers", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetRawUsers(int ownerId, bool recursive) { object[] results = this.Invoke("GetRawUsers", new object[] { ownerId, recursive}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetRawUsers(int ownerId, bool recursive, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetRawUsers", new object[] { ownerId, recursive}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetRawUsers(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetRawUsersAsync(int ownerId, bool recursive) { this.GetRawUsersAsync(ownerId, recursive, null); } /// <remarks/> public void GetRawUsersAsync(int ownerId, bool recursive, object userState) { if ((this.GetRawUsersOperationCompleted == null)) { this.GetRawUsersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRawUsersOperationCompleted); } this.InvokeAsync("GetRawUsers", new object[] { ownerId, recursive}, this.GetRawUsersOperationCompleted, userState); } private void OnGetRawUsersOperationCompleted(object arg) { if ((this.GetRawUsersCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetRawUsersCompleted(this, new GetRawUsersCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUsersPaged", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetUsersPaged(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows) { object[] results = this.Invoke("GetUsersPaged", new object[] { userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUsersPaged(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUsersPaged", new object[] { userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetUsersPaged(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetUsersPagedAsync(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows) { this.GetUsersPagedAsync(userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows, null); } /// <remarks/> public void GetUsersPagedAsync(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows, object userState) { if ((this.GetUsersPagedOperationCompleted == null)) { this.GetUsersPagedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUsersPagedOperationCompleted); } this.InvokeAsync("GetUsersPaged", new object[] { userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows}, this.GetUsersPagedOperationCompleted, userState); } private void OnGetUsersPagedOperationCompleted(object arg) { if ((this.GetUsersPagedCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUsersPagedCompleted(this, new GetUsersPagedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUsersPagedRecursive", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetUsersPagedRecursive(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows) { object[] results = this.Invoke("GetUsersPagedRecursive", new object[] { userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUsersPagedRecursive(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUsersPagedRecursive", new object[] { userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetUsersPagedRecursive(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetUsersPagedRecursiveAsync(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows) { this.GetUsersPagedRecursiveAsync(userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows, null); } /// <remarks/> public void GetUsersPagedRecursiveAsync(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows, object userState) { if ((this.GetUsersPagedRecursiveOperationCompleted == null)) { this.GetUsersPagedRecursiveOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUsersPagedRecursiveOperationCompleted); } this.InvokeAsync("GetUsersPagedRecursive", new object[] { userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows}, this.GetUsersPagedRecursiveOperationCompleted, userState); } private void OnGetUsersPagedRecursiveOperationCompleted(object arg) { if ((this.GetUsersPagedRecursiveCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUsersPagedRecursiveCompleted(this, new GetUsersPagedRecursiveCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUsersSummary", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetUsersSummary(int userId) { object[] results = this.Invoke("GetUsersSummary", new object[] { userId}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUsersSummary(int userId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUsersSummary", new object[] { userId}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetUsersSummary(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetUsersSummaryAsync(int userId) { this.GetUsersSummaryAsync(userId, null); } /// <remarks/> public void GetUsersSummaryAsync(int userId, object userState) { if ((this.GetUsersSummaryOperationCompleted == null)) { this.GetUsersSummaryOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUsersSummaryOperationCompleted); } this.InvokeAsync("GetUsersSummary", new object[] { userId}, this.GetUsersSummaryOperationCompleted, userState); } private void OnGetUsersSummaryOperationCompleted(object arg) { if ((this.GetUsersSummaryCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUsersSummaryCompleted(this, new GetUsersSummaryCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUserDomainsPaged", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetUserDomainsPaged(int userId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { object[] results = this.Invoke("GetUserDomainsPaged", new object[] { userId, filterColumn, filterValue, sortColumn, startRow, maximumRows}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUserDomainsPaged(int userId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUserDomainsPaged", new object[] { userId, filterColumn, filterValue, sortColumn, startRow, maximumRows}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetUserDomainsPaged(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetUserDomainsPagedAsync(int userId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { this.GetUserDomainsPagedAsync(userId, filterColumn, filterValue, sortColumn, startRow, maximumRows, null); } /// <remarks/> public void GetUserDomainsPagedAsync(int userId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, object userState) { if ((this.GetUserDomainsPagedOperationCompleted == null)) { this.GetUserDomainsPagedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUserDomainsPagedOperationCompleted); } this.InvokeAsync("GetUserDomainsPaged", new object[] { userId, filterColumn, filterValue, sortColumn, startRow, maximumRows}, this.GetUserDomainsPagedOperationCompleted, userState); } private void OnGetUserDomainsPagedOperationCompleted(object arg) { if ((this.GetUserDomainsPagedCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUserDomainsPagedCompleted(this, new GetUserDomainsPagedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetRawUserPeers", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetRawUserPeers(int userId) { object[] results = this.Invoke("GetRawUserPeers", new object[] { userId}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetRawUserPeers(int userId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetRawUserPeers", new object[] { userId}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetRawUserPeers(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetRawUserPeersAsync(int userId) { this.GetRawUserPeersAsync(userId, null); } /// <remarks/> public void GetRawUserPeersAsync(int userId, object userState) { if ((this.GetRawUserPeersOperationCompleted == null)) { this.GetRawUserPeersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRawUserPeersOperationCompleted); } this.InvokeAsync("GetRawUserPeers", new object[] { userId}, this.GetRawUserPeersOperationCompleted, userState); } private void OnGetRawUserPeersOperationCompleted(object arg) { if ((this.GetRawUserPeersCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetRawUserPeersCompleted(this, new GetRawUserPeersCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUserPeers", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UserInfo[] GetUserPeers(int userId) { object[] results = this.Invoke("GetUserPeers", new object[] { userId}); return ((UserInfo[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUserPeers(int userId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUserPeers", new object[] { userId}, callback, asyncState); } /// <remarks/> public UserInfo[] EndGetUserPeers(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((UserInfo[])(results[0])); } /// <remarks/> public void GetUserPeersAsync(int userId) { this.GetUserPeersAsync(userId, null); } /// <remarks/> public void GetUserPeersAsync(int userId, object userState) { if ((this.GetUserPeersOperationCompleted == null)) { this.GetUserPeersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUserPeersOperationCompleted); } this.InvokeAsync("GetUserPeers", new object[] { userId}, this.GetUserPeersOperationCompleted, userState); } private void OnGetUserPeersOperationCompleted(object arg) { if ((this.GetUserPeersCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUserPeersCompleted(this, new GetUserPeersCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUserParents", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UserInfo[] GetUserParents(int userId) { object[] results = this.Invoke("GetUserParents", new object[] { userId}); return ((UserInfo[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUserParents(int userId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUserParents", new object[] { userId}, callback, asyncState); } /// <remarks/> public UserInfo[] EndGetUserParents(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((UserInfo[])(results[0])); } /// <remarks/> public void GetUserParentsAsync(int userId) { this.GetUserParentsAsync(userId, null); } /// <remarks/> public void GetUserParentsAsync(int userId, object userState) { if ((this.GetUserParentsOperationCompleted == null)) { this.GetUserParentsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUserParentsOperationCompleted); } this.InvokeAsync("GetUserParents", new object[] { userId}, this.GetUserParentsOperationCompleted, userState); } private void OnGetUserParentsOperationCompleted(object arg) { if ((this.GetUserParentsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUserParentsCompleted(this, new GetUserParentsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/AddUser", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int AddUser(UserInfo user, bool sendLetter, string password) { object[] results = this.Invoke("AddUser", new object[] { user, sendLetter, password }); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginAddUser(UserInfo user, bool sendLetter, string password, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddUser", new object[] { user, sendLetter, password}, callback, asyncState); } /// <remarks/> public int EndAddUser(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void AddUserAsync(UserInfo user, bool sendLetter, string password) { this.AddUserAsync(user, sendLetter, password, null); } /// <remarks/> public void AddUserAsync(UserInfo user, bool sendLetter, string password, object userState) { if ((this.AddUserOperationCompleted == null)) { this.AddUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddUserOperationCompleted); } this.InvokeAsync("AddUser", new object[] { user, sendLetter, password}, this.AddUserOperationCompleted, userState); } private void OnAddUserOperationCompleted(object arg) { if ((this.AddUserCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddUserCompleted(this, new AddUserCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/UpdateUserTask", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int UpdateUserTask(string taskId, UserInfo user) { object[] results = this.Invoke("UpdateUserTask", new object[] { taskId, user}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginUpdateUserTask(string taskId, UserInfo user, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateUserTask", new object[] { taskId, user}, callback, asyncState); } /// <remarks/> public int EndUpdateUserTask(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void UpdateUserTaskAsync(string taskId, UserInfo user) { this.UpdateUserTaskAsync(taskId, user, null); } /// <remarks/> public void UpdateUserTaskAsync(string taskId, UserInfo user, object userState) { if ((this.UpdateUserTaskOperationCompleted == null)) { this.UpdateUserTaskOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateUserTaskOperationCompleted); } this.InvokeAsync("UpdateUserTask", new object[] { taskId, user}, this.UpdateUserTaskOperationCompleted, userState); } private void OnUpdateUserTaskOperationCompleted(object arg) { if ((this.UpdateUserTaskCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateUserTaskCompleted(this, new UpdateUserTaskCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/UpdateUserTaskAsynchronously", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int UpdateUserTaskAsynchronously(string taskId, UserInfo user) { object[] results = this.Invoke("UpdateUserTaskAsynchronously", new object[] { taskId, user}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginUpdateUserTaskAsynchronously(string taskId, UserInfo user, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateUserTaskAsynchronously", new object[] { taskId, user}, callback, asyncState); } /// <remarks/> public int EndUpdateUserTaskAsynchronously(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void UpdateUserTaskAsynchronouslyAsync(string taskId, UserInfo user) { this.UpdateUserTaskAsynchronouslyAsync(taskId, user, null); } /// <remarks/> public void UpdateUserTaskAsynchronouslyAsync(string taskId, UserInfo user, object userState) { if ((this.UpdateUserTaskAsynchronouslyOperationCompleted == null)) { this.UpdateUserTaskAsynchronouslyOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateUserTaskAsynchronouslyOperationCompleted); } this.InvokeAsync("UpdateUserTaskAsynchronously", new object[] { taskId, user}, this.UpdateUserTaskAsynchronouslyOperationCompleted, userState); } private void OnUpdateUserTaskAsynchronouslyOperationCompleted(object arg) { if ((this.UpdateUserTaskAsynchronouslyCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateUserTaskAsynchronouslyCompleted(this, new UpdateUserTaskAsynchronouslyCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/UpdateUser", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int UpdateUser(UserInfo user) { object[] results = this.Invoke("UpdateUser", new object[] { user}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginUpdateUser(UserInfo user, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateUser", new object[] { user}, callback, asyncState); } /// <remarks/> public int EndUpdateUser(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void UpdateUserAsync(UserInfo user) { this.UpdateUserAsync(user, null); } /// <remarks/> public void UpdateUserAsync(UserInfo user, object userState) { if ((this.UpdateUserOperationCompleted == null)) { this.UpdateUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateUserOperationCompleted); } this.InvokeAsync("UpdateUser", new object[] { user}, this.UpdateUserOperationCompleted, userState); } private void OnUpdateUserOperationCompleted(object arg) { if ((this.UpdateUserCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateUserCompleted(this, new UpdateUserCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteUser", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int DeleteUser(int userId) { object[] results = this.Invoke("DeleteUser", new object[] { userId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginDeleteUser(int userId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteUser", new object[] { userId}, callback, asyncState); } /// <remarks/> public int EndDeleteUser(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void DeleteUserAsync(int userId) { this.DeleteUserAsync(userId, null); } /// <remarks/> public void DeleteUserAsync(int userId, object userState) { if ((this.DeleteUserOperationCompleted == null)) { this.DeleteUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteUserOperationCompleted); } this.InvokeAsync("DeleteUser", new object[] { userId}, this.DeleteUserOperationCompleted, userState); } private void OnDeleteUserOperationCompleted(object arg) { if ((this.DeleteUserCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteUserCompleted(this, new DeleteUserCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/ChangeUserPassword", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int ChangeUserPassword(int userId, string password) { object[] results = this.Invoke("ChangeUserPassword", new object[] { userId, password}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginChangeUserPassword(int userId, string password, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("ChangeUserPassword", new object[] { userId, password}, callback, asyncState); } /// <remarks/> public int EndChangeUserPassword(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void ChangeUserPasswordAsync(int userId, string password) { this.ChangeUserPasswordAsync(userId, password, null); } /// <remarks/> public void ChangeUserPasswordAsync(int userId, string password, object userState) { if ((this.ChangeUserPasswordOperationCompleted == null)) { this.ChangeUserPasswordOperationCompleted = new System.Threading.SendOrPostCallback(this.OnChangeUserPasswordOperationCompleted); } this.InvokeAsync("ChangeUserPassword", new object[] { userId, password}, this.ChangeUserPasswordOperationCompleted, userState); } private void OnChangeUserPasswordOperationCompleted(object arg) { if ((this.ChangeUserPasswordCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.ChangeUserPasswordCompleted(this, new ChangeUserPasswordCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/ChangeUserStatus", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int ChangeUserStatus(int userId, UserStatus status) { object[] results = this.Invoke("ChangeUserStatus", new object[] { userId, status}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginChangeUserStatus(int userId, UserStatus status, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("ChangeUserStatus", new object[] { userId, status}, callback, asyncState); } /// <remarks/> public int EndChangeUserStatus(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void ChangeUserStatusAsync(int userId, UserStatus status) { this.ChangeUserStatusAsync(userId, status, null); } /// <remarks/> public void ChangeUserStatusAsync(int userId, UserStatus status, object userState) { if ((this.ChangeUserStatusOperationCompleted == null)) { this.ChangeUserStatusOperationCompleted = new System.Threading.SendOrPostCallback(this.OnChangeUserStatusOperationCompleted); } this.InvokeAsync("ChangeUserStatus", new object[] { userId, status}, this.ChangeUserStatusOperationCompleted, userState); } private void OnChangeUserStatusOperationCompleted(object arg) { if ((this.ChangeUserStatusCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.ChangeUserStatusCompleted(this, new ChangeUserStatusCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetUserSettings", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UserSettings GetUserSettings(int userId, string settingsName) { object[] results = this.Invoke("GetUserSettings", new object[] { userId, settingsName}); return ((UserSettings)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetUserSettings(int userId, string settingsName, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetUserSettings", new object[] { userId, settingsName}, callback, asyncState); } /// <remarks/> public UserSettings EndGetUserSettings(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((UserSettings)(results[0])); } /// <remarks/> public void GetUserSettingsAsync(int userId, string settingsName) { this.GetUserSettingsAsync(userId, settingsName, null); } /// <remarks/> public void GetUserSettingsAsync(int userId, string settingsName, object userState) { if ((this.GetUserSettingsOperationCompleted == null)) { this.GetUserSettingsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUserSettingsOperationCompleted); } this.InvokeAsync("GetUserSettings", new object[] { userId, settingsName}, this.GetUserSettingsOperationCompleted, userState); } private void OnGetUserSettingsOperationCompleted(object arg) { if ((this.GetUserSettingsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetUserSettingsCompleted(this, new GetUserSettingsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/UpdateUserSettings", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int UpdateUserSettings(UserSettings settings) { object[] results = this.Invoke("UpdateUserSettings", new object[] { settings}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginUpdateUserSettings(UserSettings settings, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateUserSettings", new object[] { settings}, callback, asyncState); } /// <remarks/> public int EndUpdateUserSettings(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void UpdateUserSettingsAsync(UserSettings settings) { this.UpdateUserSettingsAsync(settings, null); } /// <remarks/> public void UpdateUserSettingsAsync(UserSettings settings, object userState) { if ((this.UpdateUserSettingsOperationCompleted == null)) { this.UpdateUserSettingsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateUserSettingsOperationCompleted); } this.InvokeAsync("UpdateUserSettings", new object[] { settings}, this.UpdateUserSettingsOperationCompleted, userState); } private void OnUpdateUserSettingsOperationCompleted(object arg) { if ((this.UpdateUserSettingsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateUserSettingsCompleted(this, new UpdateUserSettingsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void UserExistsCompletedEventHandler(object sender, UserExistsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class UserExistsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal UserExistsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public bool Result { get { this.RaiseExceptionIfNecessary(); return ((bool)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUserByIdCompletedEventHandler(object sender, GetUserByIdCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUserByIdCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUserByIdCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public UserInfo Result { get { this.RaiseExceptionIfNecessary(); return ((UserInfo)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUserByUsernameCompletedEventHandler(object sender, GetUserByUsernameCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUserByUsernameCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUserByUsernameCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public UserInfo Result { get { this.RaiseExceptionIfNecessary(); return ((UserInfo)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUsersCompletedEventHandler(object sender, GetUsersCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUsersCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUsersCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public UserInfo[] Result { get { this.RaiseExceptionIfNecessary(); return ((UserInfo[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetRawUsersCompletedEventHandler(object sender, GetRawUsersCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetRawUsersCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetRawUsersCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUsersPagedCompletedEventHandler(object sender, GetUsersPagedCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUsersPagedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUsersPagedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUsersPagedRecursiveCompletedEventHandler(object sender, GetUsersPagedRecursiveCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUsersPagedRecursiveCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUsersPagedRecursiveCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUsersSummaryCompletedEventHandler(object sender, GetUsersSummaryCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUsersSummaryCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUsersSummaryCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUserDomainsPagedCompletedEventHandler(object sender, GetUserDomainsPagedCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUserDomainsPagedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUserDomainsPagedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetRawUserPeersCompletedEventHandler(object sender, GetRawUserPeersCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetRawUserPeersCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetRawUserPeersCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUserPeersCompletedEventHandler(object sender, GetUserPeersCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUserPeersCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUserPeersCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public UserInfo[] Result { get { this.RaiseExceptionIfNecessary(); return ((UserInfo[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUserParentsCompletedEventHandler(object sender, GetUserParentsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUserParentsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUserParentsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public UserInfo[] Result { get { this.RaiseExceptionIfNecessary(); return ((UserInfo[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void AddUserCompletedEventHandler(object sender, AddUserCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class AddUserCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal AddUserCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void UpdateUserTaskCompletedEventHandler(object sender, UpdateUserTaskCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class UpdateUserTaskCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal UpdateUserTaskCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void UpdateUserTaskAsynchronouslyCompletedEventHandler(object sender, UpdateUserTaskAsynchronouslyCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class UpdateUserTaskAsynchronouslyCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal UpdateUserTaskAsynchronouslyCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void UpdateUserCompletedEventHandler(object sender, UpdateUserCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class UpdateUserCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal UpdateUserCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void DeleteUserCompletedEventHandler(object sender, DeleteUserCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class DeleteUserCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal DeleteUserCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void ChangeUserPasswordCompletedEventHandler(object sender, ChangeUserPasswordCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class ChangeUserPasswordCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal ChangeUserPasswordCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void ChangeUserStatusCompletedEventHandler(object sender, ChangeUserStatusCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class ChangeUserStatusCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal ChangeUserStatusCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetUserSettingsCompletedEventHandler(object sender, GetUserSettingsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetUserSettingsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetUserSettingsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public UserSettings Result { get { this.RaiseExceptionIfNecessary(); return ((UserSettings)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void UpdateUserSettingsCompletedEventHandler(object sender, UpdateUserSettingsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class UpdateUserSettingsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal UpdateUserSettingsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System.Diagnostics.CodeAnalysis; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; /// <summary> /// Exposes flex API, merged from flex API of sub-segments. /// <para/> /// @lucene.experimental /// </summary> public sealed class MultiDocsAndPositionsEnum : DocsAndPositionsEnum { private readonly MultiTermsEnum parent; internal readonly DocsAndPositionsEnum[] subDocsAndPositionsEnum; private EnumWithSlice[] subs; internal int numSubs; internal int upto; internal DocsAndPositionsEnum current; internal int currentBase; internal int doc = -1; /// <summary> /// Sole constructor. </summary> public MultiDocsAndPositionsEnum(MultiTermsEnum parent, int subReaderCount) { this.parent = parent; subDocsAndPositionsEnum = new DocsAndPositionsEnum[subReaderCount]; } /// <summary> /// Returns <c>true</c> if this instance can be reused by /// the provided <see cref="MultiTermsEnum"/>. /// </summary> public bool CanReuse(MultiTermsEnum parent) { return this.parent == parent; } /// <summary> /// Re-use and reset this instance on the provided slices. </summary> public MultiDocsAndPositionsEnum Reset(EnumWithSlice[] subs, int numSubs) { this.numSubs = numSubs; this.subs = new EnumWithSlice[subs.Length]; for (int i = 0; i < subs.Length; i++) { this.subs[i] = new EnumWithSlice(); this.subs[i].DocsAndPositionsEnum = subs[i].DocsAndPositionsEnum; this.subs[i].Slice = subs[i].Slice; } upto = -1; doc = -1; current = null; return this; } /// <summary> /// How many sub-readers we are merging. </summary> /// <see cref="Subs"/> public int NumSubs => numSubs; /// <summary> /// Returns sub-readers we are merging. </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public EnumWithSlice[] Subs => subs; public override int Freq { get { if (Debugging.AssertsEnabled) Debugging.Assert(current != null); return current.Freq; } } public override int DocID => doc; public override int Advance(int target) { if (Debugging.AssertsEnabled) Debugging.Assert(target > doc); while (true) { if (current != null) { int doc; if (target < currentBase) { // target was in the previous slice but there was no matching doc after it doc = current.NextDoc(); } else { doc = current.Advance(target - currentBase); } if (doc == NO_MORE_DOCS) { current = null; } else { return this.doc = doc + currentBase; } } else if (upto == numSubs - 1) { return this.doc = NO_MORE_DOCS; } else { upto++; current = subs[upto].DocsAndPositionsEnum; currentBase = subs[upto].Slice.Start; } } } public override int NextDoc() { while (true) { if (current == null) { if (upto == numSubs - 1) { return this.doc = NO_MORE_DOCS; } else { upto++; current = subs[upto].DocsAndPositionsEnum; currentBase = subs[upto].Slice.Start; } } int doc = current.NextDoc(); if (doc != NO_MORE_DOCS) { return this.doc = currentBase + doc; } else { current = null; } } } public override int NextPosition() { return current.NextPosition(); } public override int StartOffset => current.StartOffset; public override int EndOffset => current.EndOffset; public override BytesRef GetPayload() { return current.GetPayload(); } // TODO: implement bulk read more efficiently than super /// <summary> /// Holds a <see cref="Index.DocsAndPositionsEnum"/> along with the /// corresponding <see cref="ReaderSlice"/>. /// </summary> public sealed class EnumWithSlice { internal EnumWithSlice() { } /// <summary> /// <see cref="Index.DocsAndPositionsEnum"/> for this sub-reader. </summary> public DocsAndPositionsEnum DocsAndPositionsEnum { get; internal set; } // LUCENENET NOTE: Made setter internal because ctor is internal /// <summary> /// <see cref="ReaderSlice"/> describing how this sub-reader /// fits into the composite reader. /// </summary> public ReaderSlice Slice { get; internal set; } // LUCENENET NOTE: Made setter internal because ctor is internal public override string ToString() { return Slice.ToString() + ":" + DocsAndPositionsEnum; } } public override long GetCost() { long cost = 0; for (int i = 0; i < numSubs; i++) { cost += subs[i].DocsAndPositionsEnum.GetCost(); } return cost; } public override string ToString() { return "MultiDocsAndPositionsEnum(" + Arrays.ToString(Subs) + ")"; } } }
// ---------------------------------------------------------------------- // // Microsoft Windows NT // Copyright (C) Microsoft Corporation, 2007. // // Contents: Entry points for managed PowerShell plugin worker used to // host powershell in a WSMan service. // ---------------------------------------------------------------------- using System.Collections.ObjectModel; using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using System.Management.Automation.Internal; using System.Management.Automation.Remoting.Client; using System.Management.Automation.Remoting.Server; using System.Management.Automation.Tracing; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// Abstract class that defines common functionality for WinRM Plugin API Server Sessions /// </summary> internal abstract class WSManPluginServerSession : IDisposable { private object _syncObject; protected bool isClosed; protected bool isContextReported; // used to keep track of last error..this will be used // for reporting operation complete to WSMan. protected Exception lastErrorReported; // request context passed by WSMan while creating a shell or command. internal WSManNativeApi.WSManPluginRequest creationRequestDetails; // request context passed by WSMan while sending Plugin data. internal WSManNativeApi.WSManPluginRequest sendRequestDetails; internal WSManPluginOperationShutdownContext shutDownContext; // tracker used in conjunction with WSMan API to identify a particular // shell context. internal RegisteredWaitHandle registeredShutDownWaitHandle; internal WSManPluginServerTransportManager transportMgr; internal System.Int32 registeredShutdownNotification; // event that gets raised when session is closed.."source" will provide // IntPtr for "creationRequestDetails" which can be used to free // the context. internal event EventHandler<EventArgs> SessionClosed; // Track whether Dispose has been called. private bool _disposed = false; protected WSManPluginServerSession( WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager transportMgr) { _syncObject = new Object(); this.creationRequestDetails = creationRequestDetails; this.transportMgr = transportMgr; transportMgr.PrepareCalled += new EventHandler<EventArgs>(this.HandlePrepareFromTransportManager); transportMgr.WSManTransportErrorOccured += new EventHandler<TransportErrorOccuredEventArgs>(this.HandleTransportError); } public void Dispose() { // Dispose of unmanaged resources. Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SuppressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> True when called from Dispose(), False when called from Finalize(). protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!_disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { // Dispose managed resources. //Close(false); } // Call the appropriate methods to clean up // unmanaged resources here. // If disposing is false, // only the following code is executed. Close(false); // Note disposing has been done. _disposed = true; } } /// <summary> /// Use C# destructor syntax for finalization code. /// This destructor will run only if the Dispose method /// does not get called. /// It gives your base class the opportunity to finalize. /// Do not provide destructors in types derived from this class. /// </summary> ~WSManPluginServerSession() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. Dispose(false); } internal void SendOneItemToSession( WSManNativeApi.WSManPluginRequest requestDetails, int flags, string stream, WSManNativeApi.WSManData_UnToMan inboundData) { if ((!String.Equals(stream, WSManPluginConstants.SupportedInputStream, StringComparison.Ordinal)) && (!String.Equals(stream, WSManPluginConstants.SupportedPromptResponseStream, StringComparison.Ordinal))) { WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidInputStream, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidInputStream, WSManPluginConstants.SupportedInputStream)); return; } if (null == inboundData) { // no data is supplied..just ignore. WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.NoError); return; } if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_BINARY != inboundData.Type) { // only binary data is supported WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidInputDatatype, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidInputStream, "WSMAN_DATA_TYPE_BINARY")); return; } lock (_syncObject) { if (true == isClosed) { WSManPluginInstance.ReportWSManOperationComplete(requestDetails, lastErrorReported); return; } // store the send request details..because the operation complete // may happen from a different thread. sendRequestDetails = requestDetails; } SendOneItemToSessionHelper(inboundData.Data, stream); // report operation complete. ReportSendOperationComplete(); } internal void SendOneItemToSessionHelper( System.Byte[] data, string stream) { transportMgr.ProcessRawData(data, stream); } internal bool EnableSessionToSendDataToClient( WSManNativeApi.WSManPluginRequest requestDetails, int flags, WSManNativeApi.WSManStreamIDSet_UnToMan streamSet, WSManPluginOperationShutdownContext ctxtToReport) { if (true == isClosed) { WSManPluginInstance.ReportWSManOperationComplete(requestDetails, lastErrorReported); return false; } if ((null == streamSet) || (1 != streamSet.streamIDsCount)) { // only "stdout" is the supported output stream. WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidOutputStream, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidOutputStream, WSManPluginConstants.SupportedOutputStream)); return false; } if (!String.Equals(streamSet.streamIDs[0], WSManPluginConstants.SupportedOutputStream, StringComparison.Ordinal)) { // only "stdout" is the supported output stream. WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidOutputStream, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidOutputStream, WSManPluginConstants.SupportedOutputStream)); return false; } return transportMgr.EnableTransportManagerSendDataToClient(requestDetails, ctxtToReport); } /// <summary> /// Report session context to WSMan..this will let WSMan send ACK to /// client and client can send data. /// </summary> internal void ReportContext() { int result = 0; bool isRegisterWaitForSingleObjectFailed = false; lock (_syncObject) { if (true == isClosed) { return; } if (!isContextReported) { isContextReported = true; PSEtwLog.LogAnalyticInformational(PSEventId.ReportContext, PSOpcode.Connect, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, creationRequestDetails.ToString(), creationRequestDetails.ToString()); //RACE TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime // If Signal comes and executes before registering the notification handle, cleanup will be messed result = WSManNativeApi.WSManPluginReportContext(creationRequestDetails.unmanagedHandle, 0, creationRequestDetails.unmanagedHandle); if (Platform.IsWindows && (WSManPluginConstants.ExitCodeSuccess == result)) { registeredShutdownNotification = 1; // Wrap the provided handle so it can be passed to the registration function SafeWaitHandle safeWaitHandle = new SafeWaitHandle(creationRequestDetails.shutdownNotificationHandle, false); // Owned by WinRM EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle); // Register shutdown notification handle this.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject( eventWaitHandle, new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback), shutDownContext, -1, // INFINITE true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? if (null == this.registeredShutDownWaitHandle) { isRegisterWaitForSingleObjectFailed = true; registeredShutdownNotification = 0; } } } } if ((WSManPluginConstants.ExitCodeSuccess != result) || (isRegisterWaitForSingleObjectFailed)) { string errorMessage; if (isRegisterWaitForSingleObjectFailed) { errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed); } else { errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginReportContextFailed); } // Report error and close the session Exception mgdException = new InvalidOperationException(errorMessage); Close(mgdException); } } /// <summary> /// Added to provide derived classes with the ability to send event notifications. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> protected internal void SafeInvokeSessionClosed(Object sender, EventArgs eventArgs) { SessionClosed.SafeInvoke(sender, eventArgs); } // handle transport manager related errors internal void HandleTransportError(Object sender, TransportErrorOccuredEventArgs eventArgs) { Exception reasonForClose = null; if (null != eventArgs) { reasonForClose = eventArgs.Exception; } Close(reasonForClose); } // handle prepare from transport by reporting context to WSMan. internal void HandlePrepareFromTransportManager(Object sender, EventArgs eventArgs) { ReportContext(); ReportSendOperationComplete(); transportMgr.PrepareCalled -= new EventHandler<EventArgs>(this.HandlePrepareFromTransportManager); } internal void Close(bool isShuttingDown) { if (Interlocked.Exchange(ref registeredShutdownNotification, 0) == 1) { // release the shutdown notification handle. if (null != registeredShutDownWaitHandle) { registeredShutDownWaitHandle.Unregister(null); registeredShutDownWaitHandle = null; } } // Delete the context only if isShuttingDown != true. isShuttingDown will // be true only when the method is called from RegisterWaitForSingleObject // handler..in which case the context will be freed from the callback. if (null != shutDownContext) { shutDownContext = null; } transportMgr.WSManTransportErrorOccured -= new EventHandler<TransportErrorOccuredEventArgs>(this.HandleTransportError); // We should not use request details again after so releasing the resource. // Remember not to free this memory as this memory is allocated and owned by WSMan. creationRequestDetails = null; // if already disposing..no need to let finalizer thread // put resources to clean this object. //System.GC.SuppressFinalize(this); // TODO: This is already called in Dispose(). } // close current session and transport manager because of an exception internal void Close(Exception reasonForClose) { lastErrorReported = reasonForClose; WSManPluginOperationShutdownContext context = new WSManPluginOperationShutdownContext(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, false); CloseOperation(context, reasonForClose); } // Report Operation Complete using the send request details. internal void ReportSendOperationComplete() { lock (_syncObject) { if (null != sendRequestDetails) { // report and clear the send request details WSManPluginInstance.ReportWSManOperationComplete(sendRequestDetails, lastErrorReported); sendRequestDetails = null; } } } #region Pure virtual methods internal abstract void CloseOperation(WSManPluginOperationShutdownContext context, Exception reasonForClose); internal abstract void ExecuteConnect( WSManNativeApi.WSManPluginRequest requestDetails, // in int flags, // in WSManNativeApi.WSManData_UnToMan inboundConnectInformation); // in optional #endregion } /// <summary> /// /// </summary> internal class WSManPluginShellSession : WSManPluginServerSession { #region Private Members private Dictionary<IntPtr, WSManPluginCommandSession> _activeCommandSessions; private ServerRemoteSession _remoteSession; #endregion #region Internally Visible Members internal object shellSyncObject; #endregion #region Constructor internal WSManPluginShellSession( WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager transportMgr, ServerRemoteSession remoteSession, WSManPluginOperationShutdownContext shutDownContext) : base(creationRequestDetails, transportMgr) { _remoteSession = remoteSession; _remoteSession.Closed += new EventHandler<RemoteSessionStateMachineEventArgs>(this.HandleServerRemoteSessionClosed); _activeCommandSessions = new Dictionary<IntPtr, WSManPluginCommandSession>(); this.shellSyncObject = new System.Object(); this.shutDownContext = shutDownContext; } #endregion /// <summary> /// Main Routine for Connect on a Shell. /// Calls in server remotesessions ExecuteConnect to run the Connect algorithm /// This call is synchronous. i.e WSManOperationComplete will be called before the routine completes /// </summary> /// <param name="requestDetails"></param> /// <param name="flags"></param> /// <param name="inboundConnectInformation"></param> internal override void ExecuteConnect( WSManNativeApi.WSManPluginRequest requestDetails, // in int flags, // in WSManNativeApi.WSManData_UnToMan inboundConnectInformation) // in optional { if (null == inboundConnectInformation) { WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.NullInvalidInput, StringUtil.Format( RemotingErrorIdStrings.WSManPluginNullInvalidInput, "inboundConnectInformation", "WSManPluginShellConnect")); return; } //not registering shutdown event as this is a synchronous operation. IntPtr responseXml = IntPtr.Zero; try { System.Byte[] inputData; System.Byte[] outputData; // Retrieve the string (Base64 encoded) inputData = ServerOperationHelpers.ExtractEncodedXmlElement( inboundConnectInformation.Text, WSManNativeApi.PS_CONNECT_XML_TAG); //this will raise exceptions on failure try { _remoteSession.ExecuteConnect(inputData, out outputData); //construct Xml to send back string responseData = String.Format(System.Globalization.CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\">{2}</{0}>", WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG, WSManNativeApi.PS_XML_NAMESPACE, Convert.ToBase64String(outputData)); //TODO: currently using OperationComplete to report back the responseXml. This will need to change to use WSManReportObject //that is currently internal. WSManPluginInstance.ReportOperationComplete(requestDetails, WSManPluginErrorCodes.NoError, responseData); } catch (PSRemotingDataStructureException ex) { WSManPluginInstance.ReportOperationComplete(requestDetails, WSManPluginErrorCodes.PluginConnectOperationFailed, ex.Message); } } catch (OutOfMemoryException) { WSManPluginInstance.ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory); } finally { if (responseXml != IntPtr.Zero) { Marshal.FreeHGlobal(responseXml); } } return; } // Create a new command in the shell context. internal void CreateCommand( IntPtr pluginContext, WSManNativeApi.WSManPluginRequest requestDetails, int flags, string commandLine, WSManNativeApi.WSManCommandArgSet arguments) { try { // inbound cmd information is already verified.. so no need to verify here. WSManPluginCommandTransportManager serverCmdTransportMgr = new WSManPluginCommandTransportManager(transportMgr); serverCmdTransportMgr.Initialize(); // Apply quota limits on the command transport manager _remoteSession.ApplyQuotaOnCommandTransportManager(serverCmdTransportMgr); WSManPluginCommandSession mgdCmdSession = new WSManPluginCommandSession(requestDetails, serverCmdTransportMgr, _remoteSession); AddToActiveCmdSessions(mgdCmdSession); mgdCmdSession.SessionClosed += new EventHandler<EventArgs>(this.HandleCommandSessionClosed); mgdCmdSession.shutDownContext = new WSManPluginOperationShutdownContext( pluginContext, creationRequestDetails.unmanagedHandle, mgdCmdSession.creationRequestDetails.unmanagedHandle, false); do { if (!mgdCmdSession.ProcessArguments(arguments)) { WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.InvalidArgSet, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidArgSet, "WSManPluginCommand")); break; } // Report plugin context to WSMan mgdCmdSession.ReportContext(); } while (false); } catch (System.Exception e) { CommandProcessorBase.CheckForSevereException(e); // if there is an exception creating remote session send the message to client. WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.ManagedException, StringUtil.Format( RemotingErrorIdStrings.WSManPluginManagedException, e.Message)); } } // Closes the command and clears associated resources internal void CloseCommandOperation( WSManPluginOperationShutdownContext context) { WSManPluginCommandSession mgdCmdSession = GetCommandSession(context.commandContext); if (null == mgdCmdSession) { // this should never be the case. this will protect the service. return; } // update the internal data store only if this is not receive operation. if (!context.isReceiveOperation) { DeleteFromActiveCmdSessions(mgdCmdSession.creationRequestDetails.unmanagedHandle); } mgdCmdSession.CloseOperation(context, null); } // adds command session to active command Sessions store and returns the id // at which the session is added. private void AddToActiveCmdSessions( WSManPluginCommandSession newCmdSession) { lock (shellSyncObject) { if (isClosed) { return; } IntPtr key = newCmdSession.creationRequestDetails.unmanagedHandle; Dbg.Assert(IntPtr.Zero != key, "NULL handles should not be provided"); if (!_activeCommandSessions.ContainsKey(key)) { _activeCommandSessions.Add(key, newCmdSession); return; } } } private void DeleteFromActiveCmdSessions( IntPtr keyToDelete) { lock (shellSyncObject) { if (isClosed) { return; } _activeCommandSessions.Remove(keyToDelete); } } // closes all the active command sessions. private void CloseAndClearCommandSessions( Exception reasonForClose) { Collection<WSManPluginCommandSession> copyCmdSessions = new Collection<WSManPluginCommandSession>(); lock (shellSyncObject) { Dictionary<IntPtr, WSManPluginCommandSession>.Enumerator cmdEnumerator = _activeCommandSessions.GetEnumerator(); while (cmdEnumerator.MoveNext()) { copyCmdSessions.Add(cmdEnumerator.Current.Value); } _activeCommandSessions.Clear(); } // close the command sessions outside of the lock IEnumerator<WSManPluginCommandSession> cmdSessionEnumerator = copyCmdSessions.GetEnumerator(); while (cmdSessionEnumerator.MoveNext()) { WSManPluginCommandSession cmdSession = cmdSessionEnumerator.Current; // we are not interested in session closed events anymore as we are initiating the close // anyway/ cmdSession.SessionClosed -= new EventHandler<EventArgs>(this.HandleCommandSessionClosed); cmdSession.Close(reasonForClose); } copyCmdSessions.Clear(); } // returns the command session instance for a given command id. // null if not found. internal WSManPluginCommandSession GetCommandSession( IntPtr cmdContext) { lock (shellSyncObject) { WSManPluginCommandSession result = null; _activeCommandSessions.TryGetValue(cmdContext, out result); return result; } } private void HandleServerRemoteSessionClosed( Object sender, RemoteSessionStateMachineEventArgs eventArgs) { Exception reasonForClose = null; if (null != eventArgs) { reasonForClose = eventArgs.Reason; } Close(reasonForClose); } private void HandleCommandSessionClosed( Object source, EventArgs e) { // command context is passed as "source" parameter DeleteFromActiveCmdSessions((IntPtr)source); } internal override void CloseOperation( WSManPluginOperationShutdownContext context, Exception reasonForClose) { // let command sessions to close. lock (shellSyncObject) { if (true == isClosed) { return; } if (!context.isReceiveOperation) { isClosed = true; } } bool isRcvOpShuttingDown = (context.isShuttingDown) && (context.isReceiveOperation); bool isRcvOp = context.isReceiveOperation; bool isShuttingDown = context.isShuttingDown; // close the pending send operation if any ReportSendOperationComplete(); // close the shell's transport manager after commands handled the operation transportMgr.DoClose(isRcvOpShuttingDown, reasonForClose); if (!isRcvOp) { // Initiate close on the active command sessions and then clear the internal // Command Session dictionary CloseAndClearCommandSessions(reasonForClose); // raise session closed event and let dependent code to release resources. // null check is not performed here because the handler will take care of this. base.SafeInvokeSessionClosed(creationRequestDetails.unmanagedHandle, EventArgs.Empty); // Send Operation Complete to WSMan service WSManPluginInstance.ReportWSManOperationComplete(creationRequestDetails, reasonForClose); // let base class release its resources base.Close(isShuttingDown); } // TODO: Do this.Dispose(); here? } } internal class WSManPluginCommandSession : WSManPluginServerSession { #region Private Members private ServerRemoteSession _remoteSession; #endregion #region Internally Visible Members internal object cmdSyncObject; #endregion #region Constructor internal WSManPluginCommandSession( WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager transportMgr, ServerRemoteSession remoteSession) : base(creationRequestDetails, transportMgr) { _remoteSession = remoteSession; cmdSyncObject = new System.Object(); } #endregion internal bool ProcessArguments( WSManNativeApi.WSManCommandArgSet arguments) { if (1 != arguments.argsCount) { return false; } System.Byte[] convertedBase64 = Convert.FromBase64String(arguments.args[0]); transportMgr.ProcessRawData(convertedBase64, WSManPluginConstants.SupportedInputStream); return true; } /// <summary> /// /// </summary> /// <param name="requestDetails"></param> internal void Stop( WSManNativeApi.WSManPluginRequest requestDetails) { // stop the command..command will be stoped if we raise ClosingEvent on // transport manager. transportMgr.PerformStop(); WSManPluginInstance.ReportWSManOperationComplete(requestDetails, null); } internal override void CloseOperation( WSManPluginOperationShutdownContext context, Exception reasonForClose) { // let command sessions to close. lock (cmdSyncObject) { if (true == isClosed) { return; } if (!context.isReceiveOperation) { isClosed = true; } } bool isRcvOp = context.isReceiveOperation; // only one thread will be here. bool isRcvOpShuttingDown = (context.isShuttingDown) && (context.isReceiveOperation) && (context.commandContext == creationRequestDetails.unmanagedHandle); bool isCmdShuttingDown = (context.isShuttingDown) && (!context.isReceiveOperation) && (context.commandContext == creationRequestDetails.unmanagedHandle); // close the pending send operation if any ReportSendOperationComplete(); // close the shell's transport manager first..so we wont send data. transportMgr.DoClose(isRcvOpShuttingDown, reasonForClose); if (!isRcvOp) { // raise session closed event and let dependent code to release resources. // null check is not performed here because Managed C++ will take care of this. base.SafeInvokeSessionClosed(creationRequestDetails.unmanagedHandle, EventArgs.Empty); // Send Operation Complete to WSMan service WSManPluginInstance.ReportWSManOperationComplete(creationRequestDetails, reasonForClose); // let base class release its resources this.Close(isCmdShuttingDown); } } /// <summary> /// Main routine for connect on a command/pipeline.. Currently NO-OP /// will be enhanced later to support intelligent connect... like ending input streams on pipelines /// that are still waiting for input data /// </summary> /// <param name="requestDetails"></param> /// <param name="flags"></param> /// <param name="inboundConnectInformation"></param> internal override void ExecuteConnect( WSManNativeApi.WSManPluginRequest requestDetails, int flags, WSManNativeApi.WSManData_UnToMan inboundConnectInformation) { WSManPluginInstance.ReportOperationComplete( requestDetails, WSManPluginErrorCodes.NoError); return; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Add_Vector128_Int32() { var test = new SimpleBinaryOpTest__Add_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__Add_Vector128_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Add_Vector128_Int32 testClass) { var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Add_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Add_Vector128_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleBinaryOpTest__Add_Vector128_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Add( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Add_Vector128_Int32(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__Add_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Add( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(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<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((int)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using AutoMapper.Configuration; using AutoMapper.Configuration.Conventions; using AutoMapper.Execution; using AutoMapper.Internal; namespace AutoMapper { using static Expression; [DebuggerDisplay("{Name}")] [EditorBrowsable(EditorBrowsableState.Never)] public class ProfileMap { private ITypeMapConfiguration[] _typeMapConfigs; private Dictionary<TypePair, ITypeMapConfiguration> _openTypeMapConfigs; private Dictionary<Type, TypeDetails> _typeDetails; private ConcurrentDictionaryWrapper<Type, TypeDetails> _runtimeTypeDetails; private readonly IMemberConfiguration[] _memberConfigurations; public ProfileMap(IProfileConfiguration profile, IGlobalConfigurationExpression configuration = null) { var globalProfile = (IProfileConfiguration)configuration; Name = profile.ProfileName; AllowNullCollections = profile.AllowNullCollections ?? configuration?.AllowNullCollections ?? false; AllowNullDestinationValues = profile.AllowNullDestinationValues ?? configuration?.AllowNullDestinationValues ?? true; EnableNullPropagationForQueryMapping = profile.EnableNullPropagationForQueryMapping ?? configuration?.EnableNullPropagationForQueryMapping ?? false; ConstructorMappingEnabled = profile.ConstructorMappingEnabled ?? globalProfile?.ConstructorMappingEnabled ?? true; MethodMappingEnabled = profile.MethodMappingEnabled ?? globalProfile?.MethodMappingEnabled ?? true; FieldMappingEnabled = profile.FieldMappingEnabled ?? globalProfile?.FieldMappingEnabled ?? true; ShouldMapField = profile.ShouldMapField ?? configuration?.ShouldMapField ?? (p => p.IsPublic); ShouldMapProperty = profile.ShouldMapProperty ?? configuration?.ShouldMapProperty ?? (p => p.IsPublic()); ShouldMapMethod = profile.ShouldMapMethod ?? configuration?.ShouldMapMethod ?? (p => !p.IsSpecialName); ShouldUseConstructor = profile.ShouldUseConstructor ?? configuration?.ShouldUseConstructor ?? (c => true); ValueTransformers = profile.ValueTransformers.Concat(configuration?.ValueTransformers).ToArray(); _memberConfigurations = profile.MemberConfigurations.Concat(globalProfile?.MemberConfigurations).ToArray(); var nameSplitMember = _memberConfigurations[0].MemberMappers.OfType<NameSplitMember>().FirstOrDefault(); if (nameSplitMember != null) { nameSplitMember.SourceMemberNamingConvention = profile.SourceMemberNamingConvention ?? PascalCaseNamingConvention.Instance; nameSplitMember.DestinationMemberNamingConvention = profile.DestinationMemberNamingConvention ?? PascalCaseNamingConvention.Instance; } GlobalIgnores = profile.GlobalIgnores.Concat(globalProfile?.GlobalIgnores).ToArray(); SourceExtensionMethods = profile.SourceExtensionMethods.Concat(globalProfile?.SourceExtensionMethods).ToArray(); AllPropertyMapActions = profile.AllPropertyMapActions.Concat(globalProfile?.AllPropertyMapActions).ToArray(); AllTypeMapActions = profile.AllTypeMapActions.Concat(globalProfile?.AllTypeMapActions).ToArray(); var prePostFixes = profile.MemberConfigurations.Concat(globalProfile?.MemberConfigurations) .Select(m => m.NameMapper) .SelectMany(m => m.NamedMappers) .OfType<PrePostfixName>() .ToArray(); Prefixes = prePostFixes.SelectMany(m => m.Prefixes).Distinct().ToList(); Postfixes = prePostFixes.SelectMany(m => m.Postfixes).Distinct().ToList(); SetTypeMapConfigs(); SetOpenTypeMapConfigs(); _typeDetails = new(2*_typeMapConfigs.Length); return; void SetTypeMapConfigs() { _typeMapConfigs = new ITypeMapConfiguration[profile.TypeMapConfigs.Count]; var index = 0; var reverseMapsCount = 0; foreach (var typeMapConfig in profile.TypeMapConfigs) { _typeMapConfigs[index++] = typeMapConfig; if (typeMapConfig.ReverseTypeMap != null) { reverseMapsCount++; } } TypeMapsCount = index + reverseMapsCount; } void SetOpenTypeMapConfigs() { _openTypeMapConfigs = new(profile.OpenTypeMapConfigs.Count); foreach (var openTypeMapConfig in profile.OpenTypeMapConfigs) { _openTypeMapConfigs.Add(openTypeMapConfig.Types, openTypeMapConfig); var reverseMap = openTypeMapConfig.ReverseTypeMap; if (reverseMap != null) { _openTypeMapConfigs.Add(reverseMap.Types, reverseMap); } } } } public int OpenTypeMapsCount => _openTypeMapConfigs.Count; public int TypeMapsCount { get; private set; } internal void Clear() { _typeDetails = null; _typeMapConfigs = null; _runtimeTypeDetails = new(TypeDetailsFactory, 2 * _openTypeMapConfigs.Count); } public bool AllowNullCollections { get; } public bool AllowNullDestinationValues { get; } public bool ConstructorMappingEnabled { get; } public bool EnableNullPropagationForQueryMapping { get; } public bool MethodMappingEnabled { get; } public bool FieldMappingEnabled { get; } public string Name { get; } public Func<FieldInfo, bool> ShouldMapField { get; } public Func<PropertyInfo, bool> ShouldMapProperty { get; } public Func<MethodInfo, bool> ShouldMapMethod { get; } public Func<ConstructorInfo, bool> ShouldUseConstructor { get; } public IEnumerable<Action<PropertyMap, IMemberConfigurationExpression>> AllPropertyMapActions { get; } public IEnumerable<Action<TypeMap, IMappingExpression>> AllTypeMapActions { get; } public IReadOnlyCollection<string> GlobalIgnores { get; } public IEnumerable<IMemberConfiguration> MemberConfigurations => _memberConfigurations; public IEnumerable<MethodInfo> SourceExtensionMethods { get; } public List<string> Prefixes { get; } public List<string> Postfixes { get; } public IReadOnlyCollection<ValueTransformerConfiguration> ValueTransformers { get; } public TypeDetails CreateTypeDetails(Type type) { if (_typeDetails == null) { return _runtimeTypeDetails.GetOrAdd(type); } if (_typeDetails.TryGetValue(type, out var typeDetails)) { return typeDetails; } typeDetails = TypeDetailsFactory(type); _typeDetails.Add(type, typeDetails); return typeDetails; } private TypeDetails TypeDetailsFactory(Type type) => new(type, this); public void Register(IGlobalConfiguration configurationProvider) { foreach (var config in _typeMapConfigs) { BuildTypeMap(configurationProvider, config); if (config.ReverseTypeMap != null) { BuildTypeMap(configurationProvider, config.ReverseTypeMap); } } } public void Configure(IGlobalConfiguration configurationProvider) { foreach (var typeMapConfiguration in _typeMapConfigs) { Configure(typeMapConfiguration, configurationProvider); if (typeMapConfiguration.ReverseTypeMap != null) { Configure(typeMapConfiguration.ReverseTypeMap, configurationProvider); } } } private void BuildTypeMap(IGlobalConfiguration configurationProvider, ITypeMapConfiguration config) { var typeMap = new TypeMap(config.SourceType, config.DestinationType, this, config.IsReverseMap); config.Configure(typeMap); configurationProvider.RegisterTypeMap(typeMap); } private void Configure(ITypeMapConfiguration typeMapConfiguration, IGlobalConfiguration configurationProvider) { var typeMap = typeMapConfiguration.TypeMap; if (typeMap.IncludeAllDerivedTypes) { IncludeAllDerived(configurationProvider, typeMap); } Configure(typeMap, configurationProvider); } private static void IncludeAllDerived(IGlobalConfiguration configurationProvider, TypeMap typeMap) { foreach (var derivedMap in configurationProvider.GetAllTypeMaps().Where(tm => typeMap != tm && typeMap.SourceType.IsAssignableFrom(tm.SourceType) && typeMap.DestinationType.IsAssignableFrom(tm.DestinationType))) { typeMap.IncludeDerivedTypes(derivedMap.Types); } } private void Configure(TypeMap typeMap, IGlobalConfiguration configurationProvider) { foreach (var action in AllTypeMapActions) { var expression = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList); action(typeMap, expression); expression.Configure(typeMap); } foreach (var action in AllPropertyMapActions) { foreach (var propertyMap in typeMap.PropertyMaps) { var memberExpression = new MappingExpression.MemberConfigurationExpression(propertyMap.DestinationMember, typeMap.SourceType); action(propertyMap, memberExpression); memberExpression.Configure(typeMap); } } ApplyBaseMaps(typeMap, typeMap, configurationProvider); ApplyDerivedMaps(typeMap, typeMap, configurationProvider); ApplyMemberMaps(typeMap, configurationProvider); } public TypeMap CreateClosedGenericTypeMap(ITypeMapConfiguration openMapConfig, TypePair closedTypes, IGlobalConfiguration configurationProvider) { TypeMap closedMap; lock (configurationProvider) { closedMap = new TypeMap(closedTypes.SourceType, closedTypes.DestinationType, this); } openMapConfig.Configure(closedMap); Configure(closedMap, configurationProvider); if (closedMap.TypeConverterType != null) { var typeParams = (openMapConfig.SourceType.IsGenericTypeDefinition ? closedTypes.SourceType.GenericTypeArguments : Type.EmptyTypes) .Concat(openMapConfig.DestinationType.IsGenericTypeDefinition ? closedTypes.DestinationType.GenericTypeArguments : Type.EmptyTypes); var neededParameters = closedMap.TypeConverterType.GenericParametersCount(); closedMap.TypeConverterType = closedMap.TypeConverterType.MakeGenericType(typeParams.Take(neededParameters).ToArray()); } if (closedMap.DestinationTypeOverride is { IsGenericTypeDefinition: true }) { var neededParameters = closedMap.DestinationTypeOverride.GenericParametersCount(); closedMap.DestinationTypeOverride = closedMap.DestinationTypeOverride.MakeGenericType(closedTypes.DestinationType.GenericTypeArguments.Take(neededParameters).ToArray()); } return closedMap; } public ITypeMapConfiguration GetGenericMap(TypePair genericPair) => _openTypeMapConfigs.GetValueOrDefault(genericPair); private void ApplyBaseMaps(TypeMap derivedMap, TypeMap currentMap, IGlobalConfiguration configurationProvider) { foreach (var baseMap in configurationProvider.GetIncludedTypeMaps(currentMap.IncludedBaseTypes)) { baseMap.IncludeDerivedTypes(currentMap.Types); derivedMap.AddInheritedMap(baseMap); ApplyBaseMaps(derivedMap, baseMap, configurationProvider); } } private void ApplyMemberMaps(TypeMap currentMap, IGlobalConfiguration configurationProvider) { if (!currentMap.HasIncludedMembers) { return; } foreach (var includedMemberExpression in currentMap.GetAllIncludedMembers()) { var includedMap = configurationProvider.GetIncludedTypeMap(includedMemberExpression.Body.Type, currentMap.DestinationType); var includedMember = new IncludedMember(includedMap, includedMemberExpression); if (currentMap.AddMemberMap(includedMember)) { ApplyMemberMaps(includedMap, configurationProvider); foreach (var inheritedIncludedMember in includedMap.IncludedMembersTypeMaps) { currentMap.AddMemberMap(includedMember.Chain(inheritedIncludedMember)); } } } } private void ApplyDerivedMaps(TypeMap baseMap, TypeMap typeMap, IGlobalConfiguration configurationProvider) { foreach (var derivedMap in configurationProvider.GetIncludedTypeMaps(typeMap)) { derivedMap.IncludeBaseTypes(typeMap.Types); derivedMap.AddInheritedMap(baseMap); ApplyDerivedMaps(baseMap, derivedMap, configurationProvider); } } public bool MapDestinationPropertyToSource(TypeDetails sourceTypeDetails, Type destType, Type destMemberType, string destMemberName, List<MemberInfo> members, bool reverseNamingConventions) { if(destMemberName == null) { return false; } foreach (var memberConfiguration in _memberConfigurations) { if (memberConfiguration.MapDestinationPropertyToSource(this, sourceTypeDetails, destType, destMemberType, destMemberName, members, reverseNamingConventions)) { return true; } } return false; } public bool AllowsNullDestinationValuesFor(MemberMap memberMap = null) => memberMap?.AllowNull ?? AllowNullDestinationValues; public bool AllowsNullCollectionsFor(MemberMap memberMap = null) => memberMap?.AllowNull ?? AllowNullCollections; } [EditorBrowsable(EditorBrowsableState.Never)] [DebuggerDisplay("{MemberExpression}, {TypeMap}")] public class IncludedMember : IEquatable<IncludedMember> { public IncludedMember(TypeMap typeMap, LambdaExpression memberExpression) : this(typeMap, memberExpression, Variable(memberExpression.Body.Type, string.Join("", memberExpression.GetMembersChain().Select(m => m.Name))), memberExpression) { } private IncludedMember(TypeMap typeMap, LambdaExpression memberExpression, ParameterExpression variable, LambdaExpression projectToCustomSource) { TypeMap = typeMap; MemberExpression = memberExpression; Variable = variable; ProjectToCustomSource = projectToCustomSource; } public IncludedMember Chain(IncludedMember other) { if (other == null) { return this; } return new(other.TypeMap, Chain(other.MemberExpression), other.Variable, Chain(MemberExpression, other.MemberExpression)); } public static LambdaExpression Chain(LambdaExpression customSource, LambdaExpression lambda) => Lambda(lambda.ReplaceParameters(customSource.Body), customSource.Parameters); public TypeMap TypeMap { get; } public LambdaExpression MemberExpression { get; } public ParameterExpression Variable { get; } public LambdaExpression ProjectToCustomSource { get; } public LambdaExpression Chain(LambdaExpression lambda) => Lambda(lambda.ReplaceParameters(Variable), lambda.Parameters); public bool Equals(IncludedMember other) => TypeMap == other?.TypeMap; public override int GetHashCode() => TypeMap.GetHashCode(); } }
namespace android.media { [global::MonoJavaBridge.JavaClass()] public partial class ToneGenerator : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ToneGenerator(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; protected override void finalize() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.ToneGenerator.staticClass, "finalize", "()V", ref global::android.media.ToneGenerator._m0); } private static global::MonoJavaBridge.MethodId _m1; public virtual void release() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.ToneGenerator.staticClass, "release", "()V", ref global::android.media.ToneGenerator._m1); } private static global::MonoJavaBridge.MethodId _m2; public virtual bool startTone(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.ToneGenerator.staticClass, "startTone", "(I)Z", ref global::android.media.ToneGenerator._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public virtual bool startTone(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.ToneGenerator.staticClass, "startTone", "(II)Z", ref global::android.media.ToneGenerator._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void stopTone() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.ToneGenerator.staticClass, "stopTone", "()V", ref global::android.media.ToneGenerator._m4); } private static global::MonoJavaBridge.MethodId _m5; public ToneGenerator(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.media.ToneGenerator._m5.native == global::System.IntPtr.Zero) global::android.media.ToneGenerator._m5 = @__env.GetMethodIDNoThrow(global::android.media.ToneGenerator.staticClass, "<init>", "(II)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.media.ToneGenerator.staticClass, global::android.media.ToneGenerator._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } public static int TONE_DTMF_0 { get { return 0; } } public static int TONE_DTMF_1 { get { return 1; } } public static int TONE_DTMF_2 { get { return 2; } } public static int TONE_DTMF_3 { get { return 3; } } public static int TONE_DTMF_4 { get { return 4; } } public static int TONE_DTMF_5 { get { return 5; } } public static int TONE_DTMF_6 { get { return 6; } } public static int TONE_DTMF_7 { get { return 7; } } public static int TONE_DTMF_8 { get { return 8; } } public static int TONE_DTMF_9 { get { return 9; } } public static int TONE_DTMF_S { get { return 10; } } public static int TONE_DTMF_P { get { return 11; } } public static int TONE_DTMF_A { get { return 12; } } public static int TONE_DTMF_B { get { return 13; } } public static int TONE_DTMF_C { get { return 14; } } public static int TONE_DTMF_D { get { return 15; } } public static int TONE_SUP_DIAL { get { return 16; } } public static int TONE_SUP_BUSY { get { return 17; } } public static int TONE_SUP_CONGESTION { get { return 18; } } public static int TONE_SUP_RADIO_ACK { get { return 19; } } public static int TONE_SUP_RADIO_NOTAVAIL { get { return 20; } } public static int TONE_SUP_ERROR { get { return 21; } } public static int TONE_SUP_CALL_WAITING { get { return 22; } } public static int TONE_SUP_RINGTONE { get { return 23; } } public static int TONE_PROP_BEEP { get { return 24; } } public static int TONE_PROP_ACK { get { return 25; } } public static int TONE_PROP_NACK { get { return 26; } } public static int TONE_PROP_PROMPT { get { return 27; } } public static int TONE_PROP_BEEP2 { get { return 28; } } public static int TONE_SUP_INTERCEPT { get { return 29; } } public static int TONE_SUP_INTERCEPT_ABBREV { get { return 30; } } public static int TONE_SUP_CONGESTION_ABBREV { get { return 31; } } public static int TONE_SUP_CONFIRM { get { return 32; } } public static int TONE_SUP_PIP { get { return 33; } } public static int TONE_CDMA_DIAL_TONE_LITE { get { return 34; } } public static int TONE_CDMA_NETWORK_USA_RINGBACK { get { return 35; } } public static int TONE_CDMA_INTERCEPT { get { return 36; } } public static int TONE_CDMA_ABBR_INTERCEPT { get { return 37; } } public static int TONE_CDMA_REORDER { get { return 38; } } public static int TONE_CDMA_ABBR_REORDER { get { return 39; } } public static int TONE_CDMA_NETWORK_BUSY { get { return 40; } } public static int TONE_CDMA_CONFIRM { get { return 41; } } public static int TONE_CDMA_ANSWER { get { return 42; } } public static int TONE_CDMA_NETWORK_CALLWAITING { get { return 43; } } public static int TONE_CDMA_PIP { get { return 44; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_NORMAL { get { return 45; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_INTERGROUP { get { return 46; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_SP_PRI { get { return 47; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PAT3 { get { return 48; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PING_RING { get { return 49; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PAT5 { get { return 50; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PAT6 { get { return 51; } } public static int TONE_CDMA_CALL_SIGNAL_ISDN_PAT7 { get { return 52; } } public static int TONE_CDMA_HIGH_L { get { return 53; } } public static int TONE_CDMA_MED_L { get { return 54; } } public static int TONE_CDMA_LOW_L { get { return 55; } } public static int TONE_CDMA_HIGH_SS { get { return 56; } } public static int TONE_CDMA_MED_SS { get { return 57; } } public static int TONE_CDMA_LOW_SS { get { return 58; } } public static int TONE_CDMA_HIGH_SSL { get { return 59; } } public static int TONE_CDMA_MED_SSL { get { return 60; } } public static int TONE_CDMA_LOW_SSL { get { return 61; } } public static int TONE_CDMA_HIGH_SS_2 { get { return 62; } } public static int TONE_CDMA_MED_SS_2 { get { return 63; } } public static int TONE_CDMA_LOW_SS_2 { get { return 64; } } public static int TONE_CDMA_HIGH_SLS { get { return 65; } } public static int TONE_CDMA_MED_SLS { get { return 66; } } public static int TONE_CDMA_LOW_SLS { get { return 67; } } public static int TONE_CDMA_HIGH_S_X4 { get { return 68; } } public static int TONE_CDMA_MED_S_X4 { get { return 69; } } public static int TONE_CDMA_LOW_S_X4 { get { return 70; } } public static int TONE_CDMA_HIGH_PBX_L { get { return 71; } } public static int TONE_CDMA_MED_PBX_L { get { return 72; } } public static int TONE_CDMA_LOW_PBX_L { get { return 73; } } public static int TONE_CDMA_HIGH_PBX_SS { get { return 74; } } public static int TONE_CDMA_MED_PBX_SS { get { return 75; } } public static int TONE_CDMA_LOW_PBX_SS { get { return 76; } } public static int TONE_CDMA_HIGH_PBX_SSL { get { return 77; } } public static int TONE_CDMA_MED_PBX_SSL { get { return 78; } } public static int TONE_CDMA_LOW_PBX_SSL { get { return 79; } } public static int TONE_CDMA_HIGH_PBX_SLS { get { return 80; } } public static int TONE_CDMA_MED_PBX_SLS { get { return 81; } } public static int TONE_CDMA_LOW_PBX_SLS { get { return 82; } } public static int TONE_CDMA_HIGH_PBX_S_X4 { get { return 83; } } public static int TONE_CDMA_MED_PBX_S_X4 { get { return 84; } } public static int TONE_CDMA_LOW_PBX_S_X4 { get { return 85; } } public static int TONE_CDMA_ALERT_NETWORK_LITE { get { return 86; } } public static int TONE_CDMA_ALERT_AUTOREDIAL_LITE { get { return 87; } } public static int TONE_CDMA_ONE_MIN_BEEP { get { return 88; } } public static int TONE_CDMA_KEYPAD_VOLUME_KEY_LITE { get { return 89; } } public static int TONE_CDMA_PRESSHOLDKEY_LITE { get { return 90; } } public static int TONE_CDMA_ALERT_INCALL_LITE { get { return 91; } } public static int TONE_CDMA_EMERGENCY_RINGBACK { get { return 92; } } public static int TONE_CDMA_ALERT_CALL_GUARD { get { return 93; } } public static int TONE_CDMA_SOFT_ERROR_LITE { get { return 94; } } public static int TONE_CDMA_CALLDROP_LITE { get { return 95; } } public static int TONE_CDMA_NETWORK_BUSY_ONE_SHOT { get { return 96; } } public static int TONE_CDMA_ABBR_ALERT { get { return 97; } } public static int TONE_CDMA_SIGNAL_OFF { get { return 98; } } public static int MAX_VOLUME { get { return 100; } } public static int MIN_VOLUME { get { return 0; } } static ToneGenerator() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.media.ToneGenerator.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/ToneGenerator")); } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.EventSystems; using System.Linq; using MoonSharp.Interpreter; namespace Fungus { /// <summary> /// Presents multiple choice buttons to the players. /// </summary> public class MenuDialog : MonoBehaviour { [Tooltip("Automatically select the first interactable button when the menu is shown.")] [SerializeField] protected bool autoSelectFirstButton = false; protected Button[] cachedButtons; protected Slider cachedSlider; protected virtual void Awake() { Button[] optionButtons = GetComponentsInChildren<Button>(); cachedButtons = optionButtons; Slider timeoutSlider = GetComponentInChildren<Slider>(); cachedSlider = timeoutSlider; if (Application.isPlaying) { // Don't auto disable buttons in the editor Clear(); } } protected virtual void OnEnable() { // The canvas may fail to update if the menu dialog is enabled in the first game frame. // To fix this we just need to force a canvas update when the object is enabled. Canvas.ForceUpdateCanvases(); } protected virtual IEnumerator WaitForTimeout(float timeoutDuration, Block targetBlock) { float elapsedTime = 0; Slider timeoutSlider = GetComponentInChildren<Slider>(); while (elapsedTime < timeoutDuration) { if (timeoutSlider != null) { float t = 1f - elapsedTime / timeoutDuration; timeoutSlider.value = t; } elapsedTime += Time.deltaTime; yield return null; } Clear(); gameObject.SetActive(false); HideSayDialog(); if (targetBlock != null) { targetBlock.StartExecution(); } } protected IEnumerator CallBlock(Block block) { yield return new WaitForEndOfFrame(); block.StartExecution(); } protected IEnumerator CallLuaClosure(LuaEnvironment luaEnv, Closure callback) { yield return new WaitForEndOfFrame(); if (callback != null) { luaEnv.RunLuaFunction(callback, true); } } #region Public members /// <summary> /// Currently active Menu Dialog used to display Menu options /// </summary> public static MenuDialog ActiveMenuDialog { get; set; } /// <summary> /// Returns a menu dialog by searching for one in the scene or creating one if none exists. /// </summary> public static MenuDialog GetMenuDialog() { if (ActiveMenuDialog == null) { // Use first Menu Dialog found in the scene (if any) var md = GameObject.FindObjectOfType<MenuDialog>(); if (md != null) { ActiveMenuDialog = md; } if (ActiveMenuDialog == null) { // Auto spawn a menu dialog object from the prefab GameObject prefab = Resources.Load<GameObject>("Prefabs/MenuDialog"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.SetActive(false); go.name = "MenuDialog"; ActiveMenuDialog = go.GetComponent<MenuDialog>(); } } } return ActiveMenuDialog; } /// <summary> /// A cached list of button objects in the menu dialog. /// </summary> /// <value>The cached buttons.</value> public virtual Button[] CachedButtons { get { return cachedButtons; } } /// <summary> /// A cached slider object used for the timer in the menu dialog. /// </summary> /// <value>The cached slider.</value> public virtual Slider CachedSlider { get { return cachedSlider; } } /// <summary> /// Sets the active state of the Menu Dialog gameobject. /// </summary> public virtual void SetActive(bool state) { gameObject.SetActive(state); } /// <summary> /// Clear all displayed options in the Menu Dialog. /// </summary> public virtual void Clear() { StopAllCoroutines(); var optionButtons = GetComponentsInChildren<Button>(); for (int i = 0; i < optionButtons.Length; i++) { var button = optionButtons[i]; button.onClick.RemoveAllListeners(); } for (int i = 0; i < optionButtons.Length; i++) { var button = optionButtons[i]; if (button != null) { button.gameObject.SetActive(false); } } Slider timeoutSlider = GetComponentInChildren<Slider>(); if (timeoutSlider != null) { timeoutSlider.gameObject.SetActive(false); } } /// <summary> /// Hides any currently displayed Say Dialog. /// </summary> public virtual void HideSayDialog() { var sayDialog = SayDialog.GetSayDialog(); if (sayDialog != null) { sayDialog.FadeWhenDone = true; } } /// <summary> /// Adds the option to the list of displayed options. Calls a Block when selected. /// Will cause the Menu dialog to become visible if it is not already visible. /// </summary> /// <returns><c>true</c>, if the option was added successfully.</returns> /// <param name="text">The option text to display on the button.</param> /// <param name="interactable">If false, the option is displayed but is not selectable.</param> /// <param name="targetBlock">Block to execute when the option is selected.</param> public virtual bool AddOption(string text, bool interactable, Block targetBlock) { bool addedOption = false; for (int i = 0; i < cachedButtons.Length; i++) { var button = cachedButtons[i]; if (!button.gameObject.activeSelf) { button.gameObject.SetActive(true); button.interactable = interactable; if (interactable && autoSelectFirstButton && !cachedButtons.Select(x => x.gameObject).Contains(EventSystem.current.currentSelectedGameObject)) { EventSystem.current.SetSelectedGameObject(button.gameObject); } Text textComponent = button.GetComponentInChildren<Text>(); if (textComponent != null) { textComponent.text = text; } var block = targetBlock; button.onClick.AddListener(delegate { EventSystem.current.SetSelectedGameObject(null); StopAllCoroutines(); // Stop timeout Clear(); HideSayDialog(); if (block != null) { var flowchart = block.GetFlowchart(); #if UNITY_EDITOR // Select the new target block in the Flowchart window flowchart.SelectedBlock = block; #endif gameObject.SetActive(false); // Use a coroutine to call the block on the next frame // Have to use the Flowchart gameobject as the MenuDialog is now inactive flowchart.StartCoroutine(CallBlock(block)); } }); addedOption = true; break; } } return addedOption; } /// <summary> /// Adds the option to the list of displayed options, calls a Lua function when selected. /// Will cause the Menu dialog to become visible if it is not already visible. /// </summary> /// <returns><c>true</c>, if the option was added successfully.</returns> public virtual bool AddOption(string text, bool interactable, LuaEnvironment luaEnv, Closure callBack) { if (!gameObject.activeSelf) { gameObject.SetActive(true); } bool addedOption = false; for (int i = 0; i < CachedButtons.Length; i++) { var button = CachedButtons[i]; if (!button.gameObject.activeSelf) { button.gameObject.SetActive(true); button.interactable = interactable; var textComponent = button.GetComponentInChildren<Text>(); if (textComponent != null) { textComponent.text = text; } // Copy to local variables LuaEnvironment env = luaEnv; Closure call = callBack; button.onClick.AddListener(delegate { StopAllCoroutines(); // Stop timeout Clear(); HideSayDialog(); // Use a coroutine to call the callback on the next frame StartCoroutine(CallLuaClosure(env, call)); }); addedOption = true; break; } } return addedOption; } /// <summary> /// Show a timer during which the player can select an option. Calls a Block when the timer expires. /// </summary> /// <param name="duration">The duration during which the player can select an option.</param> /// <param name="targetBlock">Block to execute if the player does not select an option in time.</param> public virtual void ShowTimer(float duration, Block targetBlock) { if (cachedSlider != null) { cachedSlider.gameObject.SetActive(true); gameObject.SetActive(true); StopAllCoroutines(); StartCoroutine(WaitForTimeout(duration, targetBlock)); } } /// <summary> /// Show a timer during which the player can select an option. Calls a Lua function when the timer expires. /// </summary> public virtual IEnumerator ShowTimer(float duration, LuaEnvironment luaEnv, Closure callBack) { if (CachedSlider == null || duration <= 0f) { yield break; } CachedSlider.gameObject.SetActive(true); StopAllCoroutines(); float elapsedTime = 0; Slider timeoutSlider = GetComponentInChildren<Slider>(); while (elapsedTime < duration) { if (timeoutSlider != null) { float t = 1f - elapsedTime / duration; timeoutSlider.value = t; } elapsedTime += Time.deltaTime; yield return null; } Clear(); gameObject.SetActive(false); HideSayDialog(); if (callBack != null) { luaEnv.RunLuaFunction(callBack, true); } } /// <summary> /// Returns true if the Menu Dialog is currently displayed. /// </summary> public virtual bool IsActive() { return gameObject.activeInHierarchy; } /// <summary> /// Returns the number of currently displayed options. /// </summary> public virtual int DisplayedOptionsCount { get { int count = 0; for (int i = 0; i < cachedButtons.Length; i++) { var button = cachedButtons[i]; if (button.gameObject.activeSelf) { count++; } } return count; } } #endregion } }
using UnityEngine; using System.Collections; public class MixedIKManager : MonoBehaviour { public bool snapHips = false; public bool renderLines = true; private static int _MixedIKID_ = 1; public int _id_ = 0; public bool showGizmos = true; public Material LimbsMaterial; public float LimbWidth = 0.05f; public float LowerLimbWidth = 0.03f; public Color lineColor = new Color(.5f, .5f, .5f); public Transform mocapHeadset; public Transform mocapLeftWrist = null; public Transform mocapRightWrist = null; public Transform mocapLeftAnkle = null; public Transform mocapRightAnkle = null; private Transform _headJoint; private Transform _hipJoint; private Transform _leftHandJoint; private Transform _rightHandJoint; private Transform _leftFootJoint; private Transform _rightFootJoint; private Transform[] _spines = new Transform[3]; private Transform[] _shoulders = new Transform[2]; private Transform[] _elbows = new Transform[2]; private Transform[] _uplegs = new Transform[2]; private Vector3[] _knees = new Vector3[2]; private float _legDist; private float _armDist; public Vector3 headOffset; public Vector3 handOffset; public Vector3 footOffset; public Vector3 SpineOffset; private Vector3 _baseSpineOrigOffset; public float kneeScale = 0.1f; public float elbowScale = 0.1f; public float minimumMidOffset = 0.05f; public float maximumMidOffset = 0.5f; public Vector3 elbowDirection; public int lineDetail = 10; private int _numClicks = 0; private float _numClicksTimer = 0f; private float _numClicksTimeFrame = 2f; private Vector3 _offset; private Vector3 _originalScale; private float _origYOffset; private float _origXOffset; private Vector3 _headToHips; private Vector3 _hipsPosition = Vector3.zero; private Vector3 _nb; //private IK _ik; public float upperArmLength = 0.5f; public float lowerArmLength = 0.5f; public Vector3 hint = new Vector3(0, 0, 1); // // public Transform leftElbow; // public Transform rightElbow; private float _averageHeadHeight = 1; private float[] _headHeights; // Use this for initialization void Start () { this._id_ = _MixedIKID_++; Debug.Log("Starting UnityIK for Avatar ID#" + this._id_); //animator = this.GetComponent<Animator>(); this.FindSkeletalParts(); _offset = _headJoint.transform.position.y * Vector3.up; _headToHips = _headJoint.transform.position - _hipJoint.transform.position; _originalScale = this.transform.localScale; _origYOffset = _headJoint.transform.position.y; _baseSpineOrigOffset = _spines[0].position - _hipJoint.position; _legDist = Vector3.Distance(_uplegs[0].position, _leftFootJoint.position); _armDist = Vector3.Distance(_shoulders[0].position, _leftHandJoint.position); GameObject shoulderChild = new GameObject (); shoulderChild.transform.parent = _shoulders [0]; GameObject shoulderChild2 = new GameObject (); shoulderChild2.transform.parent = _shoulders [1]; //_ik = new IK(); Debug.Log("Start successful for Avatar ID#" + this._id_); } void FindSkeletalParts() { Transform[] children = this.GetComponentsInChildren<Transform>(); for (int i = 0; i < children.Length; i++) { switch (children[i].tag) { case "HEAD": _headJoint = children[i]; break; case "HIPS": _hipJoint = children[i]; break; case "LEFTHAND": _leftHandJoint = children[i]; break; case "RIGHTHAND": _rightHandJoint = children[i]; break; case "LEFTFOOT": _leftFootJoint = children[i]; break; case "RIGHTFOOT": _rightFootJoint = children[i]; break; case "SPINE": _spines[0] = children[i]; break; case "SPINE1": _spines[1] = children[i]; break; case "SPINE2": _spines[2] = children[i]; break; case "LEFTSHOULDER": _shoulders[0] = children[i]; break; case "RIGHTSHOULDER": _shoulders[1] = children[i]; break; case "LEFTUPLEG": _uplegs[0] = children[i]; break; case "RIGHTUPLEG": _uplegs[1] = children[i]; break; case "LEFTELBOW": _elbows[0] = children[i]; break; case "RIGHTELBOW": _elbows[1] = children[i]; break; } } } // Update is called once per frame void Update () { this.PositionBody(); this.BindAvatarToMocap(); this.CheckForResize(); this.SolveHipsAndIK(); this.SolveSpineAndOthers(); this.averageHeadHeight (); } void PositionBody() { //this.transform.position = mocapHeadset.position - _offset + (mocapHeadset.rotation * headOffset); float la = mocapLeftAnkle.rotation.eulerAngles.y; float ra = mocapRightAnkle.rotation.eulerAngles.y; float ny = ((Mathf.Abs(la - ra) > 180) ? (la + ra + 360) : (la + ra)) / 2f; ny = ny % 360; transform.rotation = Quaternion.Euler(0, ny, 0); //Debug.Log(ny); _nb = new Vector3((mocapLeftAnkle.position.x + mocapRightAnkle.position.x) / 2f, 0f, (mocapLeftAnkle.position.z + mocapRightAnkle.position.z) / 2f); this.transform.position = _nb; } void BindAvatarToMocap() { if (mocapHeadset) Bind(mocapHeadset, _headJoint, headOffset); if (mocapLeftWrist) Bind(mocapLeftWrist, _leftHandJoint, handOffset); if (mocapRightWrist) Bind(mocapRightWrist, _rightHandJoint, handOffset); if (mocapLeftAnkle) Bind(mocapLeftAnkle, _leftFootJoint, footOffset); if (mocapRightAnkle) Bind(mocapRightAnkle, _rightFootJoint, footOffset); } void Bind(Transform mocap, Transform bone, Vector3 offset) { if (bone.tag.Equals("LEFTHAND") || bone.tag.Equals("LEFTFOOT")) { offset.x *= -1; } bone.position = mocap.position + (mocap.rotation * offset); bone.rotation = mocap.rotation; } void CheckForResize() { if (Input.GetMouseButtonDown(0)) { _numClicks += 1; if (_numClicks == 1) { _numClicksTimer = Time.time; } } if (_numClicks >= 4) { this.ResizeAvatar(); _numClicks = 0; } if (Time.time > _numClicksTimer + _numClicksTimeFrame) { _numClicks = 0; } } public static void ResizeAvatarWithID(int id) { MixedIKManager[] managers = GameObject.FindObjectsOfType<MixedIKManager>(); for (int i = 0; i < managers.Length; i++) { if (managers[i]._id_ == id) { managers[i].ResizeAvatar(); } } } void ResizeAvatar() { Debug.Log("Resize Activated for Avatar ID#" + this._id_); Vector3 ny = _originalScale; float scale = (mocapHeadset.position.y / _origYOffset); ny *= scale; _baseSpineOrigOffset *= scale; SpineOffset *= scale; _offset = _headJoint.transform.position.y * Vector3.up; _headToHips = _headJoint.transform.position - _hipJoint.transform.position; this.transform.localScale = ny; } void SolveHipsAndIK() { _hipsPosition = SolveForHipsPosition(); _hipJoint.transform.position = _hipsPosition; _hipJoint.transform.up = (_headJoint.transform.position - _hipJoint.transform.position).normalized; } Vector3 SolveForHipsPosition() { Vector3 hit = Vector3.zero; if (SolveHipsIntersection(out hit) && snapHips) { return hit; } else { hit = _headJoint.transform.position - (_headJoint.transform.position - _nb).normalized * Vector3.Distance(_headToHips, Vector3.zero); Vector3 headxz = Vector3.Scale (_headJoint.transform.position, Vector3.right + Vector3.forward); Vector3 offsetxz = (headxz - _nb)* -0.5f; //Vector3 offsety = Vector3.up * Vector3.Magnitude(offsetxz) * (0.2f + Mathf.Abs (Vector3.Dot (offsetxz.normalized, _hipJoint.transform.forward.normalized)) * 1.0f); hit += offsetxz;// + offsety; //hit = Vector3.Lerp(_nb,_headJoint.transform.position,.5f); //hit = Vector3.Scale(hit,new Vector3(1,1,-.5f)); } return hit; } bool SolveHipsIntersection(out Vector3 hitPoint) { float d, q, t, l2, r2, m2; hitPoint = Vector3.zero; Vector3 s2r = _headJoint.transform.position - _nb; l2 = s2r.sqrMagnitude; d = Vector3.Dot(s2r, Vector3.up); r2 = Mathf.Pow(Vector3.Distance(_headToHips, Vector3.zero), 2f); if (d < 0.0f && l2 > r2) { return false; } m2 = (l2 - (d * d)); if (m2 > r2) { return false; } q = Mathf.Sqrt(r2 - m2); if (l2 > r2) { t = d - q; } else { t = d + q; } Vector3 v = Vector3.up * t; hitPoint = _nb + v; return true; } void SolveSpineAndOthers() { Vector3 dir = (_headJoint.position - _hipJoint.position).normalized; _hipJoint.up = dir; _spines[0].position = _hipJoint.position + _hipJoint.rotation * _baseSpineOrigOffset; _spines[1].position = _spines[0].position + _hipJoint.rotation * SpineOffset; _spines[2].position = _spines[1].position + _hipJoint.rotation * SpineOffset; //SPINES[1] POSITION? EXTRA BEND IN HIPS? float la = _leftFootJoint.rotation.eulerAngles.y; float ra = _rightFootJoint.rotation.eulerAngles.y; float ny = ((Mathf.Abs(la - ra) > 180) ? (la + ra + 360) : (la + ra)) / 2f; ny = ny % 360; _hipJoint.Rotate(ny * Vector3.up); Vector3 o = -0.05f * ((_headJoint.eulerAngles.x > 180f ? _headJoint.eulerAngles.x -360f : _headJoint.eulerAngles.x) / 30f) * this.transform.forward; _spines[1].position += o; _spines[2].position += o; _spines [2].rotation = _hipJoint.rotation; if (_rightFootJoint.position.y < 0.35) { if (_rightFootJoint.position.y < 0.15) _rightFootJoint.position = new Vector3(_rightFootJoint.position.x, 0.15f, _rightFootJoint.position.z); Vector3 fxz = Vector3.Scale (_rightFootJoint.transform.forward, Vector3.right + Vector3.forward).normalized; _rightFootJoint.transform.forward = Vector3.Lerp(fxz,_rightFootJoint.transform.forward,(_rightFootJoint.position.y-.15f)/0.2f); } if (_leftFootJoint.position.y < 0.35) { if (_leftFootJoint.position.y < 0.15) _leftFootJoint.position = new Vector3(_leftFootJoint.position.x, 0.15f, _leftFootJoint.position.z); Vector3 fxz = Vector3.Scale (_leftFootJoint.transform.forward, Vector3.right + Vector3.forward).normalized; _leftFootJoint.transform.forward = Vector3.Lerp(fxz,_leftFootJoint.transform.forward,(_leftFootJoint.position.y-.15f)/0.2f); } //SPINES[1] POSITION? EXTRA BEND IN HIPS? //float rx = _headJoint.eulerAngles.x; //_hipJoint.Rotate((rx < 180 ? rx : rx - 360) * Vector3.right * -0.5f); float d, nks; //ELBOWS AND KNEES //d = Vector3.Distance(_shoulders[0].position, _leftHandJoint.position); //nks = Mathf.Clamp((_armDist / d) * elbowScale, minimumMidOffset, maximumMidOffset); //_elbows[0] = ((_shoulders[0].position + _leftHandJoint.position) / 2f) + (nks * elbowDirection); //d = Vector3.Distance(_shoulders[1].position, _rightHandJoint.position); //nks = Mathf.Clamp((_armDist / d) * elbowScale, minimumMidOffset, maximumMidOffset); //_elbows[1] = ((_shoulders[1].position + _rightHandJoint.position) / 2f) + (nks * elbowDirection); d = Vector3.Distance(_uplegs[0].position,_leftFootJoint.position); nks = Mathf.Clamp((_legDist / d) * kneeScale, minimumMidOffset, maximumMidOffset); _knees[0] = ((_uplegs[0].position + _leftFootJoint.position) / 2f) + (nks * _leftFootJoint.forward); d = Vector3.Distance(_uplegs[1].position, _rightFootJoint.position); nks = Mathf.Clamp((_legDist / d) * kneeScale, minimumMidOffset, maximumMidOffset); _knees[1] = ((_uplegs[1].position + _rightFootJoint.position) / 2f) + (nks * _rightFootJoint.forward); //Lines! RebuildLine(_uplegs[0].gameObject, new Vector3[] { _uplegs[0].position, _knees[0], mocapLeftAnkle.position }, mocapLeftAnkle.gameObject); RebuildLine(_uplegs[1].gameObject, new Vector3[] { _uplegs[1].position, _knees[1], mocapRightAnkle.position }, mocapRightAnkle.gameObject); //Spine! //RebuildLine(_spines[0].gameObject, new Vector3[] { /*_spines[0].position, _spines[1].position, _spines[2].position,*/ _headJoint.position }, mocapHeadset.gameObject); IKArm(_shoulders[0], _elbows[0], _leftHandJoint, upperArmLength*_averageHeadHeight, lowerArmLength*_averageHeadHeight,false); IKArm(_shoulders[1], _elbows[1], _rightHandJoint, upperArmLength*_averageHeadHeight, lowerArmLength*_averageHeadHeight,true); RebuildLine(_shoulders[0].gameObject, new Vector3[] { _shoulders[0].position, _elbows[0].position, mocapLeftWrist.position }, mocapLeftWrist.gameObject); RebuildLine(_shoulders[1].gameObject, new Vector3[] { _shoulders[1].position, _elbows[1].position, mocapRightWrist.position }, mocapRightWrist.gameObject); } void RebuildLine(GameObject g, Vector3[] points, GameObject e) { if (!renderLines) return; LineRenderer r = g.GetComponent<LineRenderer>(); if (!r) { r = g.AddComponent<LineRenderer>(); r.SetWidth(LimbWidth, LowerLimbWidth); r.material = LimbsMaterial; r.material.color = lineColor; } Vector3[] interpPoints = getPoints (points); int q = 0; for (int i = 0; i < interpPoints.Length; i++) { r.SetVertexCount(i + 1); r.SetPosition(i, interpPoints[i]); q = i; } // // int q = 0; // for (int i = 0; i < points.Length; i++) // { // r.SetVertexCount(i + 1); // r.SetPosition(i, points[i]); // q = i; // } // r.SetVertexCount(q + 1); r.SetPosition(q, e.transform.position); } Vector3 interp(Vector3[] P, float t){ return Vector3.Lerp (Vector3.Lerp (P [0], P [1], t), Vector3.Lerp (P [1], P [2], t), t); } Vector3[] getPoints(Vector3[] points){ Vector3[] returnPoints = new Vector3[lineDetail]; for (int i = 0; i < lineDetail; i++) { if(points.Length<=3) returnPoints[i] = interp(points,(float)i/(lineDetail-1)); else returnPoints[i] = interp(points,(float)i/(lineDetail-1)); } return returnPoints; } Vector3 C, D; float cc, x, y; /* void IKArm(Transform startJoint, Transform midJoint, Transform endJoint, float a, float b, bool rightArm) { C = endJoint.position - startJoint.position; D = findHint(C); if (!rightArm) { D = new Vector3(D.x, D.y, D.z * -1f); } //smoothing float t = Mathf.Sqrt(Vector3.Dot(C,C)) / (a + b) - .2f; t = Mathf.Max(0, Mathf.Min(1, t * t * (3 - t - t))); t = .9f + .2f * Mathf.Sqrt(t); a *= t; b *= t; //smoothing cc = Vector3.Dot(C, C); x = (1 + (a * a - b * b) / cc) / 2; y = Vector3.Dot(C, D) / cc; D -= y * C; y = Mathf.Sqrt(Mathf.Max(0, a * a - cc * x * x) / Vector3.Dot(D, D)); D = x * C + y * D; midJoint.position = D + startJoint.position; } */ void IKArm(Transform startJoint, Transform midJoint, Transform endJoint, float a, float b, bool rightArm) { GameObject tempEnd = startJoint.GetChild (1).gameObject; tempEnd.transform.position = endJoint.transform.position; C = tempEnd.transform.localPosition;//endJoint.position - startJoint.position; D = findHint(C,true); if (rightArm) { D = findHint(C,false); // D = new Vector3(D.x, D.y, D.z * -1f); } //smoothing float t = Mathf.Sqrt(Vector3.Dot(C,C)) / (a + b) - .2f; t = Mathf.Max(0, Mathf.Min(1, t * t * (3 - t - t))); t = .9f + .2f * Mathf.Sqrt(t); a *= t; b *= t; //smoothing cc = Vector3.Dot(C, C); x = (1 + (a * a - b * b) / cc) / 2; y = Vector3.Dot(C, D) / cc; D -= y * C; y = Mathf.Sqrt(Mathf.Max(0, a * a - cc * x * x) / Vector3.Dot(D, D)); D = x * C + y * D; midJoint.localPosition = D;// + startJoint.position; } public Vector3 findHint(Vector3 endEffectorPosition,bool right) { float r = Mathf.Sqrt(0.5f); Vector3 c = endEffectorPosition; float[] C = { c.x, c.y, c.z }; float[, ,] map = new float[,,]{ {{ 1, 0, 0 } , { 0, -r, -r }}, {{ -1, 0, 0 } , { 0, 0, 1 }}, {{ 0, 1, 0 } , { 1, 0, 0 }}, {{ 0, -1, 0 } , { r, 0, -r }}, {{ 0, 0, 1 } , { r, -r, 0 }}, {{ r, 0, r } , { r, 0, -r }}, {{ -r, 0, r } , { r, 0, r }}, }; if(right){ map = new float[,,]{ {{ -1, 0, 0 } , { 0, -r, -r }}, {{ 1, 0, 0 } , { 0, 0, 1 }}, {{ 0, 1, 0 } , { -1, 0, 0 }}, {{ 0, -1, 0 } , { -r, 0, -r }}, {{ 0, 0, 1 } , { -r, -r, 0 }}, {{ -r, 0, r } , { -r, 0, -r }}, {{ r, 0, r } , { -r, 0, r }}, }; } float[] D = { 0, 0, 0 }; for (int n = 0; n < 7; n++) { float[] thisMap = { map[n, 0, 0], map[n, 0, 1], map[n, 0, 2] }; float d = dot(thisMap, C); if (d > 0) for (int j = 0; j < 3; j++) D[j] += d * map[n, 1, j]; } normalize(D); return new Vector3(D[0], D[1], D[2]); } float dot(float[] a, float[] b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } float[] normalize(float[] a) { float length = Mathf.Sqrt((a[0] * a[0]) + (a[1] * a[1]) + (a[2] * a[2])); float[] r = { a[0] / length, a[1] / length, a[2] / length }; return (r); } void OnDrawGizmos() { if (showGizmos) { Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(_nb, 0.05f); //Gizmos.DrawWireSphere(_elbows[0].position, 0.05f); //Gizmos.DrawWireSphere(_elbows[1].position, 0.05f); Gizmos.DrawWireSphere(_knees[0], 0.05f); Gizmos.DrawWireSphere(_knees[1], 0.05f); } } void averageHeadHeight(){ if (_headHeights == null) { _headHeights = new float[1000]; for (int i = 0; i < _headHeights.Length-1; i++) { _headHeights[i] = _headJoint.transform.position.y; } } for (int i = 0; i < _headHeights.Length-1; i++) { _headHeights[i] = _headHeights[i+1]; } _headHeights [_headHeights.Length - 1] = _headJoint.transform.position.y; _averageHeadHeight = 0; for (int i = 0; i < _headHeights.Length; i++) { _averageHeadHeight += _headHeights[i]; } _averageHeadHeight /= _headHeights.Length; } Vector3 interpb3(Vector3[] points, float t){ Vector3 vector = new Vector3(); vector.x = b3( t, points[0].x, points[1].x, points[2].x, points[3].x ); vector.y = b3( t, points[0].y, points[1].y, points[2].y, points[3].y ); vector.z = b3( t, points[0].z, points[1].z, points[2].z, points[3].z ); return vector; } // Cubic Bezier Functions float b3p0 ( float t, float p ) { float k = 1 - t; return k * k * k * p; } float b3p1 ( float t, float p ) { float k = 1 - t; return 3 * k * k * t * p; } float b3p2 ( float t,float p ) { float k = 1 - t; return 3 * k * t * t * p; } float b3p3 ( float t, float p ) { return t * t * t * p; } float b3 ( float t, float p0, float p1, float p2, float p3 ) { return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 ); } }
// // GtkGladeCodeGenerator.cs // // Authors: // Eric Butler <[email protected]> // See AUTHORS for a full list of contributors. // // (C) 2005, Eric Butler <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.IO; using System.Collections; using GladeCodeGenerator; using System.Reflection; public class GtkGladeCodeGenerator { public static void Main() { /*foreach (AssemblyName name in Assembly.GetExecutingAssembly().GetReferencedAssemblies()) { AppDomain.CurrentDomain.Load(name); Console.WriteLine("Loading: " + name.FullName); }*/ new GtkGladeCodeGenerator(); } Gtk.Window window; [Glade.Widget] Gtk.EventBox mainEventBox; [Glade.Widget] Gtk.Entry inputFileEntry; [Glade.Widget] Gtk.Entry outputDirectoryEntry; [Glade.Widget] Gtk.TreeView widgetTree; [Glade.Widget] Gtk.ComboBox languageComboBox; [Glade.Widget] Gtk.Label statusLabel; [Glade.Widget] Gtk.ProgressBar progressBar; Generator codegen; Gtk.TreeStore widgetTreeStore; public GtkGladeCodeGenerator() { Gtk.Application.Init(); Glade.XML glade = new Glade.XML(null, "gladecodegenerator.glade", "MainWindow", null); glade.Autoconnect(this); window = (Gtk.Window)glade.GetWidget("MainWindow"); //mainEventBox.ModifyBg(Gtk.StateType.Normal, new Gdk.Color(0xff,0xff,0xff)); mainEventBox.ModifyBg(Gtk.StateType.Normal, mainEventBox.Style.White); widgetTreeStore = new Gtk.TreeStore(typeof(Gdk.Pixbuf), typeof(string), typeof(bool), typeof(Widget)); Gtk.TreeViewColumn completeColumn = new Gtk.TreeViewColumn(); Gtk.CellRendererToggle toggleRenderer = new Gtk.CellRendererToggle(); toggleRenderer.Toggled += new Gtk.ToggledHandler (on_toggleRenderer_Toggled); completeColumn.PackStart(toggleRenderer, false); completeColumn.SetCellDataFunc(toggleRenderer, new Gtk.TreeCellDataFunc(toggleRendererFunc)); Gtk.CellRendererPixbuf imageRenderer = new Gtk.CellRendererPixbuf(); completeColumn.PackStart(imageRenderer, false); completeColumn.AddAttribute(imageRenderer, "pixbuf", 0); completeColumn.AddAttribute(imageRenderer, "visible", 2); Gtk.CellRendererText textRenderer = new Gtk.CellRendererText(); completeColumn.PackStart(textRenderer, false); completeColumn.AddAttribute(textRenderer, "text", 1); widgetTree.AppendColumn(completeColumn); widgetTree.Model = widgetTreeStore; widgetTreeStore.SetSortColumnId(2,Gtk.SortType.Ascending); languageComboBox.Active = 0; window.Show(); Gtk.Application.Run(); } private void toggleRendererFunc (Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel tree_model, Gtk.TreeIter iter) { Gtk.CellRendererToggle toggle = (cell as Gtk.CellRendererToggle); Widget currentWidget = (tree_model.GetValue(iter, 3) as Widget); if (currentWidget == null) { toggle.Visible = false; } else { toggle.Active = currentWidget.GenerateCode; toggle.Visible = true; } } private void on_toggleRenderer_Toggled(object o, Gtk.ToggledArgs args) { Gtk.TreeIter iter; if (widgetTreeStore.GetIterFromString (out iter, args.Path)) { //bool val = (bool) widgetTreeStore.GetValue (iter, 0); //widgetTreeStore.SetValue (iter, 0, !val); Widget widget = (widgetTreeStore.GetValue(iter, 3) as Widget); Gtk.TreeIter parent; if (widgetTreeStore.IterParent (out parent, iter) == false) { if (!widget.GenerateCode == false) { widget.GenerateCode = false; Gtk.TreeIter childIter; while (widgetTreeStore.IterChildren(out childIter, iter) == true) { widgetTreeStore.Remove(ref childIter); } } else { currentWindowIter = iter; typeIters.Clear(); PopulateTreeWithWidgets( widget.Widgets ); widgetTree.ExpandRow(widgetTreeStore.GetPath(iter), false); widget.GenerateCode = true; } } else { /*if (!val == true) { (widgetTreeStore.GetValue(iter, 5) as Widget).GenerateCode = true; } else { (widgetTreeStore.GetValue(iter, 5) as Widget).GenerateCode = false; }*/ widget.GenerateCode = !widget.GenerateCode; } } int count = codegen.CountSelectedWidgets(); if (count == 1) statusLabel.Text = "There is 1 widget selected."; else if (count == 0) statusLabel.Text = "There are no widgets selected."; else statusLabel.Text = "There are " + count + " total widgets selected."; } private void on_browseInputFile_clicked(object o, EventArgs e) { FileSelector fileSelector = new FileSelector("Select Glade XML File"); if (fileSelector.Run() == (int)Gtk.ResponseType.Ok) inputFileEntry.Text = fileSelector.Filename; fileSelector.Destroy(); } private void on_loadFileButton_clicked(object o, EventArgs e) { widgetTreeStore.Clear(); if (File.Exists(inputFileEntry.Text) == true) { statusLabel.Text = "There are no widgets selected."; codegen = new Generator(inputFileEntry.Text); codegen.BeginLoadFile(new AsyncCallback(FileLoaded)); progressBar.Visible = true; pulse = true; Gtk.Timeout.Add(60, new Gtk.Function(ProgressPulse)); } else { Gtk.MessageDialog dialog = new Gtk.MessageDialog(window, Gtk.DialogFlags.Modal, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, "The specified file does not exist."); dialog.Run(); dialog.Destroy(); } } bool pulse; private void FileLoaded(IAsyncResult result) { codegen.EndLoadFile(result); RunOnMainThread.Run(this, "DoFileLoaded", null); } private void DoFileLoaded() { pulse = false; progressBar.Visible = false; FileInfo fileInfo = new FileInfo(inputFileEntry.Text); if (outputDirectoryEntry.Text == "") { outputDirectoryEntry.Text = Path.Combine(Path.Combine(Environment.CurrentDirectory,"generated"), fileInfo.Name); } PopulateTreeWithWindows(codegen.Widgets); } private bool ProgressPulse() { progressBar.Pulse(); return pulse; } private Gtk.TreeIter currentWindowIter; private Hashtable typeIters = new Hashtable(); private void PopulateTreeWithWindows(WidgetCollection windows) { foreach (Widget widget in windows) { if (widget.Type == "GtkWindow" | widget.Type == "GtkMenu" | widget.Type == "GnomeApp" | widget.Type.EndsWith("Dialog")) { Gdk.Pixbuf image = GetImage(widget.Type); currentWindowIter = widgetTreeStore.AppendValues(image, widget.Name, true, widget); } } } private void PopulateTreeWithWidgets(WidgetCollection widgets) { foreach (Widget widget in widgets) { Gdk.Pixbuf image = GetImage(widget.Type); if (typeIters[widget.Type] == null) { string name = widget.Type; //.Substring(3); if (name.EndsWith("x")) name += "es"; else if (name.EndsWith("y")) name = name.Substring(0, name.Length -1) + "ies"; else name += "s"; Gtk.TreeIter newIter = widgetTreeStore.AppendValues(currentWindowIter, image, name, true, null); typeIters.Add(widget.Type, newIter); } Gtk.TreeIter parentIter = (Gtk.TreeIter)typeIters[widget.Type]; widgetTreeStore.AppendValues(parentIter, null, widget.Name, false, widget); PopulateTreeWithWidgets(widget.Widgets); } } //TODO: Fix this up: private Gdk.Pixbuf GetImage(string type) { string imageName = ""; if (type.StartsWith("Gnome")) { imageName = type.Substring(5).ToLower() + ".png"; } else if (type.StartsWith("Gtk")) { imageName = type.Substring(3).ToLower() + ".png"; } else if (type.StartsWith("Bonobo")) { imageName = type.Substring(6).ToLower() + ".png"; } else { throw new Exception("Unknown type: " + type); } if (imageName.IndexOf("dialog") > -1 | imageName.EndsWith("about.png")) imageName = "dialog.png"; else if (imageName.IndexOf("combo") > -1) imageName = "combo.png"; try { Gdk.Pixbuf image = new Gdk.Pixbuf(System.Reflection.Assembly.GetExecutingAssembly(), imageName); return image; } catch (Exception ex) { return new Gtk.IconTheme().LoadIcon(Gtk.Stock.MissingImage, 22, Gtk.IconLookupFlags.UseBuiltin); } } private void on_generateButton_clicked(object o, EventArgs e) { try { if (Directory.Exists(outputDirectoryEntry.Text) == false) { Gtk.MessageDialog dialog = new Gtk.MessageDialog(window, Gtk.DialogFlags.Modal, Gtk.MessageType.Question, Gtk.ButtonsType.YesNo, "The specified directory does not exist, would you like it to be created?"); if (dialog.Run() == (int)Gtk.ResponseType.Yes) { Directory.CreateDirectory(outputDirectoryEntry.Text); dialog.Destroy(); } else { dialog.Destroy(); return; } } DirectoryInfo dir = new DirectoryInfo(outputDirectoryEntry.Text); if (dir.GetFiles().Length > 0) { Gtk.MessageDialog dialog = new Gtk.MessageDialog(window, Gtk.DialogFlags.Modal, Gtk.MessageType.Question, Gtk.ButtonsType.YesNo, "The specified directory is not empty, any files with the same " + "names as your top-level widgets will be over-written. Do you want to continue?"); if (dialog.Run() != (int)Gtk.ResponseType.Yes) { dialog.Destroy(); return; } else { dialog.Destroy(); } } if (languageComboBox.Active == 0) codegen.GenerateCode(Language.CSharp, outputDirectoryEntry.Text); else if (languageComboBox.Active == 1) codegen.GenerateCode(Language.VisualBasic, outputDirectoryEntry.Text); else if (languageComboBox.Active == 2) codegen.GenerateCode(Language.Boo, outputDirectoryEntry.Text); else if (languageComboBox.Active == 3) codegen.GenerateCode(Language.Nemerle, outputDirectoryEntry.Text); else throw new Exception ("What is " + languageComboBox.Active + "??"); Gtk.MessageDialog msg = new Gtk.MessageDialog(window, Gtk.DialogFlags.Modal, Gtk.MessageType.Info, Gtk.ButtonsType.Ok, "Code generation completed!!"); msg.Show(); msg.Run(); msg.Destroy(); //TODO: This sucks! System.Diagnostics.Process.Start("gnome-open", outputDirectoryEntry.Text); } catch (Exception ex) { Console.WriteLine(ex); Gtk.MessageDialog errordialog = new Gtk.MessageDialog(window, Gtk.DialogFlags.Modal, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, ex.Message); errordialog.Run(); errordialog.Destroy(); } } private void on_MainWindow_delete_event (object o, Gtk.DeleteEventArgs e) { Gtk.Application.Quit(); } private void fileQuitMenuItemActivated (object o, EventArgs e) { Gtk.Application.Quit(); } private void helpAboutMenuItemActivated (object o, EventArgs e) { Glade.XML glade = new Glade.XML(null, "gladecodegenerator.glade", "AboutDialog", null); Gtk.Dialog dialog = (Gtk.Dialog)glade.GetWidget("AboutDialog"); dialog.Show(); dialog.Run(); dialog.Destroy(); } private void on_browseOutputFile_clicked (object o, EventArgs e) { FolderDialog folderDialog = new FolderDialog("Select folder to write code to"); if (folderDialog.Run() == (int)Gtk.ResponseType.Ok) { outputDirectoryEntry.Text = folderDialog.CurrentFolder; } folderDialog.Destroy(); } }
using System; using System.Diagnostics; namespace Lucene.Net.Codecs.Compressing { /* * 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 IndexOutput = Lucene.Net.Store.IndexOutput; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; /// <summary> /// Efficient index format for block-based <see cref="Codec"/>s. /// <para/> this writer generates a file which can be loaded into memory using /// memory-efficient data structures to quickly locate the block that contains /// any document. /// <para>In order to have a compact in-memory representation, for every block of /// 1024 chunks, this index computes the average number of bytes per /// chunk and for every chunk, only stores the difference between /// <list type="bullet"> /// <li>${chunk number} * ${average length of a chunk}</li> /// <li>and the actual start offset of the chunk</li> /// </list> /// </para> /// <para>Data is written as follows:</para> /// <list type="bullet"> /// <li>PackedIntsVersion, &lt;Block&gt;<sup>BlockCount</sup>, BlocksEndMarker</li> /// <li>PackedIntsVersion --&gt; <see cref="PackedInt32s.VERSION_CURRENT"/> as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </li> /// <li>BlocksEndMarker --&gt; <tt>0</tt> as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) , this marks the end of blocks since blocks are not allowed to start with <tt>0</tt></li> /// <li>Block --&gt; BlockChunks, &lt;DocBases&gt;, &lt;StartPointers&gt;</li> /// <li>BlockChunks --&gt; a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) which is the number of chunks encoded in the block</li> /// <li>DocBases --&gt; DocBase, AvgChunkDocs, BitsPerDocBaseDelta, DocBaseDeltas</li> /// <li>DocBase --&gt; first document ID of the block of chunks, as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </li> /// <li>AvgChunkDocs --&gt; average number of documents in a single chunk, as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) </li> /// <li>BitsPerDocBaseDelta --&gt; number of bits required to represent a delta from the average using <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">ZigZag encoding</a></li> /// <li>DocBaseDeltas --&gt; packed (<see cref="PackedInt32s"/>) array of BlockChunks elements of BitsPerDocBaseDelta bits each, representing the deltas from the average doc base using <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">ZigZag encoding</a>.</li> /// <li>StartPointers --&gt; StartPointerBase, AvgChunkSize, BitsPerStartPointerDelta, StartPointerDeltas</li> /// <li>StartPointerBase --&gt; the first start pointer of the block, as a VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </li> /// <li>AvgChunkSize --&gt; the average size of a chunk of compressed documents, as a VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </li> /// <li>BitsPerStartPointerDelta --&gt; number of bits required to represent a delta from the average using <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">ZigZag encoding</a></li> /// <li>StartPointerDeltas --&gt; packed (<see cref="PackedInt32s"/>) array of BlockChunks elements of BitsPerStartPointerDelta bits each, representing the deltas from the average start pointer using <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">ZigZag encoding</a></li> /// <li>Footer --&gt; CodecFooter (<see cref="CodecUtil.WriteFooter(IndexOutput)"/>) </li> /// </list> /// <para>Notes</para> /// <list type="bullet"> /// <li>For any block, the doc base of the n-th chunk can be restored with /// <c>DocBase + AvgChunkDocs * n + DocBaseDeltas[n]</c>.</li> /// <li>For any block, the start pointer of the n-th chunk can be restored with /// <c>StartPointerBase + AvgChunkSize * n + StartPointerDeltas[n]</c>.</li> /// <li>Once data is loaded into memory, you can lookup the start pointer of any /// document by performing two binary searches: a first one based on the values /// of DocBase in order to find the right block, and then inside the block based /// on DocBaseDeltas (by reconstructing the doc bases for every chunk).</li> /// </list> /// @lucene.internal /// </summary> public sealed class CompressingStoredFieldsIndexWriter : IDisposable { internal const int BLOCK_SIZE = 1024; // number of chunks to serialize at once internal static long MoveSignToLowOrderBit(long n) { return (n >> 63) ^ (n << 1); } internal readonly IndexOutput fieldsIndexOut; internal int totalDocs; internal int blockDocs; internal int blockChunks; internal long firstStartPointer; internal long maxStartPointer; internal readonly int[] docBaseDeltas; internal readonly long[] startPointerDeltas; internal CompressingStoredFieldsIndexWriter(IndexOutput indexOutput) { this.fieldsIndexOut = indexOutput; Reset(); totalDocs = 0; docBaseDeltas = new int[BLOCK_SIZE]; startPointerDeltas = new long[BLOCK_SIZE]; fieldsIndexOut.WriteVInt32(PackedInt32s.VERSION_CURRENT); } private void Reset() { blockChunks = 0; blockDocs = 0; firstStartPointer = -1; // means unset } private void WriteBlock() { Debug.Assert(blockChunks > 0); fieldsIndexOut.WriteVInt32(blockChunks); // The trick here is that we only store the difference from the average start // pointer or doc base, this helps save bits per value. // And in order to prevent a few chunks that would be far from the average to // raise the number of bits per value for all of them, we only encode blocks // of 1024 chunks at once // See LUCENE-4512 // doc bases int avgChunkDocs; if (blockChunks == 1) { avgChunkDocs = 0; } else { avgChunkDocs = (int)Math.Round((float)(blockDocs - docBaseDeltas[blockChunks - 1]) / (blockChunks - 1)); } fieldsIndexOut.WriteVInt32(totalDocs - blockDocs); // docBase fieldsIndexOut.WriteVInt32(avgChunkDocs); int docBase = 0; long maxDelta = 0; for (int i = 0; i < blockChunks; ++i) { int delta = docBase - avgChunkDocs * i; maxDelta |= MoveSignToLowOrderBit(delta); docBase += docBaseDeltas[i]; } int bitsPerDocBase = PackedInt32s.BitsRequired(maxDelta); fieldsIndexOut.WriteVInt32(bitsPerDocBase); PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(fieldsIndexOut, PackedInt32s.Format.PACKED, blockChunks, bitsPerDocBase, 1); docBase = 0; for (int i = 0; i < blockChunks; ++i) { long delta = docBase - avgChunkDocs * i; Debug.Assert(PackedInt32s.BitsRequired(MoveSignToLowOrderBit(delta)) <= writer.BitsPerValue); writer.Add(MoveSignToLowOrderBit(delta)); docBase += docBaseDeltas[i]; } writer.Finish(); // start pointers fieldsIndexOut.WriteVInt64(firstStartPointer); long avgChunkSize; if (blockChunks == 1) { avgChunkSize = 0; } else { avgChunkSize = (maxStartPointer - firstStartPointer) / (blockChunks - 1); } fieldsIndexOut.WriteVInt64(avgChunkSize); long startPointer = 0; maxDelta = 0; for (int i = 0; i < blockChunks; ++i) { startPointer += startPointerDeltas[i]; long delta = startPointer - avgChunkSize * i; maxDelta |= MoveSignToLowOrderBit(delta); } int bitsPerStartPointer = PackedInt32s.BitsRequired(maxDelta); fieldsIndexOut.WriteVInt32(bitsPerStartPointer); writer = PackedInt32s.GetWriterNoHeader(fieldsIndexOut, PackedInt32s.Format.PACKED, blockChunks, bitsPerStartPointer, 1); startPointer = 0; for (int i = 0; i < blockChunks; ++i) { startPointer += startPointerDeltas[i]; long delta = startPointer - avgChunkSize * i; Debug.Assert(PackedInt32s.BitsRequired(MoveSignToLowOrderBit(delta)) <= writer.BitsPerValue); writer.Add(MoveSignToLowOrderBit(delta)); } writer.Finish(); } internal void WriteIndex(int numDocs, long startPointer) { if (blockChunks == BLOCK_SIZE) { WriteBlock(); Reset(); } if (firstStartPointer == -1) { firstStartPointer = maxStartPointer = startPointer; } Debug.Assert(firstStartPointer > 0 && startPointer >= firstStartPointer); docBaseDeltas[blockChunks] = numDocs; startPointerDeltas[blockChunks] = startPointer - maxStartPointer; ++blockChunks; blockDocs += numDocs; totalDocs += numDocs; maxStartPointer = startPointer; } internal void Finish(int numDocs, long maxPointer) { if (numDocs != totalDocs) { throw new Exception("Expected " + numDocs + " docs, but got " + totalDocs); } if (blockChunks > 0) { WriteBlock(); } fieldsIndexOut.WriteVInt32(0); // end marker fieldsIndexOut.WriteVInt64(maxPointer); CodecUtil.WriteFooter(fieldsIndexOut); } public void Dispose() { fieldsIndexOut.Dispose(); } } }
using System; using System.Globalization; namespace ClosedXML.Excel { public enum XLScope { Workbook, Worksheet } public interface IXLRangeBase : IDisposable { IXLWorksheet Worksheet { get; } /// <summary> /// Gets an object with the boundaries of this range. /// </summary> IXLRangeAddress RangeAddress { get; } /// <summary> /// Sets a value to every cell in this range. /// <para>If the object is an IEnumerable ClosedXML will copy the collection's data into a table starting from each cell.</para> /// <para>If the object is a range ClosedXML will copy the range starting from each cell.</para> /// <para>Setting the value to an object (not IEnumerable/range) will call the object's ToString() method.</para> /// <para>ClosedXML will try to translate it to the corresponding type, if it can't then the value will be left as a string.</para> /// </summary> /// <value> /// The object containing the value(s) to set. /// </value> Object Value { set; } /// <summary> /// Sets the type of the cells' data. /// <para>Changing the data type will cause ClosedXML to covert the current value to the new data type.</para> /// <para>An exception will be thrown if the current value cannot be converted to the new data type.</para> /// </summary> /// <value> /// The type of the cell's data. /// </value> /// <exception cref = "ArgumentException"></exception> XLCellValues DataType { set; } /// <summary> /// Sets the cells' formula with A1 references. /// </summary> /// <value>The formula with A1 references.</value> String FormulaA1 { set; } /// <summary> /// Sets the cells' formula with R1C1 references. /// </summary> /// <value>The formula with R1C1 references.</value> String FormulaR1C1 { set; } IXLStyle Style { get; set; } /// <summary> /// Gets or sets a value indicating whether this cell's text should be shared or not. /// </summary> /// <value> /// If false the cell's text will not be shared and stored as an inline value. /// </value> Boolean ShareString { set; } IXLHyperlinks Hyperlinks { get; } /// <summary> /// Returns the collection of cells. /// </summary> IXLCells Cells(); IXLCells Cells(Boolean usedCellsOnly); IXLCells Cells(Boolean usedCellsOnly, Boolean includeFormats); IXLCells Cells(String cells); IXLCells Cells(Func<IXLCell, Boolean> predicate); /// <summary> /// Returns the collection of cells that have a value. Formats are ignored. /// </summary> IXLCells CellsUsed(); /// <summary> /// Returns the collection of cells that have a value. /// </summary> /// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param> IXLCells CellsUsed(Boolean includeFormats); IXLCells CellsUsed(Func<IXLCell, Boolean> predicate); IXLCells CellsUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate); /// <summary> /// Searches the cells' contents for a given piece of text /// </summary> /// <param name="searchText">The search text.</param> /// <param name="compareOptions">The compare options.</param> /// <param name="searchFormulae">if set to <c>true</c> search formulae instead of cell values.</param> /// <returns></returns> IXLCells Search(String searchText, CompareOptions compareOptions = CompareOptions.Ordinal, Boolean searchFormulae = false); /// <summary> /// Returns the first cell of this range. /// </summary> IXLCell FirstCell(); /// <summary> /// Returns the first cell with a value of this range. Formats are ignored. /// <para>The cell's address is going to be ([First Row with a value], [First Column with a value])</para> /// </summary> IXLCell FirstCellUsed(); /// <summary> /// Returns the first cell with a value of this range. /// </summary> /// <para>The cell's address is going to be ([First Row with a value], [First Column with a value])</para> /// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param> IXLCell FirstCellUsed(Boolean includeFormats); IXLCell FirstCellUsed(Func<IXLCell, Boolean> predicate); IXLCell FirstCellUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate); /// <summary> /// Returns the last cell of this range. /// </summary> IXLCell LastCell(); /// <summary> /// Returns the last cell with a value of this range. Formats are ignored. /// <para>The cell's address is going to be ([Last Row with a value], [Last Column with a value])</para> /// </summary> IXLCell LastCellUsed(); /// <summary> /// Returns the last cell with a value of this range. /// </summary> /// <para>The cell's address is going to be ([Last Row with a value], [Last Column with a value])</para> /// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param> IXLCell LastCellUsed(Boolean includeFormats); IXLCell LastCellUsed(Func<IXLCell, Boolean> predicate); IXLCell LastCellUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate); /// <summary> /// Determines whether this range contains the specified range (completely). /// <para>For partial matches use the range.Intersects method.</para> /// </summary> /// <param name = "rangeAddress">The range address.</param> /// <returns> /// <c>true</c> if this range contains the specified range; otherwise, <c>false</c>. /// </returns> Boolean Contains(String rangeAddress); /// <summary> /// Determines whether this range contains the specified range (completely). /// <para>For partial matches use the range.Intersects method.</para> /// </summary> /// <param name = "range">The range to match.</param> /// <returns> /// <c>true</c> if this range contains the specified range; otherwise, <c>false</c>. /// </returns> Boolean Contains(IXLRangeBase range); Boolean Contains(IXLCell cell); /// <summary> /// Determines whether this range intersects the specified range. /// <para>For whole matches use the range.Contains method.</para> /// </summary> /// <param name = "rangeAddress">The range address.</param> /// <returns> /// <c>true</c> if this range intersects the specified range; otherwise, <c>false</c>. /// </returns> Boolean Intersects(String rangeAddress); /// <summary> /// Determines whether this range contains the specified range. /// <para>For whole matches use the range.Contains method.</para> /// </summary> /// <param name = "range">The range to match.</param> /// <returns> /// <c>true</c> if this range intersects the specified range; otherwise, <c>false</c>. /// </returns> Boolean Intersects(IXLRangeBase range); /// <summary> /// Unmerges this range. /// </summary> IXLRange Unmerge(); /// <summary> /// Merges this range. /// <para>The contents and style of the merged cells will be equal to the first cell.</para> /// </summary> IXLRange Merge(); IXLRange Merge(Boolean checkIntersect); /// <summary> /// Creates a named range out of this range. /// <para>If the named range exists, it will add this range to that named range.</para> /// <para>The default scope for the named range is Workbook.</para> /// </summary> /// <param name = "rangeName">Name of the range.</param> IXLRange AddToNamed(String rangeName); /// <summary> /// Creates a named range out of this range. /// <para>If the named range exists, it will add this range to that named range.</para> /// <param name = "rangeName">Name of the range.</param> /// <param name = "scope">The scope for the named range.</param> /// </summary> IXLRange AddToNamed(String rangeName, XLScope scope); /// <summary> /// Creates a named range out of this range. /// <para>If the named range exists, it will add this range to that named range.</para> /// <param name = "rangeName">Name of the range.</param> /// <param name = "scope">The scope for the named range.</param> /// <param name = "comment">The comments for the named range.</param> /// </summary> IXLRange AddToNamed(String rangeName, XLScope scope, String comment); /// <summary> /// Clears the contents of this range. /// </summary> /// <param name="clearOptions">Specify what you want to clear.</param> IXLRangeBase Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats); /// <summary> /// Deletes the cell comments from this range. /// </summary> void DeleteComments(); IXLRangeBase SetValue<T>(T value); /// <summary> /// Converts this object to a range. /// </summary> IXLRange AsRange(); Boolean IsMerged(); Boolean IsEmpty(); Boolean IsEmpty(Boolean includeFormats); Boolean IsEntireRow(); Boolean IsEntireColumn(); IXLPivotTable CreatePivotTable(IXLCell targetCell); IXLPivotTable CreatePivotTable(IXLCell targetCell, String name); //IXLChart CreateChart(Int32 firstRow, Int32 firstColumn, Int32 lastRow, Int32 lastColumn); IXLAutoFilter SetAutoFilter(); IXLDataValidation SetDataValidation(); IXLConditionalFormat AddConditionalFormat(); void Select(); } }
// Copyright (c) 2011-2013 Drew DeVault // // 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.Globalization; using System.Text; namespace MineAPI.Network.Crypto { class AsnParser { private List<byte> octets; private int initialCount; public AsnParser(byte[] values) { octets = new List<byte>(values.Length); octets.AddRange(values); initialCount = octets.Count; } internal int CurrentPosition() { return initialCount - octets.Count; } internal int RemainingBytes() { return octets.Count; } private int GetLength() { int length = 0; // Checkpoint int position = CurrentPosition(); try { byte b = GetNextOctet(); if (b == (b & 0x7f)) { return b; } int i = b & 0x7f; if (i > 4) { StringBuilder sb = new StringBuilder("Invalid Length Encoding. "); sb.AppendFormat("Length uses {0} octets", i.ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } while (0 != i--) { // shift left length <<= 8; length |= GetNextOctet(); } } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } return length; } internal byte[] Next() { int position = CurrentPosition(); try { /*byte b = */ GetNextOctet(); int length = GetLength(); if (length > RemainingBytes()) { StringBuilder sb = new StringBuilder("Incorrect Size. "); sb.AppendFormat("Specified: {0}, Remaining: {1}", length.ToString(CultureInfo.InvariantCulture), RemainingBytes().ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } return GetOctets(length); } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } } internal byte GetNextOctet() { int position = CurrentPosition(); if (0 == RemainingBytes()) { StringBuilder sb = new StringBuilder("Incorrect Size. "); sb.AppendFormat("Specified: {0}, Remaining: {1}", 1.ToString(CultureInfo.InvariantCulture), RemainingBytes().ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } byte b = GetOctets(1)[0]; return b; } internal byte[] GetOctets(int octetCount) { int position = CurrentPosition(); if (octetCount > RemainingBytes()) { StringBuilder sb = new StringBuilder("Incorrect Size. "); sb.AppendFormat("Specified: {0}, Remaining: {1}", octetCount.ToString(CultureInfo.InvariantCulture), RemainingBytes().ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } byte[] values = new byte[octetCount]; try { octets.CopyTo(0, values, 0, octetCount); octets.RemoveRange(0, octetCount); } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } return values; } internal bool IsNextNull() { return 0x05 == octets[0]; } internal int NextNull() { int position = CurrentPosition(); try { byte b = GetNextOctet(); if (0x05 != b) { StringBuilder sb = new StringBuilder("Expected Null. "); sb.AppendFormat("Specified Identifier: {0}", b.ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } // Next octet must be 0 b = GetNextOctet(); if (0x00 != b) { StringBuilder sb = new StringBuilder("Null has non-zero size. "); sb.AppendFormat("Size: {0}", b.ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } return 0; } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } } internal bool IsNextSequence() { return 0x30 == octets[0]; } internal int NextSequence() { int position = CurrentPosition(); try { byte b = GetNextOctet(); if (0x30 != b) { StringBuilder sb = new StringBuilder("Expected Sequence. "); sb.AppendFormat("Specified Identifier: {0}", b.ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } int length = GetLength(); if (length > RemainingBytes()) { StringBuilder sb = new StringBuilder("Incorrect Sequence Size. "); sb.AppendFormat("Specified: {0}, Remaining: {1}", length.ToString(CultureInfo.InvariantCulture), RemainingBytes().ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } return length; } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } } internal bool IsNextOctetString() { return 0x04 == octets[0]; } internal int NextOctetString() { int position = CurrentPosition(); try { byte b = GetNextOctet(); if (0x04 != b) { StringBuilder sb = new StringBuilder("Expected Octet String. "); sb.AppendFormat("Specified Identifier: {0}", b.ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } int length = GetLength(); if (length > RemainingBytes()) { StringBuilder sb = new StringBuilder("Incorrect Octet String Size. "); sb.AppendFormat("Specified: {0}, Remaining: {1}", length.ToString(CultureInfo.InvariantCulture), RemainingBytes().ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } return length; } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } } internal bool IsNextBitString() { return 0x03 == octets[0]; } internal int NextBitString() { int position = CurrentPosition(); try { byte b = GetNextOctet(); if (0x03 != b) { StringBuilder sb = new StringBuilder("Expected Bit String. "); sb.AppendFormat("Specified Identifier: {0}", b.ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } int length = GetLength(); // We need to consume unused bits, which is the first // octet of the remaing values b = octets[0]; octets.RemoveAt(0); length--; if (0x00 != b) { throw new BerDecodeException("The first octet of BitString must be 0", position); } return length; } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } } internal bool IsNextInteger() { return 0x02 == octets[0]; } internal byte[] NextInteger() { int position = CurrentPosition(); try { byte b = GetNextOctet(); if (0x02 != b) { StringBuilder sb = new StringBuilder("Expected Integer. "); sb.AppendFormat("Specified Identifier: {0}", b.ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } int length = GetLength(); if (length > RemainingBytes()) { StringBuilder sb = new StringBuilder("Incorrect Integer Size. "); sb.AppendFormat("Specified: {0}, Remaining: {1}", length.ToString(CultureInfo.InvariantCulture), RemainingBytes().ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } return GetOctets(length); } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } } internal byte[] NextOID() { int position = CurrentPosition(); try { byte b = GetNextOctet(); if (0x06 != b) { StringBuilder sb = new StringBuilder("Expected Object Identifier. "); sb.AppendFormat("Specified Identifier: {0}", b.ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } int length = GetLength(); if (length > RemainingBytes()) { StringBuilder sb = new StringBuilder("Incorrect Object Identifier Size. "); sb.AppendFormat("Specified: {0}, Remaining: {1}", length.ToString(CultureInfo.InvariantCulture), RemainingBytes().ToString(CultureInfo.InvariantCulture)); throw new BerDecodeException(sb.ToString(), position); } byte[] values = new byte[length]; for (int i = 0; i < length; i++) { values[i] = octets[0]; octets.RemoveAt(0); } return values; } catch (ArgumentOutOfRangeException ex) { throw new BerDecodeException("Error Parsing Key", position, ex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; [Serializable] public struct TypeWithoutNamespace { } namespace System.Runtime.Serialization.Formatters.Tests { [Serializable] public sealed class SealedObjectWithIntStringFields { public int Member1; public string Member2; public string Member3; public override bool Equals(object obj) { var o = obj as SealedObjectWithIntStringFields; if (o == null) return false; return EqualityComparer<int>.Default.Equals(Member1, o.Member1) && EqualityComparer<string>.Default.Equals(Member2, o.Member2) && EqualityComparer<string>.Default.Equals(Member3, o.Member3); } public override int GetHashCode() => 1; } [Serializable] public class ObjectWithIntStringUShortUIntULongAndCustomObjectFields { public int Member1; public string Member2; public string _member3; public SealedObjectWithIntStringFields Member4; public SealedObjectWithIntStringFields Member4shared; public SealedObjectWithIntStringFields Member5; public string Member6; public string str1; public string str2; public string str3; public string str4; public ushort u16; public uint u32; public ulong u64; public override bool Equals(object obj) { var o = obj as ObjectWithIntStringUShortUIntULongAndCustomObjectFields; if (o == null) return false; return EqualityComparer<int>.Default.Equals(Member1, o.Member1) && EqualityComparer<string>.Default.Equals(Member2, o.Member2) && EqualityComparer<string>.Default.Equals(_member3, o._member3) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member4, o.Member4) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member4shared, o.Member4shared) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member5, o.Member5) && EqualityComparer<string>.Default.Equals(Member6, o.Member6) && EqualityComparer<string>.Default.Equals(str1, o.str1) && EqualityComparer<string>.Default.Equals(str2, o.str2) && EqualityComparer<string>.Default.Equals(str3, o.str3) && EqualityComparer<string>.Default.Equals(str4, o.str4) && EqualityComparer<ushort>.Default.Equals(u16, o.u16) && EqualityComparer<uint>.Default.Equals(u16, o.u16) && EqualityComparer<ulong>.Default.Equals(u64, o.u64) && // make sure shared members are the same object ReferenceEquals(Member4, Member4shared) && ReferenceEquals(o.Member4, o.Member4shared); } public override int GetHashCode() => 1; } [Serializable] public class Point { public int X; public int Y; public Point(int x, int y) { X = x; Y = y; } public override bool Equals(object obj) { var o = obj as Point; if (o == null) return false; return X == o.X && Y == o.Y; } public override int GetHashCode() => 1; } [Serializable] public class Tree<T> { public Tree(T value, Tree<T> left, Tree<T> right) { Value = value; Left = left; Right = right; } public T Value { get; } public Tree<T> Left { get; } public Tree<T> Right { get; } public override bool Equals(object obj) { Tree<T> o = obj as Tree<T>; if (o == null) return false; return EqualityComparer<T>.Default.Equals(Value, o.Value) && EqualityComparer<Tree<T>>.Default.Equals(Left, o.Left) && EqualityComparer<Tree<T>>.Default.Equals(Right, o.Right) && // make sure the branches aren't actually the exact same object (Left == null || !ReferenceEquals(Left, o.Left)) && (Right == null || !ReferenceEquals(Right, o.Right)); } public override int GetHashCode() => 1; } [Serializable] public class Graph<T> { public T Value; public Graph<T>[] Links; public override bool Equals(object obj) { Graph<T> o = obj as Graph<T>; if (o == null) return false; var toExplore = new Stack<KeyValuePair<Graph<T>, Graph<T>>>(); toExplore.Push(new KeyValuePair<Graph<T>, Graph<T>>(this, o)); var seen1 = new HashSet<Graph<T>>(new ObjectReferenceEqualityComparer()); while (toExplore.Count > 0) { var cur = toExplore.Pop(); if (!seen1.Add(cur.Key)) { continue; } if (!EqualityComparer<T>.Default.Equals(cur.Key.Value, cur.Value.Value)) { return false; } if (Links == null || o.Links == null) { if (Links != o.Links) return false; continue; } if (Links.Length != o.Links.Length) { return false; } for (int i = 0; i < Links.Length; i++) { toExplore.Push(new KeyValuePair<Graph<T>, Graph<T>>(Links[i], o.Links[i])); } } return true; } public override int GetHashCode() => 1; } [Serializable] internal sealed class ObjectWithArrays { public int[] IntArray; public string[] StringArray; public Tree<int>[] TreeArray; public byte[] ByteArray; public int[][] JaggedArray; public int[,] MultiDimensionalArray; public override bool Equals(object obj) { ObjectWithArrays o = obj as ObjectWithArrays; if (o == null) return false; return EqualityHelpers.ArraysAreEqual(IntArray, o.IntArray) && EqualityHelpers.ArraysAreEqual(StringArray, o.StringArray) && EqualityHelpers.ArraysAreEqual(TreeArray, o.TreeArray) && EqualityHelpers.ArraysAreEqual(ByteArray, o.ByteArray) && EqualityHelpers.ArraysAreEqual(JaggedArray, o.JaggedArray) && EqualityHelpers.ArraysAreEqual(MultiDimensionalArray, o.MultiDimensionalArray); } public override int GetHashCode() => 1; } [Serializable] public enum Colors { Red, Orange, Yellow, Green, Blue, Purple } public struct NonSerializableStruct { public int Value; } public class NonSerializableClass { public int Value; } [Serializable] public class SerializableClassWithBadField { public NonSerializableClass Value; } [Serializable] public struct EmptyStruct { } [Serializable] public struct StructWithIntField { public int X; } [Serializable] public struct StructWithStringFields { public string String1; public string String2; } [Serializable] public struct StructContainingOtherStructs { public StructWithStringFields Nested1; public StructWithStringFields Nested2; } [Serializable] public struct StructContainingArraysOfOtherStructs { public StructContainingOtherStructs[] Nested; public override bool Equals(object obj) { if (!(obj is StructContainingArraysOfOtherStructs)) return false; return EqualityHelpers.ArraysAreEqual(Nested, ((StructContainingArraysOfOtherStructs)obj).Nested); } public override int GetHashCode() => 1; } [Serializable] public class BasicISerializableObject : ISerializable { private NonSerializablePair<int, string> _data; public BasicISerializableObject(int value1, string value2) { _data = new NonSerializablePair<int, string> { Value1 = value1, Value2 = value2 }; } public BasicISerializableObject(SerializationInfo info, StreamingContext context) { _data = new NonSerializablePair<int, string> { Value1 = info.GetInt32("Value1"), Value2 = info.GetString("Value2") }; } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Value1", _data.Value1); info.AddValue("Value2", _data.Value2); } public override bool Equals(object obj) { var o = obj as BasicISerializableObject; if (o == null) return false; if (_data == null || o._data == null) return _data == o._data; return _data.Value1 == o._data.Value1 && _data.Value2 == o._data.Value2; } public override int GetHashCode() => 1; } [Serializable] public sealed class DerivedISerializableWithNonPublicDeserializationCtor : BasicISerializableObject { public DerivedISerializableWithNonPublicDeserializationCtor(int value1, string value2) : base(value1, value2) { } private DerivedISerializableWithNonPublicDeserializationCtor(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class IncrementCountsDuringRoundtrip { public int IncrementedDuringOnSerializingMethod; public int IncrementedDuringOnSerializedMethod; [NonSerialized] public int IncrementedDuringOnDeserializingMethod; public int IncrementedDuringOnDeserializedMethod; public IncrementCountsDuringRoundtrip(string ignored) { } // non-default ctor so that we can observe changes from OnDeserializing [OnSerializing] private void OnSerializingMethod(StreamingContext context) => IncrementedDuringOnSerializingMethod++; [OnSerialized] private void OnSerializedMethod(StreamingContext context) => IncrementedDuringOnSerializedMethod++; [OnDeserializing] private void OnDeserializingMethod(StreamingContext context) => IncrementedDuringOnDeserializingMethod++; [OnDeserialized] private void OnDeserializedMethod(StreamingContext context) => IncrementedDuringOnDeserializedMethod++; } [Serializable] public sealed class DerivedIncrementCountsDuringRoundtrip : IncrementCountsDuringRoundtrip { internal int DerivedIncrementedDuringOnSerializingMethod; internal int DerivedIncrementedDuringOnSerializedMethod; [NonSerialized] internal int DerivedIncrementedDuringOnDeserializingMethod; internal int DerivedIncrementedDuringOnDeserializedMethod; public DerivedIncrementCountsDuringRoundtrip(string ignored) : base(ignored) { } [OnSerializing] private void OnSerializingMethod(StreamingContext context) => DerivedIncrementedDuringOnSerializingMethod++; [OnSerialized] private void OnSerializedMethod(StreamingContext context) => DerivedIncrementedDuringOnSerializedMethod++; [OnDeserializing] private void OnDeserializingMethod(StreamingContext context) => DerivedIncrementedDuringOnDeserializingMethod++; [OnDeserialized] private void OnDeserializedMethod(StreamingContext context) => DerivedIncrementedDuringOnDeserializedMethod++; } [Serializable] public sealed class ObjRefReturnsObj : IObjectReference { public object Real; public object GetRealObject(StreamingContext context) => Real; } internal sealed class NonSerializablePair<T1, T2> { public T1 Value1; public T2 Value2; } internal sealed class NonSerializablePairSurrogate : ISerializationSurrogate { public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) { var pair = (NonSerializablePair<int,string>)obj; info.AddValue("Value1", pair.Value1); info.AddValue("Value2", pair.Value2); } public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { var pair = (NonSerializablePair<int, string>)obj; pair.Value1 = info.GetInt32("Value1"); pair.Value2 = info.GetString("Value2"); return pair; } } [Serializable] public class Version1ClassWithoutField { } [Serializable] public class Version2ClassWithoutOptionalField { public object Value; } [Serializable] public class Version2ClassWithOptionalField { [OptionalField(VersionAdded = 2)] public object Value; } [Serializable] public class ObjectWithStateAndMethod { public int State; public int GetState() => State; } internal sealed class ObjectReferenceEqualityComparer : IEqualityComparer<object> { public new bool Equals(object x, object y) => ReferenceEquals(x, y); public int GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj); } internal static class EqualityHelpers { public static bool ArraysAreEqual<T>(T[] array1, T[] array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { if (!EqualityComparer<T>.Default.Equals(array1[i], array2[i])) { return false; } } return true; } public static bool ArraysAreEqual(Array array1, Array array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; if (array1.Rank != array2.Rank) return false; for (int i = 0; i < array1.Rank; i++) { if (array1.GetLength(i) != array2.GetLength(i)) return false; } var e1 = array1.GetEnumerator(); var e2 = array2.GetEnumerator(); while (e1.MoveNext()) { e2.MoveNext(); if (!EqualityComparer<object>.Default.Equals(e1.Current, e2.Current)) { return false; } } return true; } public static bool ArraysAreEqual<T>(T[][] array1, T[][] array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { T[] sub1 = array1[i], sub2 = array2[i]; if (sub1 == null || sub2 == null && (sub1 != sub2)) return false; if (sub1.Length != sub2.Length) return false; for (int j = 0; j < sub1.Length; j++) { if (!EqualityComparer<T>.Default.Equals(sub1[j], sub2[j])) { return false; } } } return true; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ApplicationGatewaysOperations operations. /// </summary> public partial interface IApplicationGatewaysOperations { /// <summary> /// The delete ApplicationGateway operation deletes the specified /// application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The delete ApplicationGateway operation deletes the specified /// application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Get ApplicationGateway operation retrieves information about /// the specified application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ApplicationGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put ApplicationGateway operation creates/updates a /// ApplicationGateway /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the ApplicationGateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete ApplicationGateway /// operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ApplicationGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put ApplicationGateway operation creates/updates a /// ApplicationGateway /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the ApplicationGateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete ApplicationGateway /// operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ApplicationGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List ApplicationGateway operation retrieves all the /// application gateways in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List ApplicationGateway operation retrieves all the /// application gateways in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Start ApplicationGateway operation starts application gateway /// in the specified resource group through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Start ApplicationGateway operation starts application gateway /// in the specified resource group through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The STOP ApplicationGateway operation stops application gateway in /// the specified resource group through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The STOP ApplicationGateway operation stops application gateway in /// the specified resource group through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The BackendHealth operation gets the backend health of application /// gateway in the specified resource group through Network resource /// provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in /// backend health. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ApplicationGatewayBackendHealth>> BackendHealthWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The BackendHealth operation gets the backend health of application /// gateway in the specified resource group through Network resource /// provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in /// backend health. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ApplicationGatewayBackendHealth>> BeginBackendHealthWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List ApplicationGateway operation retrieves all the /// application gateways in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List ApplicationGateway operation retrieves all the /// application gateways in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
#region License /* * Copyright 2002-2010 the original author or 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 GemStone.GemFire.Cache; using Spring.Objects.Factory; namespace Spring.Data.GemFire { /// <summary> /// Create a Gemstone.Gemfire.Cache.RegionsAttribute using standard .NET setter properties. /// </summary> /// <author>Mark Pollack</author> public class RegionAttributesFactoryObject : IFactoryObject, IInitializingObject { //TODO add support for the BDB persistence manager //This class is sealed and also doesn't follow standard .NET property setter style. private readonly AttributesFactory attributesFactory = new AttributesFactory(); private RegionAttributes gemfireRegionAttributes; // Expiration private uint regionTimeToLive; private ExpirationAction regionTimeToLiveAction = ExpirationAction.Invalidate; private uint regionIdleTimeout; private ExpirationAction regionIdleTimeoutAction = ExpirationAction.Invalidate; private uint entryTimeToLive; private ExpirationAction entryTimeToLiveAction = ExpirationAction.Invalidate; private uint entryIdleTimeout; private ExpirationAction entryIdleTimeoutAction = ExpirationAction.Invalidate; // storage; private int? initialCapacity; private float? loadFactor; private int? concurrencyLevel; private DiskPolicyType diskPolicy = DiskPolicyType.None; // Distribution // For client caches the ScopeType should only be used when you want a local scope. // TODO check on using StypeType - related to use of CachingEnabled property in RegionAttributes. private bool? localScope; //Misc settings private bool? cachingEnabled; private bool? clientNotificationEnabled; private uint? lruEntriesLimit; private bool? cloningEnabled; /// <summary> /// Sets the caching enabled flag for this region. /// </summary> /// <value>The caching is enabled.</value> /// <remarks>If true, cache data for this region in this process. /// If set to false, then no data is stored in the local process, /// but events and distributions will still occur, and the region can still be used to put and remove, etc... /// The default if not set is 'true', 'false' is illegal for regions of ScopeType.Local scope. <see cref="LocalScope"/> /// </remarks> public bool? CachingEnabled { set { cachingEnabled = value; } } /// <summary> /// Sets the client notification to be enabled/disabled. /// </summary> /// <value>The client notification enabled.</value> /// <remarks> ///Ttrue if client notifications have to be enabled; false otherwise /// </remarks> public bool? ClientNotification { set { clientNotificationEnabled = value; } } /// <summary> /// Sets a limit on the number of entries that will be held in the cache. If a new entry is added while at the limit, the cache will evict the least recently used entry. /// </summary> /// <value>The limit of the number of entries before eviction starts. Defaults to 0, meaning no LRU actions will used.</value> public uint? LruEntriesLimit { set { lruEntriesLimit = value; } } /// <summary> /// Gets or sets the cloning enabled. /// </summary> /// <value>The cloning enabled.</value> public bool? CloningEnabled { set { cloningEnabled = value; } } #region Distribution /// <summary> /// Sets a value indicating whether the region should be local scope, creating a private /// data set in the memory area where this region residers, invisible to other client caches in the system. /// </summary> /// <value><c>true</c> if create a locally coped region; otherwise, <c>false</c>.</value> public bool LocalScope { set { localScope = value; } } #endregion #region Storage /// <summary> /// Sets the disk policy. Only used when a new region is created. /// </summary> /// <value>The region disk policy.</value> public DiskPolicyType DiskPolicy { set { diskPolicy = value; } } /// <summary> /// Sets the initial capacity of the map used for storing the entries. Default is 16 /// </summary> /// <value>The initial capacity.</value> public int InitialCapacity { set { initialCapacity = value; } } /// <summary> /// Sets the load factor of the map used for storing the entries. Default 0.75 /// </summary> /// <value>The load factor.</value> public float LoadFactor { set { loadFactor = value; } } /// <summary> /// Sets the allowed concurrency among updates to values in the region is guided by the concurrencyLevel, /// which is used as a hint for internal sizing. Default 16. /// </summary> /// <value>The concurrency level.</value> public int ConcurrencyLevel { set { concurrencyLevel = value; } } #endregion #region Expiration /// <summary> /// Sets the region time to live in seconds for the region as a whole /// </summary> /// <value>The region time to live.</value> public uint RegionTimeToLive { set { regionTimeToLive = value; } } /// <summary> /// Sets the region time to live expiration action. /// </summary> /// <value>The region time to live action.</value> public ExpirationAction RegionTimeToLiveAction { set { regionTimeToLiveAction = value; } } /// <summary> /// Sets the region idle timeout in seconds /// </summary> /// <value>The region idle timeout.</value> public uint RegionIdleTimeout { set { regionIdleTimeout = value; } } /// <summary> /// Sets the region idle timeout expiration action. /// </summary> /// <value>The region idle timeout action.</value> public ExpirationAction RegionIdleTimeoutAction { set { regionIdleTimeoutAction = value; } } /// <summary> /// Sets the entry time to live in seconds /// </summary> /// <value>The entry time to live.</value> public uint EntryTimeToLive { set { entryTimeToLive = value; } } /// <summary> /// Sets the entry time to live expiration action. /// </summary> /// <value>The entry time to live action.</value> public ExpirationAction EntryTimeToLiveAction { set { entryTimeToLiveAction = value; } } /// <summary> /// Sets the entry idle timeout in seconds /// </summary> /// <value>The entry idle timeout.</value> public uint EntryIdleTimeout { set { entryIdleTimeout = value; } } /// <summary> /// Sets the entry idle timeout expiration action. /// </summary> /// <value>The entry idle timeout action.</value> public ExpirationAction EntryIdleTimeoutAction { set { entryIdleTimeoutAction = value; } } #endregion public object GetObject() { return gemfireRegionAttributes; } public Type ObjectType { get { return typeof (RegionAttributes); } } public bool IsSingleton { get { return true; } } public void AfterPropertiesSet() { if (cachingEnabled != null) attributesFactory.SetCachingEnabled(cachingEnabled.Value); if (clientNotificationEnabled != null) attributesFactory.SetClientNotificationEnabled(clientNotificationEnabled.Value); if (lruEntriesLimit != null) attributesFactory.SetLruEntriesLimit(lruEntriesLimit.Value); if (cloningEnabled != null) attributesFactory.SetCloningEnabled(cloningEnabled.Value); SetStorageProperties(attributesFactory); SetExpirationProperties(attributesFactory); gemfireRegionAttributes = attributesFactory.CreateRegionAttributes(); } protected virtual void SetStorageProperties(AttributesFactory attrFactory) { attrFactory.SetDiskPolicy(diskPolicy); if (initialCapacity != null) { attrFactory.SetInitialCapacity(initialCapacity.Value); } if (loadFactor != null) { attrFactory.SetLoadFactor(loadFactor.Value); } if (concurrencyLevel != null) { attrFactory.SetConcurrencyLevel(concurrencyLevel.Value); } } protected virtual void SetExpirationProperties(AttributesFactory attrFactory) { attrFactory.SetRegionTimeToLive(regionTimeToLiveAction, regionTimeToLive); attrFactory.SetRegionIdleTimeout(regionIdleTimeoutAction, regionIdleTimeout); attrFactory.SetEntryTimeToLive(entryTimeToLiveAction, entryTimeToLive); attrFactory.SetEntryIdleTimeout(entryIdleTimeoutAction, entryIdleTimeout); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A user account for remote access to a compute node. /// </summary> public partial class ComputeNodeUser : ITransportObjectProvider<Models.ComputeNodeUser>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<DateTime> ExpiryTimeProperty; public readonly PropertyAccessor<bool?> IsAdminProperty; public readonly PropertyAccessor<string> NameProperty; public readonly PropertyAccessor<string> PasswordProperty; public readonly PropertyAccessor<string> SshPublicKeyProperty; public PropertyContainer() : base(BindingState.Unbound) { this.ExpiryTimeProperty = this.CreatePropertyAccessor<DateTime>(nameof(ExpiryTime), BindingAccess.Read | BindingAccess.Write); this.IsAdminProperty = this.CreatePropertyAccessor<bool?>(nameof(IsAdmin), BindingAccess.Read | BindingAccess.Write); this.NameProperty = this.CreatePropertyAccessor<string>(nameof(Name), BindingAccess.Read | BindingAccess.Write); this.PasswordProperty = this.CreatePropertyAccessor<string>(nameof(Password), BindingAccess.Read | BindingAccess.Write); this.SshPublicKeyProperty = this.CreatePropertyAccessor<string>(nameof(SshPublicKey), BindingAccess.Read | BindingAccess.Write); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; private readonly string parentPoolId; internal string ParentPoolId { get { return this.parentPoolId; } } private readonly string parentNodeId; internal string ParentNodeId { get { return this.parentNodeId; } } #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ComputeNodeUser"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> /// <param name='parentPoolId'>The parentPoolId.</param> /// <param name='parentNodeId'>The parentNodeId.</param> internal ComputeNodeUser( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors, string parentPoolId, string parentNodeId) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; this.parentPoolId = parentPoolId; this.parentNodeId = parentNodeId; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } /// <summary> /// Default constructor to support mocking the <see cref="ComputeNodeUser"/> class. /// </summary> protected ComputeNodeUser() { this.propertyContainer = new PropertyContainer(); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="ComputeNodeUser"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region ComputeNodeUser /// <summary> /// Gets or sets the expiry time. /// </summary> public DateTime ExpiryTime { get { return this.propertyContainer.ExpiryTimeProperty.Value; } set { this.propertyContainer.ExpiryTimeProperty.Value = value; } } /// <summary> /// Gets or sets the administrative privilege level of the user account. The value of this property is ignored when /// UpdateUser is specified for the commit operation. /// </summary> public bool? IsAdmin { get { return this.propertyContainer.IsAdminProperty.Value; } set { this.propertyContainer.IsAdminProperty.Value = value; } } /// <summary> /// Gets or sets the name. If AddUser is specified for the commit operation, the value of this property is the name /// of the local Windows account created. If UpdateUser is specified for the commit operation, the value of this /// property selects the local Windows account to modify. Changing this property does not rename the local Windows /// account on the compute node. /// </summary> public string Name { get { return this.propertyContainer.NameProperty.Value; } set { this.propertyContainer.NameProperty.Value = value; } } /// <summary> /// Gets or sets the password. /// </summary> public string Password { get { return this.propertyContainer.PasswordProperty.Value; } set { this.propertyContainer.PasswordProperty.Value = value; } } /// <summary> /// Gets or sets the SSH public key that can be used for remote login to the compute node. /// </summary> /// <remarks> /// <para>The public key should be compatible with Open SSH encoding and should be base 64 encoded. This property /// can be specified only for Linux nodes. The Batch service will return an error if this property is set for pools /// created with <see cref="Microsoft.Azure.Batch.CloudServiceConfiguration"/> or <see cref="Microsoft.Azure.Batch.VirtualMachineConfiguration"/> /// with Windows compute nodes.</para> /// </remarks> public string SshPublicKey { get { return this.propertyContainer.SshPublicKeyProperty.Value; } set { this.propertyContainer.SshPublicKeyProperty.Value = value; } } #endregion // ComputeNodeUser #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.ComputeNodeUser ITransportObjectProvider<Models.ComputeNodeUser>.GetTransportObject() { Models.ComputeNodeUser result = new Models.ComputeNodeUser() { ExpiryTime = this.ExpiryTime, IsAdmin = this.IsAdmin, Name = this.Name, Password = this.Password, SshPublicKey = this.SshPublicKey, }; return result; } #endregion // Internal/private methods } }
//regarding binding and vertex arrays: //http://stackoverflow.com/questions/8704801/glvertexattribpointer-clarification //http://stackoverflow.com/questions/9536973/oes-vertex-array-object-and-client-state //http://www.opengl.org/wiki/Vertex_Specification //etc //glBindAttribLocation (programID, 0, "vertexPosition_modelspace"); //for future reference: c# tesselators //http://www.opentk.com/node/437 (AGG#, codes on Tao forums) using System; using System.Reflection; using System.Threading; using System.IO; using System.Collections.Generic; using sd = System.Drawing; using sdi = System.Drawing.Imaging; using swf=System.Windows.Forms; using BizHawk.Bizware.BizwareGL; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using otkg = OpenTK.Graphics; namespace BizHawk.Bizware.BizwareGL.Drivers.OpenTK { /// <summary> /// OpenTK implementation of the BizwareGL.IGL interface. /// TODO - can we have more than one of these? could be dangerous. such dangerous things to be possibly reconsidered are marked with HAMNUTS /// TODO - if we have any way of making contexts, we also need a way of freeing it, and then we can cleanup our dictionaries /// </summary> public class IGL_TK : IGL { //rendering state Pipeline _CurrPipeline; RenderTarget _CurrRenderTarget; static IGL_TK() { //make sure OpenTK initializes without getting wrecked on the SDL check and throwing an exception to annoy our MDA's var toolkitOptions = global::OpenTK.ToolkitOptions.Default; toolkitOptions.Backend = PlatformBackend.PreferNative; global::OpenTK.Toolkit.Init(toolkitOptions); //NOTE: this throws EGL exceptions anyway. I'm going to ignore it and whine about it later } public string API { get { return "OPENGL"; } } public int Version { get { //doesnt work on older than gl3 maybe //int major, minor; ////other overloads may not exist... //GL.GetInteger(GetPName.MajorVersion, out major); //GL.GetInteger(GetPName.MinorVersion, out minor); //supposedly the standard dictates that whatever junk is in the version string, some kind of version is at the beginning string version_string = GL.GetString(StringName.Version); var version_parts = version_string.Split('.'); int major = int.Parse(version_parts[0]); //getting a minor version out is too hard and not needed now return major * 100; } } public IGL_TK(int major_version, int minor_version, bool forward_compatible) { //make an 'offscreen context' so we can at least do things without having to create a window OffscreenNativeWindow = new NativeWindow(); OffscreenNativeWindow.ClientSize = new sd.Size(8, 8); this.GraphicsContext = new GraphicsContext(GraphicsMode.Default, OffscreenNativeWindow.WindowInfo, major_version, minor_version, forward_compatible ? GraphicsContextFlags.ForwardCompatible : GraphicsContextFlags.Default); MakeDefaultCurrent(); //this is important for reasons unknown this.GraphicsContext.LoadAll(); //misc initialization CreateRenderStates(); PurgeStateCache(); } public void BeginScene() { //seems not to be needed... } public void EndScene() { //seems not to be needed... } void IDisposable.Dispose() { //TODO - a lot of analysis here OffscreenNativeWindow.Dispose(); OffscreenNativeWindow = null; GraphicsContext.Dispose(); GraphicsContext = null; } public void Clear(ClearBufferMask mask) { GL.Clear((global::OpenTK.Graphics.OpenGL.ClearBufferMask)mask); } public void SetClearColor(sd.Color color) { GL.ClearColor(color); } public IGraphicsControl Internal_CreateGraphicsControl() { var glc = new GLControlWrapper(this); glc.CreateControl(); //now the control's context will be current. annoying! fix it. MakeDefaultCurrent(); return glc; } public int GenTexture() { return GL.GenTexture(); } public void FreeTexture(Texture2d tex) { GL.DeleteTexture((int)tex.Opaque); } public Shader CreateFragmentShader(bool cg, string source, string entry, bool required) { return CreateShader(cg, ShaderType.FragmentShader, source, entry, required); } public Shader CreateVertexShader(bool cg, string source, string entry, bool required) { return CreateShader(cg, ShaderType.VertexShader, source, entry, required); } public IBlendState CreateBlendState(BlendingFactorSrc colorSource, BlendEquationMode colorEquation, BlendingFactorDest colorDest, BlendingFactorSrc alphaSource, BlendEquationMode alphaEquation, BlendingFactorDest alphaDest) { return new CacheBlendState(true, colorSource, colorEquation, colorDest, alphaSource, alphaEquation, alphaDest); } public void SetBlendState(IBlendState rsBlend) { var mybs = rsBlend as CacheBlendState; if (mybs.Enabled) { GL.Enable(EnableCap.Blend); GL.BlendEquationSeparate(mybs.colorEquation, mybs.alphaEquation); GL.BlendFuncSeparate(mybs.colorSource, mybs.colorDest, mybs.alphaSource, mybs.alphaDest); } else GL.Disable(EnableCap.Blend); if (rsBlend == _rsBlendNoneOpaque) { //make sure constant color is set correctly GL.BlendColor(new Color4(255, 255, 255, 255)); } } public IBlendState BlendNoneCopy { get { return _rsBlendNoneVerbatim; } } public IBlendState BlendNoneOpaque { get { return _rsBlendNoneOpaque; } } public IBlendState BlendNormal { get { return _rsBlendNormal; } } class ShaderWrapper { public int sid; public Dictionary<string, string> MapCodeToNative; public Dictionary<string, string> MapNativeToCode; } class PipelineWrapper { public int pid; public Shader FragmentShader, VertexShader; public List<int> SamplerLocs; } public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required, string memo) { //if the shaders arent available, the pipeline isn't either if (!vertexShader.Available || !fragmentShader.Available) { string errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}"; if (required) throw new InvalidOperationException($"Couldn't build required GL pipeline:\r\n{errors}"); var pipeline = new Pipeline(this, null, false, null, null, null); pipeline.Errors = errors; return pipeline; } bool success = true; var vsw = vertexShader.Opaque as ShaderWrapper; var fsw = fragmentShader.Opaque as ShaderWrapper; var sws = new[] { vsw,fsw }; bool mapVariables = vsw.MapCodeToNative != null || fsw.MapCodeToNative != null; ErrorCode errcode; int pid = GL.CreateProgram(); GL.AttachShader(pid, vsw.sid); errcode = GL.GetError(); GL.AttachShader(pid, fsw.sid); errcode = GL.GetError(); //NOT BEING USED NOW: USING SEMANTICS INSTEAD ////bind the attribute locations from the vertex layout ////as we go, look for attribute mappings (CGC will happily reorder and rename our attribute mappings) ////what's more it will _RESIZE_ them but this seems benign..somehow.. ////WELLLLLLL we wish we could do that by names ////but the shaders dont seem to be adequate quality (oddly named attributes.. texCoord vs texCoord1). need to use semantics instead. //foreach (var kvp in vertexLayout.Items) //{ // string name = kvp.Value.Name; // //if (mapVariables) // //{ // // foreach (var sw in sws) // // { // // if (sw.MapNativeToCode.ContainsKey(name)) // // { // // name = sw.MapNativeToCode[name]; // // break; // // } // // } // //} // if(mapVariables) { // ////proxy for came-from-cgc // //switch (kvp.Value.Usage) // //{ // // case AttributeUsage.Position: // //} // } // //GL.BindAttribLocation(pid, kvp.Key, name); //} GL.LinkProgram(pid); errcode = GL.GetError(); string resultLog = GL.GetProgramInfoLog(pid); if (errcode != ErrorCode.NoError) if (required) throw new InvalidOperationException($"Error creating pipeline (error returned from glLinkProgram): {errcode}\r\n\r\n{resultLog}"); else success = false; int linkStatus; GL.GetProgram(pid, GetProgramParameterName.LinkStatus, out linkStatus); if (linkStatus == 0) if (required) throw new InvalidOperationException($"Error creating pipeline (link status false returned from glLinkProgram): \r\n\r\n{resultLog}"); else success = false; //need to work on validation. apparently there are some weird caveats to glValidate which make it complicated and possibly excuses (barely) the intel drivers' dysfunctional operation //"A sampler points to a texture unit used by fixed function with an incompatible target" // //info: //http://www.opengl.org/sdk/docs/man/xhtml/glValidateProgram.xml //This function mimics the validation operation that OpenGL implementations must perform when rendering commands are issued while programmable shaders are part of current state. //glValidateProgram checks to see whether the executables contained in program can execute given the current OpenGL state //This function is typically useful only during application development. // //So, this is no big deal. we shouldnt be calling validate right now anyway. //conclusion: glValidate is very complicated and is of virtually no use unless your draw calls are returning errors and you want to know why //GL.ValidateProgram(pid); //errcode = GL.GetError(); //resultLog = GL.GetProgramInfoLog(pid); //if (errcode != ErrorCode.NoError) // throw new InvalidOperationException($"Error creating pipeline (error returned from glValidateProgram): {errcode}\r\n\r\n{resultLog}"); //int validateStatus; //GL.GetProgram(pid, GetProgramParameterName.ValidateStatus, out validateStatus); //if (validateStatus == 0) // throw new InvalidOperationException($"Error creating pipeline (validateStatus status false returned from glValidateProgram): \r\n\r\n{resultLog}"); //set the program to active, in case we need to set sampler uniforms on it GL.UseProgram(pid); //get all the attributes (not needed) List<AttributeInfo> attributes = new List<AttributeInfo>(); int nAttributes; GL.GetProgram(pid, GetProgramParameterName.ActiveAttributes, out nAttributes); for (int i = 0; i < nAttributes; i++) { int size, length; string name = new System.Text.StringBuilder(1024).ToString(); ActiveAttribType type; GL.GetActiveAttrib(pid, i, 1024, out length, out size, out type, out name); attributes.Add(new AttributeInfo() { Handle = new IntPtr(i), Name = name }); } //get all the uniforms List<UniformInfo> uniforms = new List<UniformInfo>(); int nUniforms; GL.GetProgram(pid,GetProgramParameterName.ActiveUniforms,out nUniforms); List<int> samplers = new List<int>(); for (int i = 0; i < nUniforms; i++) { int size, length; ActiveUniformType type; string name = new System.Text.StringBuilder(1024).ToString().ToString(); GL.GetActiveUniform(pid, i, 1024, out length, out size, out type, out name); errcode = GL.GetError(); int loc = GL.GetUniformLocation(pid, name); //translate name if appropriate //not sure how effective this approach will be, due to confusion of vertex and fragment uniforms if (mapVariables) { if (vsw.MapCodeToNative.ContainsKey(name)) name = vsw.MapCodeToNative[name]; if (fsw.MapCodeToNative.ContainsKey(name)) name = fsw.MapCodeToNative[name]; } var ui = new UniformInfo(); ui.Name = name; ui.Opaque = loc; if (type == ActiveUniformType.Sampler2D) { ui.IsSampler = true; ui.SamplerIndex = samplers.Count; ui.Opaque = loc | (samplers.Count << 24); samplers.Add(loc); } uniforms.Add(ui); } //deactivate the program, so we dont accidentally use it GL.UseProgram(0); if (!vertexShader.Available) success = false; if (!fragmentShader.Available) success = false; var pw = new PipelineWrapper() { pid = pid, VertexShader = vertexShader, FragmentShader = fragmentShader, SamplerLocs = samplers }; return new Pipeline(this, pw, success, vertexLayout, uniforms, memo); } public void FreePipeline(Pipeline pipeline) { var pw = pipeline.Opaque as PipelineWrapper; //unavailable pipelines will have no opaque if (pw == null) return; GL.DeleteProgram(pw.pid); pw.FragmentShader.Release(); pw.VertexShader.Release(); } public void Internal_FreeShader(Shader shader) { var sw = shader.Opaque as ShaderWrapper; GL.DeleteShader(sw.sid); } public void BindPipeline(Pipeline pipeline) { _CurrPipeline = pipeline; if (pipeline == null) { sStatePendingVertexLayout = null; GL.UseProgram(0); return; } if (!pipeline.Available) throw new InvalidOperationException("Attempt to bind unavailable pipeline"); sStatePendingVertexLayout = pipeline.VertexLayout; var pw = pipeline.Opaque as PipelineWrapper; GL.UseProgram(pw.pid); //this is dumb and confusing, but we have to bind physical sampler numbers to sampler variables. for (int i = 0; i < pw.SamplerLocs.Count; i++) { GL.Uniform1(pw.SamplerLocs[i], i); } } public VertexLayout CreateVertexLayout() { return new VertexLayout(this, null); } private void BindTexture2d(Texture2d tex) { GL.BindTexture(TextureTarget.Texture2D, (int)tex.Opaque); } public void SetTextureWrapMode(Texture2d tex, bool clamp) { BindTexture2d(tex); int mode; if (clamp) { mode = (int)global::OpenTK.Graphics.OpenGL.TextureWrapMode.ClampToEdge; } else mode = (int)global::OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat; GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, mode); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, mode); } public unsafe void BindArrayData(void* pData) { MyBindArrayData(sStatePendingVertexLayout, pData); } public void DrawArrays(PrimitiveType mode, int first, int count) { GL.DrawArrays((global::OpenTK.Graphics.OpenGL.PrimitiveType)mode, first, count); } public void SetPipelineUniform(PipelineUniform uniform, bool value) { GL.Uniform1((int)uniform.Sole.Opaque, value ? 1 : 0); } public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, Matrix4 mat, bool transpose) { //GL.UniformMatrix4((int)uniform.Opaque, 1, transpose, (float*)&mat); GL.Uniform4((int)uniform.Sole.Opaque + 0, 1, (float*)&mat.Row0); GL.Uniform4((int)uniform.Sole.Opaque + 1, 1, (float*)&mat.Row1); GL.Uniform4((int)uniform.Sole.Opaque + 2, 1, (float*)&mat.Row2); GL.Uniform4((int)uniform.Sole.Opaque + 3, 1, (float*)&mat.Row3); } public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, ref Matrix4 mat, bool transpose) { fixed(Matrix4* pMat = &mat) GL.UniformMatrix4((int)uniform.Sole.Opaque, 1, transpose, (float*)pMat); } public void SetPipelineUniform(PipelineUniform uniform, Vector4 value) { GL.Uniform4((int)uniform.Sole.Opaque, value.X, value.Y, value.Z, value.W); } public void SetPipelineUniform(PipelineUniform uniform, Vector2 value) { GL.Uniform2((int)uniform.Sole.Opaque, value.X, value.Y); } public void SetPipelineUniform(PipelineUniform uniform, float value) { if (uniform.Owner == null) return; //uniform was optimized out GL.Uniform1((int)uniform.Sole.Opaque, value); } public unsafe void SetPipelineUniform(PipelineUniform uniform, Vector4[] values) { fixed (Vector4* pValues = &values[0]) GL.Uniform4((int)uniform.Sole.Opaque, values.Length, (float*)pValues); } public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex) { int n = ((int)uniform.Sole.Opaque)>>24; //set the sampler index into the uniform first if (sActiveTexture != n) { sActiveTexture = n; var selectedUnit = (TextureUnit)((int)TextureUnit.Texture0 + n); GL.ActiveTexture(selectedUnit); } //now bind the texture GL.BindTexture(TextureTarget.Texture2D, (int)tex.Opaque); } public void TexParameter2d(Texture2d tex, TextureParameterName pname, int param) { BindTexture2d(tex); GL.TexParameter(TextureTarget.Texture2D, (global::OpenTK.Graphics.OpenGL.TextureParameterName)pname, param); } public Texture2d LoadTexture(sd.Bitmap bitmap) { using (var bmp = new BitmapBuffer(bitmap, new BitmapLoadOptions())) return (this as IGL).LoadTexture(bmp); } public Texture2d LoadTexture(Stream stream) { using(var bmp = new BitmapBuffer(stream,new BitmapLoadOptions())) return (this as IGL).LoadTexture(bmp); } public Texture2d CreateTexture(int width, int height) { int id = GenTexture(); return new Texture2d(this, id, width, height); } public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) { return new Texture2d(this as IGL, glTexId.ToInt32(), width, height); } public void LoadTextureData(Texture2d tex, BitmapBuffer bmp) { sdi.BitmapData bmp_data = bmp.LockBits(); try { GL.BindTexture(TextureTarget.Texture2D, (int)tex.Opaque); GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, bmp.Width, bmp.Height, PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0); } finally { bmp.UnlockBits(bmp_data); } } public void FreeRenderTarget(RenderTarget rt) { rt.Texture2d.Dispose(); GL.Ext.DeleteFramebuffer((int)rt.Opaque); } public unsafe RenderTarget CreateRenderTarget(int w, int h) { //create a texture for it int texid = GenTexture(); Texture2d tex = new Texture2d(this, texid, w, h); GL.BindTexture(TextureTarget.Texture2D,texid); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, w, h, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); tex.SetMagFilter(TextureMagFilter.Nearest); tex.SetMinFilter(TextureMinFilter.Nearest); //create the FBO int fbid = GL.Ext.GenFramebuffer(); GL.Ext.BindFramebuffer(FramebufferTarget.Framebuffer, fbid); //bind the tex to the FBO GL.Ext.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, texid, 0); //do something, I guess say which colorbuffers are used by the framebuffer DrawBuffersEnum* buffers = stackalloc DrawBuffersEnum[1]; buffers[0] = DrawBuffersEnum.ColorAttachment0; GL.DrawBuffers(1, buffers); if (GL.Ext.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) throw new InvalidOperationException($"Error creating framebuffer (at {nameof(GL.Ext.CheckFramebufferStatus)})"); //since we're done configuring unbind this framebuffer, to return to the default GL.Ext.BindFramebuffer(FramebufferTarget.Framebuffer, 0); return new RenderTarget(this, fbid, tex); } public void BindRenderTarget(RenderTarget rt) { _CurrRenderTarget = rt; if(rt == null) GL.Ext.BindFramebuffer(FramebufferTarget.Framebuffer, 0); else GL.Ext.BindFramebuffer(FramebufferTarget.Framebuffer, (int)rt.Opaque); } public Texture2d LoadTexture(BitmapBuffer bmp) { Texture2d ret = null; int id = GenTexture(); try { ret = new Texture2d(this, id, bmp.Width, bmp.Height); GL.BindTexture(TextureTarget.Texture2D, id); //picking a color order that matches doesnt seem to help, any. maybe my driver is accelerating it, or maybe it isnt a big deal. but its something to study on another day GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp.Width, bmp.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); (this as IGL).LoadTextureData(ret, bmp); } catch { GL.DeleteTexture(id); throw; } //set default filtering.. its safest to do this always ret.SetFilterNearest(); return ret; } public unsafe BitmapBuffer ResolveTexture2d(Texture2d tex) { //note - this is dangerous since it changes the bound texture. could we save it? BindTexture2d(tex); var bb = new BitmapBuffer(tex.IntWidth, tex.IntHeight); var bmpdata = bb.LockBits(); GL.GetTexImage(TextureTarget.Texture2D, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmpdata.Scan0); var err = GL.GetError(); bb.UnlockBits(bmpdata); return bb; } public Texture2d LoadTexture(string path) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) return (this as IGL).LoadTexture(fs); } public Matrix4 CreateGuiProjectionMatrix(int w, int h) { return CreateGuiProjectionMatrix(new sd.Size(w, h)); } public Matrix4 CreateGuiViewMatrix(int w, int h, bool autoflip) { return CreateGuiViewMatrix(new sd.Size(w, h), autoflip); } public Matrix4 CreateGuiProjectionMatrix(sd.Size dims) { Matrix4 ret = Matrix4.Identity; ret.M11 = 2.0f / (float)dims.Width; ret.M22 = 2.0f / (float)dims.Height; return ret; } public Matrix4 CreateGuiViewMatrix(sd.Size dims, bool autoflip) { Matrix4 ret = Matrix4.Identity; ret.M22 = -1.0f; ret.M41 = -(float)dims.Width * 0.5f; ret.M42 = (float)dims.Height * 0.5f; if (autoflip) { if (_CurrRenderTarget == null) { } else { //flip as long as we're not a final render target ret.M22 = 1.0f; ret.M42 *= -1; } } return ret; } public void SetViewport(int x, int y, int width, int height) { GL.Viewport(x, y, width, height); GL.Scissor(x, y, width, height); //hack for mupen[rice]+intel: at least the rice plugin leaves the scissor rectangle scrambled, and we're trying to run it in the main graphics context for intel //BUT ALSO: new specifications.. viewport+scissor make sense together } public void SetViewport(int width, int height) { SetViewport(0, 0, width, height); } public void SetViewport(sd.Size size) { SetViewport(size.Width, size.Height); } public void SetViewport(swf.Control control) { var r = control.ClientRectangle; SetViewport(r.Left, r.Top, r.Width, r.Height); } //------------------ INativeWindow OffscreenNativeWindow; IGraphicsContext GraphicsContext; //--------------- //my utility methods GLControl CastControl(swf.Control swfControl) { GLControl glc = swfControl as GLControl; if (glc == null) throw new ArgumentException("Argument isn't a control created by the IGL interface", "glControl"); return glc; } Shader CreateShader(bool cg, ShaderType type, string source, string entry, bool required) { var sw = new ShaderWrapper(); if (cg) { var cgc = new CGC(); var results = cgc.Run(source, entry, type == ShaderType.FragmentShader ? "glslf" : "glslv", false); if (!results.Succeeded) { Console.WriteLine("CGC failed"); Console.WriteLine(results.Errors); return new Shader(this, null, false); } source = results.Code; sw.MapCodeToNative = results.MapCodeToNative; sw.MapNativeToCode = results.MapNativeToCode; } int sid = GL.CreateShader(type); bool ok = CompileShaderSimple(sid, source, required); if(!ok) { GL.DeleteShader(sid); sid = 0; } sw.sid = sid; return new Shader(this, sw, ok); } bool CompileShaderSimple(int sid, string source, bool required) { bool success = true; ErrorCode errcode; errcode = GL.GetError(); if (errcode != ErrorCode.NoError) if (required) throw new InvalidOperationException($"Error compiling shader (from previous operation) {errcode}"); else success = false; GL.ShaderSource(sid, source); errcode = GL.GetError(); if (errcode != ErrorCode.NoError) if (required) throw new InvalidOperationException($"Error compiling shader ({nameof(GL.ShaderSource)}) {errcode}"); else success = false; GL.CompileShader(sid); errcode = GL.GetError(); string resultLog = GL.GetShaderInfoLog(sid); if (errcode != ErrorCode.NoError) { string message = $"Error compiling shader ({nameof(GL.CompileShader)}) {errcode}\r\n\r\n{resultLog}"; if (required) throw new InvalidOperationException(message); else { Console.WriteLine(message); success = false; } } int n; GL.GetShader(sid, ShaderParameter.CompileStatus, out n); if (n == 0) if (required) throw new InvalidOperationException($"Error compiling shader ({nameof(GL.GetShader)})\r\n\r\n{resultLog}"); else success = false; return success; } void UnbindVertexAttributes() { //HAMNUTS: //its not clear how many bindings we'll have to disable before we can enable the ones we need.. //so lets just disable the ones we remember we have bound var currBindings = sVertexAttribEnables; foreach (var index in currBindings) GL.DisableVertexAttribArray(index); currBindings.Clear(); } unsafe void MyBindArrayData(VertexLayout layout, void* pData) { UnbindVertexAttributes(); //HAMNUTS (continued) var currBindings = sVertexAttribEnables; sStateCurrentVertexLayout = sStatePendingVertexLayout; if (layout == null) return; //disable all the client states.. a lot of overhead right now, to be sure GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.ColorArray); for(int i=0;i<8;i++) GL.DisableVertexAttribArray(i); for (int i = 0; i < 8; i++) { GL.ClientActiveTexture(TextureUnit.Texture0 + i); GL.DisableClientState(ArrayCap.TextureCoordArray); } GL.ClientActiveTexture(TextureUnit.Texture0); foreach (var kvp in layout.Items) { if(_CurrPipeline.Memo == "gui") { GL.VertexAttribPointer(kvp.Key, kvp.Value.Components, (VertexAttribPointerType)kvp.Value.AttribType, kvp.Value.Normalized, kvp.Value.Stride, new IntPtr(pData) + kvp.Value.Offset); GL.EnableVertexAttribArray(kvp.Key); currBindings.Add(kvp.Key); } else { var pw = _CurrPipeline.Opaque as PipelineWrapper; //comment SNACKPANTS switch (kvp.Value.Usage) { case AttributeUsage.Position: GL.EnableClientState(ArrayCap.VertexArray); GL.VertexPointer(kvp.Value.Components,VertexPointerType.Float,kvp.Value.Stride,new IntPtr(pData) + kvp.Value.Offset); break; case AttributeUsage.Texcoord0: GL.ClientActiveTexture(TextureUnit.Texture0); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.TexCoordPointer(kvp.Value.Components, TexCoordPointerType.Float, kvp.Value.Stride, new IntPtr(pData) + kvp.Value.Offset); break; case AttributeUsage.Texcoord1: GL.ClientActiveTexture(TextureUnit.Texture1); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.TexCoordPointer(kvp.Value.Components, TexCoordPointerType.Float, kvp.Value.Stride, new IntPtr(pData) + kvp.Value.Offset); GL.ClientActiveTexture(TextureUnit.Texture0); break; case AttributeUsage.Color0: break; } } } } public void MakeDefaultCurrent() { MakeContextCurrent(this.GraphicsContext,OffscreenNativeWindow.WindowInfo); } internal void MakeContextCurrent(IGraphicsContext context, global::OpenTK.Platform.IWindowInfo windowInfo) { context.MakeCurrent(windowInfo); PurgeStateCache(); } void CreateRenderStates() { _rsBlendNoneVerbatim = new CacheBlendState( false, BlendingFactorSrc.One, BlendEquationMode.FuncAdd, BlendingFactorDest.Zero, BlendingFactorSrc.One, BlendEquationMode.FuncAdd, BlendingFactorDest.Zero); _rsBlendNoneOpaque = new CacheBlendState( false, BlendingFactorSrc.One, BlendEquationMode.FuncAdd, BlendingFactorDest.Zero, BlendingFactorSrc.ConstantAlpha, BlendEquationMode.FuncAdd, BlendingFactorDest.Zero); _rsBlendNormal = new CacheBlendState( true, BlendingFactorSrc.SrcAlpha, BlendEquationMode.FuncAdd, BlendingFactorDest.OneMinusSrcAlpha, BlendingFactorSrc.One, BlendEquationMode.FuncAdd, BlendingFactorDest.Zero); } CacheBlendState _rsBlendNoneVerbatim, _rsBlendNoneOpaque, _rsBlendNormal; //state caches int sActiveTexture; VertexLayout sStateCurrentVertexLayout; VertexLayout sStatePendingVertexLayout; HashSet<int> sVertexAttribEnables = new HashSet<int>(); void PurgeStateCache() { sStateCurrentVertexLayout = null; sStatePendingVertexLayout = null; sVertexAttribEnables.Clear(); sActiveTexture = -1; } } //class IGL_TK }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob. // #if DEBUG internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle { #else internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeSspiAuthDataHandle() : base(true) { } protected override bool ReleaseHandle() { return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SECURITY_STATUS.OK; } } // // A set of Safe Handles that depend on native FreeContextBuffer finalizer. // #if DEBUG internal abstract class SafeFreeContextBuffer : DebugSafeHandle { #else internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid { #endif protected SafeFreeContextBuffer() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = -1; SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null; res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; if (res != 0 && pkgArray != null) { pkgArray.SetHandleAsInvalid(); } return res; } internal static SafeFreeContextBuffer CreateEmptyHandle() { return new SafeFreeContextBuffer_SECURITY(); } // // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { if (refHandle is SafeFreeContextBuffer) { ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); } else { ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer); } } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } return status; } public static int SetContextAttributes( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer) { try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length); } finally { phContext.DangerousRelease(); } } } internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer { internal SafeFreeContextBuffer_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } // // Implementation of handles required CertFreeCertificateContext // #if DEBUG internal sealed class SafeFreeCertContext : DebugSafeHandle { #else internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid { #endif internal SafeFreeCertContext() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040; protected override bool ReleaseHandle() { Interop.Crypt32.CertFreeCertificateContext(handle); return true; } } // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif internal Interop.SspiCli.CredHandle _handle; //should be always used as by ref in PInvokes parameters protected SafeFreeCredentials() : base(IntPtr.Zero, true) { _handle = new Interop.SspiCli.CredHandle(); } #if TRACE_VERBOSE public override string ToString() { return "0x" + _handle.ToString(); } #endif public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } #if DEBUG public new IntPtr DangerousGetHandle() { Debug.Fail("This method should never be called for this type"); throw NotImplemented.ByDesign; } #endif public static unsafe int AcquireDefaultCredential( string package, Interop.SspiCli.CredentialUse intent, out SafeFreeCredentials outCredential) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent); int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, IntPtr.Zero, null, null, ref outCredential._handle, out timeStamp); #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out timeStamp); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref Interop.SspiCli.SCHANNEL_CRED authdata, out SafeFreeCredentials outCredential) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata); int errorCode = -1; long timeStamp; // If there is a certificate, wrap it into an array. // Not threadsafe. IntPtr copiedPtr = authdata.paCred; try { IntPtr certArrayPtr = new IntPtr(&copiedPtr); if (copiedPtr != IntPtr.Zero) { authdata.paCred = certArrayPtr; } outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp); } finally { authdata.paCred = copiedPtr; } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } } // // This is a class holding a Credential handle reference, used for static handles cache // #if DEBUG internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid { #else internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid { #endif // // Static cache will return the target handle if found the reference in the table. // internal SafeFreeCredentials Target; internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) { SafeCredentialReference result = new SafeCredentialReference(target); if (result.IsInvalid) { return null; } return result; } private SafeCredentialReference(SafeFreeCredentials target) : base() { // Bumps up the refcount on Target to signify that target handle is statically cached so // its dispose should be postponed bool ignore = false; target.DangerousAddRef(ref ignore); Target = target; SetHandle(new IntPtr(0)); // make this handle valid } protected override bool ReleaseHandle() { SafeFreeCredentials target = Target; if (target != null) { target.DangerousRelease(); } Target = null; return true; } } internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials { public SafeFreeCredential_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0; } } // // Implementation of handles that are dependent on DeleteSecurityContext // #if DEBUG internal abstract partial class SafeDeleteContext : DebugSafeHandle { #else internal abstract partial class SafeDeleteContext : SafeHandle { #endif private const string dummyStr = " "; private static readonly byte[] s_dummyBytes = new byte[] { 0 }; private static readonly IdnMapping s_idnMapping = new IdnMapping(); protected SafeFreeCredentials _EffectiveCredential; //------------------------------------------------------------------- internal static unsafe int InitializeSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { #if TRACE_VERBOSE if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, $"credential:{inCredentials}, crefContext:{refContext}, targetName:{targetName}, inFlags:{inFlags}, endianness:{endianness}"); if (inSecBuffers == null) { NetEventSource.Info(null, $"inSecBuffers = (null)"); } else { NetEventSource.Info(null, $"inSecBuffers = {inSecBuffers}"); } } #endif if (outSecBuffer == null) { NetEventSource.Fail(null, "outSecBuffer != null"); } if (inSecBuffer != null && inSecBuffers != null) { NetEventSource.Fail(null, "inSecBuffer == null || inSecBuffers == null"); } if (inCredentials == null) { throw new ArgumentNullException(nameof(inCredentials)); } Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = default(Interop.SspiCli.SecBufferDesc); bool haveInSecurityBufferDescriptor = false; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); haveInSecurityBufferDescriptor = true; } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); haveInSecurityBufferDescriptor = true; } Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); Interop.SspiCli.SecBuffer[] inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[haveInSecurityBufferDescriptor ? inSecurityBufferDescriptor.cBuffers : 1]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (haveInSecurityBufferDescriptor) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}"); #endif } } } Interop.SspiCli.SecBuffer outUnmanagedBuffer = default; // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.pBuffers = &outUnmanagedBuffer; outUnmanagedBuffer.cbBuffer = outSecBuffer.size; outUnmanagedBuffer.BufferType = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer.pvBuffer = IntPtr.Zero; } else { outUnmanagedBuffer.pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } if (targetName == null || targetName.Length == 0) { targetName = dummyStr; } string punyCode = s_idnMapping.GetAscii(targetName); fixed (char* namePtr = punyCode) { errorCode = MustRunInitializeSecurityContext( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, haveInSecurityBufferDescriptor ? &inSecurityBufferDescriptor : null, refContext, ref outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); } if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshalling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer.cbBuffer; outSecBuffer.type = outUnmanagedBuffer.BufferType; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer.pvBuffer, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}"); return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunInitializeSecurityContext( ref SafeFreeCredentials inCredentials, void* inContextPtr, byte* targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, Interop.SspiCli.SecBufferDesc* inputBuffer, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags attributes, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.SspiCli.InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, ref outputBuffer, ref attributes, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } return errorCode; } //------------------------------------------------------------------- internal static unsafe int AcceptSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { #if TRACE_VERBOSE if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, $"credential={inCredentials}, refContext={refContext}, inFlags={inFlags}"); if (inSecBuffers == null) { NetEventSource.Info(null, "inSecBuffers = (null)"); } else { NetEventSource.Info(null, $"inSecBuffers[] = (inSecBuffers)"); } } #endif if (outSecBuffer == null) { NetEventSource.Fail(null, "outSecBuffer != null"); } if (inSecBuffer != null && inSecBuffers != null) { NetEventSource.Fail(null, "inSecBuffer == null || inSecBuffers == null"); } if (inCredentials == null) { throw new ArgumentNullException(nameof(inCredentials)); } Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = default(Interop.SspiCli.SecBufferDesc); bool haveInSecurityBufferDescriptor = false; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); haveInSecurityBufferDescriptor = true; } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); haveInSecurityBufferDescriptor = true; } Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[haveInSecurityBufferDescriptor ? inSecurityBufferDescriptor.cBuffers : 1]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (haveInSecurityBufferDescriptor) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}"); #endif } } } var outUnmanagedBuffer = new Interop.SspiCli.SecBuffer[1]; fixed (void* outUnmanagedBufferPtr = &outUnmanagedBuffer[0]) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.pBuffers = outUnmanagedBufferPtr; // Copy the SecurityBuffer content into unmanaged place holder. outUnmanagedBuffer[0].cbBuffer = outSecBuffer.size; outUnmanagedBuffer[0].BufferType = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].pvBuffer = IntPtr.Zero; } else { outUnmanagedBuffer[0].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, haveInSecurityBufferDescriptor ? &inSecurityBufferDescriptor : null, inFlags, endianness, refContext, ref outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshaling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer[0].cbBuffer; outSecBuffer.type = outUnmanagedBuffer[0].BufferType; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer[0].pvBuffer, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}"); return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunAcceptSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, void* inContextPtr, Interop.SspiCli.SecBufferDesc* inputBuffer, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags outFlags, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // Run the body of this method as a non-interruptible block. try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.SspiCli.AcceptSecurityContext( ref credentialHandle, inContextPtr, inputBuffer, inFlags, endianness, ref outContext._handle, ref outputBuffer, ref outFlags, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle. if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes. handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // An error on the first call, need to set the out handle to invalid value. outContext._handle.SetToInvalid(); } return errorCode; } internal static unsafe int CompleteAuthToken( ref SafeDeleteContext refContext, SecurityBuffer[] inSecBuffers) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, "SafeDeleteContext::CompleteAuthToken"); NetEventSource.Info(null, $" refContext = {refContext}"); NetEventSource.Info(null, $" inSecBuffers[] = {inSecBuffers}"); } if (inSecBuffers == null) { NetEventSource.Fail(null, "inSecBuffers == null"); } var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[inSecurityBufferDescriptor.cBuffers]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { securityBuffer = inSecBuffers[index]; if (securityBuffer != null) { inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType: {securityBuffer.type}"); #endif } } Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle(); if (refContext != null) { contextHandle = refContext._handle; } try { if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } try { bool ignore = false; refContext.DangerousAddRef(ref ignore); errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { refContext.DangerousRelease(); } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}"); return errorCode; } internal static unsafe int ApplyControlToken( ref SafeDeleteContext refContext, SecurityBuffer[] inSecBuffers) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(null); NetEventSource.Info(null, $" refContext = {refContext}"); NetEventSource.Info(null, $" inSecBuffers[] = length:{inSecBuffers.Length}"); } if (inSecBuffers == null) { NetEventSource.Fail(null, "inSecBuffers == null"); } var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; var inUnmanagedBuffer = new Interop.SspiCli.SecBuffer[inSecurityBufferDescriptor.cBuffers]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.cBuffers]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { securityBuffer = inSecBuffers[index]; if (securityBuffer != null) { inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].pvBuffer = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}"); #endif } } // TODO: (#3114): Optimizations to remove the unnecesary allocation of a CredHandle, remove the AddRef // if refContext was previously null, refactor the code to unify CompleteAuthToken and ApplyControlToken. Interop.SspiCli.CredHandle contextHandle = new Interop.SspiCli.CredHandle(); if (refContext != null) { contextHandle = refContext._handle; } try { if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } try { bool ignore = false; refContext.DangerousAddRef(ref ignore); errorCode = Interop.SspiCli.ApplyControlToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { refContext.DangerousRelease(); } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}"); return errorCode; } } internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext { internal SafeDeleteContext_SECURITY() : base() { } protected override bool ReleaseHandle() { if (this._EffectiveCredential != null) { this._EffectiveCredential.DangerousRelease(); } return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0; } } // Based on SafeFreeContextBuffer. internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding { private int _size; public override int Size { get { return _size; } } public override bool IsInvalid { get { return handle == new IntPtr(0) || handle == new IntPtr(-1); } } internal unsafe void Set(IntPtr value) { this.handle = value; } internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle() { return new SafeFreeContextBufferChannelBinding_SECURITY(); } public static unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, SecPkgContext_Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; // SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which // map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique. if (contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_ENDPOINT_BINDINGS && contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_UNIQUE_BINDINGS) { return status; } try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { refHandle.Set((*buffer).Bindings); refHandle._size = (*buffer).BindingsLength; } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } return status; } public override string ToString() { if (IsInvalid) { return null; } var bytes = new byte[_size]; Marshal.Copy(handle, bytes, 0, bytes.Length); return BitConverter.ToString(bytes).Replace('-', ' '); } } internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding { protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; #if WINDOWS_UWP using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; #else using System.Windows; using System.Windows.Controls; #endif namespace ReactNative.UIManager { /// <summary> /// Class responsible for knowing how to create and update views of a given /// type. It is also responsible for creating and updating /// <see cref="ReactShadowNode"/> subclasses used for calculating position /// and size for the corresponding native view. /// </summary> public abstract class ViewManager<TFrameworkElement, TReactShadowNode> : IViewManager where TFrameworkElement : FrameworkElement where TReactShadowNode : ReactShadowNode { /// <summary> /// The name of this view manager. This will be the name used to /// reference this view manager from JavaScript. /// </summary> public abstract string Name { get; } /// <summary> /// The <see cref="Type"/> instance that represents the type of shadow /// node that this manager will return from /// <see cref="CreateShadowNodeInstance"/>. /// /// This method will be used in the bridge initialization phase to /// collect properties exposed using the <see cref="Annotations.ReactPropAttribute"/> /// annotation from the <see cref="ReactShadowNode"/> subclass. /// </summary> public virtual Type ShadowNodeType { get { return typeof(TReactShadowNode); } } /// <summary> /// The commands map for the view manager. /// </summary> public virtual IReadOnlyDictionary<string, object> CommandsMap { get; } /// <summary> /// The exported custom bubbling event types. /// </summary> public virtual IReadOnlyDictionary<string, object> ExportedCustomBubblingEventTypeConstants { get; } /// <summary> /// The exported custom direct event types. /// </summary> public virtual IReadOnlyDictionary<string, object> ExportedCustomDirectEventTypeConstants { get; } /// <summary> /// The exported view constants. /// </summary> public virtual IReadOnlyDictionary<string, object> ExportedViewConstants { get; } /// <summary> /// Creates a shadow node for the view manager. /// </summary> /// <returns>The shadow node instance.</returns> public IReadOnlyDictionary<string, string> NativeProperties { get { return ViewManagersPropertyCache.GetNativePropertiesForView(GetType(), ShadowNodeType); } } /// <summary> /// Update the properties of the given view. /// </summary> /// <param name="viewToUpdate">The view to update.</param> /// <param name="props">The properties.</param> public void UpdateProperties(TFrameworkElement viewToUpdate, ReactStylesDiffMap props) { var propertySetters = ViewManagersPropertyCache.GetNativePropertySettersForViewManagerType(GetType()); var keys = props.Keys; foreach (var key in keys) { var setter = default(IPropertySetter); if (propertySetters.TryGetValue(key, out setter)) { setter.UpdateViewManagerProperty(this, viewToUpdate, props); } } OnAfterUpdateTransaction(viewToUpdate); } /// <summary> /// Creates a view and installs event emitters on it. /// </summary> /// <param name="reactContext">The context.</param> /// <returns>The view.</returns> public TFrameworkElement CreateView(ThemedReactContext reactContext) { var view = CreateViewInstance(reactContext); AddEventEmitters(reactContext, view); // TODO: enable touch intercepting view parents return view; } /// <summary> /// Called when view is detached from view hierarchy and allows for /// additional cleanup by the <see cref="IViewManager"/> subclass. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The view.</param> public virtual void OnDropViewInstance(ThemedReactContext reactContext, TFrameworkElement view) { } /// <summary> /// This method should return the subclass of <see cref="ReactShadowNode"/> /// which will be then used for measuring the position and size of the /// view. /// </summary> /// <remarks> /// In most cases, this will just return an instance of /// <see cref="ReactShadowNode"/>. /// </remarks> /// <returns>The shadow node instance.</returns> public abstract TReactShadowNode CreateShadowNodeInstance(); /// <summary> /// Implement this method to receive optional extra data enqueued from /// the corresponding instance of <see cref="ReactShadowNode"/> in /// <see cref="ReactShadowNode.OnCollectExtraUpdates"/>. /// </summary> /// <param name="root">The root view.</param> /// <param name="extraData">The extra data.</param> public abstract void UpdateExtraData(TFrameworkElement root, object extraData); /// <summary> /// Implement this method to receive events/commands directly from /// JavaScript through the <see cref="UIManagerModule"/>. /// </summary> /// <param name="view"> /// The view instance that should receive the command. /// </param> /// <param name="commandId">Identifer for the command.</param> /// <param name="args">Optional arguments for the command.</param> public virtual void ReceiveCommand(TFrameworkElement view, int commandId, JArray args) { } /// <summary> /// Gets the dimensions of the view. /// </summary> /// <param name="view">The view.</param> /// <returns>The view dimensions.</returns> public Dimensions GetDimensions(TFrameworkElement view) { return new Dimensions { X = Canvas.GetLeft(view), Y = Canvas.GetTop(view), Width = view.Width, Height = view.Height, }; } /// <summary> /// Sets the dimensions of the view. /// </summary> /// <param name="view">The view.</param> /// <param name="dimensions">The output buffer.</param> public virtual void SetDimensions(TFrameworkElement view, Dimensions dimensions) { Canvas.SetLeft(view, dimensions.X); Canvas.SetTop(view, dimensions.Y); view.Width = dimensions.Width; view.Height = dimensions.Height; } /// <summary> /// Creates a new view instance of type <typeparamref name="TFrameworkElement"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <returns>The view instance.</returns> protected abstract TFrameworkElement CreateViewInstance(ThemedReactContext reactContext); /// <summary> /// Subclasses can override this method to install custom event /// emitters on the given view. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The view instance.</param> /// <remarks> /// Consider overriding this method if your view needs to emit events /// besides basic touch events to JavaScript (e.g., scroll events). /// </remarks> protected virtual void AddEventEmitters(ThemedReactContext reactContext, TFrameworkElement view) { } /// <summary> /// Callback that will be triggered after all properties are updated in /// the current update transation (all <see cref="Annotations.ReactPropAttribute"/> handlers /// for properties updated in the current transaction have been called). /// </summary> /// <param name="view">The view.</param> protected virtual void OnAfterUpdateTransaction(TFrameworkElement view) { } #region IViewManager void IViewManager.UpdateProperties(DependencyObject viewToUpdate, ReactStylesDiffMap props) { UpdateProperties((TFrameworkElement)viewToUpdate, props); } DependencyObject IViewManager.CreateView(ThemedReactContext reactContext) { return CreateView(reactContext); } void IViewManager.OnDropViewInstance(ThemedReactContext reactContext, DependencyObject view) { OnDropViewInstance(reactContext, (TFrameworkElement)view); } ReactShadowNode IViewManager.CreateShadowNodeInstance() { return CreateShadowNodeInstance(); } void IViewManager.UpdateExtraData(DependencyObject root, object extraData) { UpdateExtraData((TFrameworkElement)root, extraData); } void IViewManager.ReceiveCommand(DependencyObject view, int commandId, JArray args) { ReceiveCommand((TFrameworkElement)view, commandId, args); } Dimensions IViewManager.GetDimensions(DependencyObject view) { return GetDimensions((TFrameworkElement)view); } void IViewManager.SetDimensions(DependencyObject view, Dimensions dimensions) { SetDimensions((TFrameworkElement)view, dimensions); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Threading; using System.Windows; using System.Windows.Threading; using System.Linq; using CodeOwls.SeeShell.Common.DataSources; using CodeOwls.SeeShell.Common.Exceptions; using CodeOwls.SeeShell.Common.Triggers; using CodeOwls.SeeShell.Common.ViewModels; using CodeOwls.SeeShell.PowerShell.Cmdlets; namespace CodeOwls.SeeShell.Common { //TODO: add prop change notifications public class PowerShellDataSource : DataViewModelBase, IPowerShellDataSource { private static readonly Log _log = new Log( typeof(PowerShellDataSource)); private System.Management.Automation.PowerShell _powerShell; private IAsyncResult _asyncResult; private readonly ObservableCollection<ProgressRecord> _progressRecords; private ObservableCollection<object> _data; private string _scriptBlock; private ManualResetEvent _scriptCompleteEvent; private int _dataCollectionMaxSize; private ITrigger _trigger; private readonly ScaleDescriptorAssignmentCollection _scales; private readonly List<PSMemberInfo> _dynamicMembers; private readonly List<DynamicMemberSpecification> _specs; private readonly ObservableCollection<object> _allRecords; private readonly object _dataSyncObject = new object(); private ObservableCollection<object> _transactionDataSet; public PowerShellDataSource() { _allRecords = new ObservableCollection<object>(); _specs = new List<DynamicMemberSpecification>(); _scales = new ScaleDescriptorAssignmentCollection(); _scales.CollectionChanged += OnScaleDescriptorAssignmentCollectionChanged; _dataCollectionMaxSize = 20; _data = new ObservableCollection<object>(); _progressRecords = new ObservableCollection<ProgressRecord>(); _dynamicMembers = new List<PSMemberInfo>(); _powerShell = System.Management.Automation.PowerShell.Create(); var runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); runspace.SessionStateProxy.SetVariable( "seeShellDataSource", this ); var tmp = System.Management.Automation.PowerShell.Create(); tmp.Runspace = runspace; tmp.AddScript("function start-seeShellDataSet { $seeShellDataSource.StartDataSet(); }") .AddScript("function commit-seeShellDataSet { $seeShellDataSource.CommitDataSet(); }") .AddScript("function undo-seeShellDataSet { $seeShellDataSource.RollbackDataSet(); }"); tmp.Invoke(); _powerShell.Runspace = runspace; _powerShell.InvocationStateChanged += InvocationStateChanged; _powerShell.Streams.Debug.DataAdded += DebugRecordAdded; _powerShell.Streams.Verbose.DataAdded += VerboseRecordAdded; _powerShell.Streams.Progress.DataAdded += ProgressRecordAdded; _powerShell.Streams.Error.DataAdded += ErrorRecordAdded; _powerShell.Streams.Warning.DataAdded += WarningRecordAdded; } public void StartDataSet() { _transactionDataSet = new ObservableCollection<object>(); } public void CommitDataSet() { _data = _transactionDataSet; Application.Current.Dispatcher.BeginInvoke((Action)(()=> NotifyOfPropertyChange(() => Data)) ); } public void RollbackDataSet() { _transactionDataSet = null; } private void OnScaleDescriptorAssignmentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if( e.Action != NotifyCollectionChangedAction.Add) { return; } } public WaitHandle ScriptComplete { get { if( null == _asyncResult ) { return null; } return _asyncResult.AsyncWaitHandle; } } public ScaleDescriptorAssignmentCollection Scales { get { return _scales; } } public ITrigger Trigger { get { return _trigger; } set { if( null != _trigger ) { _trigger.Trigger -= OnTrigger; } _trigger = value; _trigger.Trigger += OnTrigger; } } public bool UseDispatcher { get; set; } public string ScriptBlock { get { return _scriptBlock; } set { EndCurrentAsyncResult(); ClearPowerShellState(); _scriptBlock = value; _powerShell.AddScript(_scriptBlock, false); } } private void ClearPowerShellState() { _powerShell.Commands.Clear(); var e = _scriptCompleteEvent; if( null != e ) { e.Close(); e.Dispose(); } _scriptCompleteEvent = new ManualResetEvent(false); } private void EndCurrentAsyncResult() { var asyncResult = Interlocked.Exchange(ref _asyncResult, null); if (null == asyncResult) { return; } _powerShell.EndInvoke(asyncResult); } public PSInvocationStateInfo InvocationState { get { return _powerShell.InvocationStateInfo; } } public ObservableCollection<ProgressRecord> ProgressRecords { get { return _progressRecords; } } public override ObservableCollection<object> AllRecords { get { return _allRecords; } } public ObservableCollection<object> Data { get { return _data; } } public void AddDynamicMember(PSMemberInfo plotMember) { AddDynamicMemberAndScale(plotMember); } private void AddDynamicMemberAndScale(PSMemberInfo plotMember) { if (null == plotMember) { return; } SafeAddDynamicMember(plotMember); var name = plotMember.Name; AddDynamicScaleForProperty(name); } private void SafeAddDynamicMember(PSMemberInfo plotMember) { using (_log.PushContext("SafeAddDynamicMember")) { if (null == plotMember) { _log.Debug("no plot member specified"); return; } if (!(from dm in _dynamicMembers where Name == plotMember.Name select dm).Any()) { _log.DebugFormat( "adding dynamic member [{0}]", plotMember.Name ); _dynamicMembers.Add(plotMember); } } } public IScaleDescriptorAssignment AddDynamicScaleForProperty(string name) { var scaleAssignment = this.Scales.ForProperty(name); if (null == scaleAssignment) { var scale = new DynamicPropertyScaleDescriptor(this, name); scaleAssignment = new ScaleDescriptorAssignment {PropertyName = name, Scale = scale}; Scales.Add(scaleAssignment); } return scaleAssignment; } public int DataCollectionMaxSize { get { return _dataCollectionMaxSize; } set { _dataCollectionMaxSize = value; EnforceDataCollectionLimit(); NotifyOfPropertyChange(()=>DataCollectionMaxSize); } } private void EnforceDataCollectionLimit() { if( -1 == _dataCollectionMaxSize || _data.Count <= _dataCollectionMaxSize ) { return; } var overCount = _data.Count - _dataCollectionMaxSize; while( overCount-- > 0 ) { _data.RemoveAt(0); } } private void WarningRecordAdded(object sender, DataAddedEventArgs e) { var record = _powerShell.Streams.Warning[e.Index]; AllRecords.Add(record); } private void ErrorRecordAdded(object sender, DataAddedEventArgs e) { var record = _powerShell.Streams.Error[e.Index]; AllRecords.Add(record); } private void ProgressRecordAdded(object sender, DataAddedEventArgs e) { var record = _powerShell.Streams.Progress[e.Index]; ProgressRecords.Add(record); } private void VerboseRecordAdded(object sender, DataAddedEventArgs e) { var record = _powerShell.Streams.Verbose[e.Index]; AllRecords.Add(record); } private void DebugRecordAdded(object sender, DataAddedEventArgs e) { var record = _powerShell.Streams.Debug[e.Index]; AllRecords.Add(record); } private void InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e) { if (e.InvocationStateInfo.State != this.InvocationState.State || e.InvocationStateInfo.Reason != this.InvocationState.Reason) { NotifyOfPropertyChange(() => InvocationState); } } public void Dispose() { EndCurrentAsyncResult(); var ps = Interlocked.Exchange(ref _powerShell, null); if (null == ps) { return; } ps.Runspace.Close(); ps.Runspace.Dispose(); ps.Dispose(); } protected virtual PSDataCollection<object> CurrentScriptBlockInput { get { return null; } } void ExecuteScriptBlock() { PSDataCollection<PSObject> data = new PSDataCollection<PSObject>(); data.DataAdded += (s, a) => { PSObject ps = data[a.Index]; AddDataObject(ps); }; var input = CurrentScriptBlockInput; _asyncResult = _powerShell.BeginInvoke(input, data); } public void AddDataObject(PSObject ps) { using (_log.PushContext("AddDataObject")) { var solidifier = new PSObjectSolidifier(); UpdateDynamicMembers(ps); AddDynamicMembersToPSObject(ps); AddMagicPropertiesToPSObject(ps); object d = solidifier.AsConcreteType(ps); if (UseDispatcher && null != Application.Current && null != Application.Current.Dispatcher && !Application.Current.Dispatcher.CheckAccess()) { //TODO: reconcile begininvoke and just invoke Application.Current.Dispatcher.BeginInvoke(new SendOrPostCallback(AddDataObjectToCollection), d); } else { AddDataObjectToCollection(d); } } } private void AddDataObjectToCollection(object t) { if (null != _transactionDataSet) { _transactionDataSet.Add(t); return; } lock (_dataSyncObject) { try { _data.Add(t); } catch (Exception x) { AllRecords.Add( new ErrorRecord( x, "SeeShell.DataSource.AddDataException", ErrorCategory.InvalidOperation, t ) ); } EnforceDataCollectionLimit(); } } private void OnTrigger(object sender, EventArgs e) { ExecuteScriptBlock(); } public void AddDynamicMemberSpecification( DynamicMemberSpecification spec ) { lock (_specs) { _specs.Add(spec); ApplyDynamicMemberSpecifications(); } } private void ApplyDynamicMemberSpecifications() { using (_log.PushContext("ApplyDynamicMemberSpecifications")) { if (0 < Data.Count) { lock (_dataSyncObject) { var newData = Data.ToList().ConvertAll(o => ((SolidPSObjectBase) o).PSObject).ToList(); UpdateDynamicMembers(newData.First()); newData.ForEach(pso => { AddDynamicMembersToPSObject(pso); AddMagicPropertiesToPSObject(pso); }); var solidifier = new PSObjectSolidifier(); for (int i = 0; i < newData.Count; ++i) { AddIndexToPSObject(newData[i], i); Data[i] = solidifier.AsConcreteType(newData[i]); } } } else if (0 < AllRecordsCount) { UpdateDynamicMembers(new PSObject()); } } } private void AddIndexToPSObject(PSObject ps, int i) { var prop = ps.Properties.Match(MagicNames.DataItemIndexPropertyName).FirstOrDefault(); if (null == prop) { var m = new PSNoteProperty(MagicNames.DataItemIndexPropertyName, i); ps.Properties.Add(m); } else { prop.Value = i; } } private void AddDynamicMembersToPSObject(PSObject item) { if (null == item) { return; } _dynamicMembers.ToList().ForEach((psm) => { if (null == item.Members[psm.Name]) { try { item.Members.Add(psm); } catch( Exception e ) { _log.Error( String.Format( "an exception was raised while adding member [{0}] to data item", psm.Name), e); } } } ); } IScaleDescriptorAssignment GetOrCreateScaleAssignment(string propertyName, PSPropertyInfo member) { using (_log.PushContext("GetOrCreateScaleAssignment [{0}]", propertyName)) { var scaleAssignment = (from s in Scales where StringComparer.InvariantCultureIgnoreCase.Equals(s.PropertyName, propertyName) select s).FirstOrDefault(); if (null == scaleAssignment && null == member) { return null; } if (null != scaleAssignment) { Scales.Add(new ScaleDescriptorAssignment {PropertyName = member.Name, Scale = scaleAssignment.Scale}); return scaleAssignment; } return AddDynamicScaleForProperty(member.Name); } } void UpdateDynamicMembers(PSObject ps) { List<DynamicMemberSpecification> specs; lock (_specs) { if (0 == _specs.Count) { return; } specs = _specs.ToList(); _specs.Clear(); } var factory = new DynamicMemberFactory(this, specs, ps); var dynamicMembers = factory.CreateDynamicMembers(); foreach( var m in dynamicMembers ) { SafeAddScaleDescriptorAssignment(m); SafeAddDynamicMember( m.MemberInfo ); } } void AddMagicPropertiesToPSObject( PSObject ps ) { if (!ps.Properties.Match(MagicNames.DataSourcePropertyName).Any()) { var m = new PSNoteProperty(MagicNames.DataSourcePropertyName, this); ps.Properties.Add(m); } //Scales.ToList().ForEach(sda => // { // try // { // var sm = new PSNoteProperty(sda.PropertyName + "_Scale", sda); // ps.Properties.Add(sm); // } // catch // { // } // }); } private void SafeAddScaleDescriptorAssignment(DynamicMemberDescriptor m) { using (_log.PushContext("SafeAddScaleDescriptorAssignment")) { IScaleDescriptor sd = m.ScaleDescriptor; if (null == sd) { _log.DebugFormat("getting/creating scale descriptor for {0}", m.MemberInfo.Name); GetOrCreateScaleAssignment(m.MemberInfo.Name, m.MemberInfo); } else { _log.DebugFormat("adding scale descriptor assignment for {0} to {1}", m.MemberInfo.Name, m.ScaleDescriptor.Name); Scales.Add(new ScaleDescriptorAssignment {PropertyName = m.MemberInfo.Name, Scale = m.ScaleDescriptor}); } } } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ namespace NPOI.HPSF { using System; using System.Collections; /// <summary> /// The <em>Variant</em> types as defined by Microsoft's COM. I /// found this information in <a href="http://www.marin.clara.net/COM/variant_type_definitions.htm"> /// http://www.marin.clara.net/COM/variant_type_definitions.htm</a>. /// In the variant types descriptions the following shortcuts are /// used: <strong> [V]</strong> - may appear in a VARIANT, /// <strong>[T]</strong> - may appear in a TYPEDESC, /// <strong>[P]</strong> - may appear in an OLE property Set, /// <strong>[S]</strong> - may appear in a Safe Array. /// @author Rainer Klute ([email protected]) /// @since 2002-02-09 /// </summary> public class Variant { /** * [V][P] Nothing, i.e. not a single byte of data. */ public const int VT_EMPTY = 0; /** * [V][P] SQL style Null. */ public const int VT_NULL = 1; /** * [V][T][P][S] 2 byte signed int. */ public const int VT_I2 = 2; /** * [V][T][P][S] 4 byte signed int. */ public const int VT_I4 = 3; /** * [V][T][P][S] 4 byte real. */ public const int VT_R4 = 4; /** * [V][T][P][S] 8 byte real. */ public const int VT_R8 = 5; /** * [V][T][P][S] currency. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_CY = 6; /** * [V][T][P][S] DateTime. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_DATE = 7; /** * [V][T][P][S] OLE Automation string. <span * style="background-color: #ffff00">How long is this? How is it * To be interpreted?</span> */ public const int VT_BSTR = 8; /** * [V][T][P][S] IDispatch *. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_DISPATCH = 9; /** * [V][T][S] SCODE. <span style="background-color: #ffff00">How * long is this? How is it To be interpreted?</span> */ public const int VT_ERROR = 10; /** * [V][T][P][S] True=-1, False=0. */ public const int VT_BOOL = 11; /** * [V][T][P][S] VARIANT *. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_VARIANT = 12; /** * [V][T][S] IUnknown *. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_UNKNOWN = 13; /** * [V][T][S] 16 byte fixed point. */ public const int VT_DECIMAL = 14; /** * [T] signed char. */ public const int VT_I1 = 16; /** * [V][T][P][S] unsigned char. */ public const int VT_UI1 = 17; /** * [T][P] unsigned short. */ public const int VT_UI2 = 18; /** * [T][P] unsigned int. */ public const int VT_UI4 = 19; /** * [T][P] signed 64-bit int. */ public const int VT_I8 = 20; /** * [T][P] unsigned 64-bit int. */ public const int VT_UI8 = 21; /** * [T] signed machine int. */ public const int VT_INT = 22; /** * [T] unsigned machine int. */ public const int VT_UINT = 23; /** * [T] C style void. */ public const int VT_VOID = 24; /** * [T] Standard return type. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_HRESULT = 25; /** * [T] pointer type. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_PTR = 26; /** * [T] (use VT_ARRAY in VARIANT). */ public const int VT_SAFEARRAY = 27; /** * [T] C style array. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_CARRAY = 28; /** * [T] user defined type. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_USERDEFINED = 29; /** * [T][P] null terminated string. */ public const int VT_LPSTR = 30; /** * [T][P] wide (Unicode) null terminated string. */ public const int VT_LPWSTR = 31; /** * [P] FILETIME. The FILETIME structure holds a DateTime and time * associated with a file. The structure identifies a 64-bit * integer specifying the number of 100-nanosecond intervals which * have passed since January 1, 1601. This 64-bit value is split * into the two dwords stored in the structure. */ public const int VT_FILETIME = 64; /** * [P] Length prefixed bytes. */ public const int VT_BLOB = 65; /** * [P] Name of the stream follows. */ public const int VT_STREAM = 66; /** * [P] Name of the storage follows. */ public const int VT_STORAGE = 67; /** * [P] Stream Contains an object. <span * style="background-color: #ffff00"> How long is this? How is it * To be interpreted?</span> */ public const int VT_STREAMED_OBJECT = 68; /** * [P] Storage Contains an object. <span * style="background-color: #ffff00"> How long is this? How is it * To be interpreted?</span> */ public const int VT_STORED_OBJECT = 69; /** * [P] Blob Contains an object. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_BLOB_OBJECT = 70; /** * [P] Clipboard format. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_CF = 71; /** * [P] A Class ID. * * It consists of a 32 bit unsigned integer indicating the size * of the structure, a 32 bit signed integer indicating (Clipboard * Format Tag) indicating the type of data that it Contains, and * then a byte array containing the data. * * The valid Clipboard Format Tags are: * * <ul> * <li>{@link Thumbnail#CFTAG_WINDOWS}</li> * <li>{@link Thumbnail#CFTAG_MACINTOSH}</li> * <li>{@link Thumbnail#CFTAG_NODATA}</li> * <li>{@link Thumbnail#CFTAG_FMTID}</li> * </ul> * * <pre>typedef struct tagCLIPDATA { * // cbSize is the size of the buffer pointed To * // by pClipData, plus sizeof(ulClipFmt) * ULONG cbSize; * long ulClipFmt; * BYTE* pClipData; * } CLIPDATA;</pre> * * See <a * href="msdn.microsoft.com/library/en-us/com/stgrstrc_0uwk.asp" * tarGet="_blank"> * msdn.microsoft.com/library/en-us/com/stgrstrc_0uwk.asp</a>. */ public const int VT_CLSID = 72; /** * "MUST be a VersionedStream. The storage representing the (non-simple) * property set MUST have a stream element with the name in the StreamName * field." -- [MS-OLEPS] -- v20110920; Object Linking and Embedding (OLE) * Property Set Data Structures; page 24 / 63 */ public const int VT_VERSIONED_STREAM = 0x0049; /** * [P] simple counted array. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_VECTOR = 0x1000; /** * [V] SAFEARRAY*. <span style="background-color: #ffff00">How * long is this? How is it To be interpreted?</span> */ public const int VT_ARRAY = 0x2000; /** * [V] void* for local use. <span style="background-color: * #ffff00">How long is this? How is it To be * interpreted?</span> */ public const int VT_BYREF = 0x4000; /** * FIXME (3): Document this! */ public const int VT_RESERVED = 0x8000; /** * FIXME (3): Document this! */ public const int VT_ILLEGAL = 0xFFFF; /** * FIXME (3): Document this! */ public const int VT_ILLEGALMASKED = 0xFFF; /** * FIXME (3): Document this! */ public const int VT_TYPEMASK = 0xFFF; /** * Maps the numbers denoting the variant types To their corresponding * variant type names. */ private static IDictionary numberToName; private static IDictionary numberToLength; /** * Denotes a variant type with a Length that is unknown To HPSF yet. */ public const int Length_UNKNOWN = -2; /** * Denotes a variant type with a variable Length. */ public const int Length_VARIABLE = -1; /** * Denotes a variant type with a Length of 0 bytes. */ public const int Length_0 = 0; /** * Denotes a variant type with a Length of 2 bytes. */ public const int Length_2 = 2; /** * Denotes a variant type with a Length of 4 bytes. */ public const int Length_4 = 4; /** * Denotes a variant type with a Length of 8 bytes. */ public const int Length_8 = 8; static Variant() { /* Initialize the number-to-name map: */ Hashtable tm1 = new Hashtable(); tm1[0] = "VT_EMPTY"; tm1[1] = "VT_NULL"; tm1[2] = "VT_I2"; tm1[3] = "VT_I4"; tm1[4] = "VT_R4"; tm1[5] = "VT_R8"; tm1[6] = "VT_CY"; tm1[7] = "VT_DATE"; tm1[8] = "VT_BSTR"; tm1[9] = "VT_DISPATCH"; tm1[10] = "VT_ERROR"; tm1[11] = "VT_BOOL"; tm1[12] = "VT_VARIANT"; tm1[13] = "VT_UNKNOWN"; tm1[14] = "VT_DECIMAL"; tm1[16] = "VT_I1"; tm1[17] = "VT_UI1"; tm1[18] = "VT_UI2"; tm1[19] = "VT_UI4"; tm1[20] = "VT_I8"; tm1[21] = "VT_UI8"; tm1[22] = "VT_INT"; tm1[23] = "VT_UINT"; tm1[24] = "VT_VOID"; tm1[25] = "VT_HRESULT"; tm1[26] = "VT_PTR"; tm1[27] = "VT_SAFEARRAY"; tm1[28] = "VT_CARRAY"; tm1[29] = "VT_USERDEFINED"; tm1[30] = "VT_LPSTR"; tm1[31] = "VT_LPWSTR"; tm1[64] = "VT_FILETIME"; tm1[65] = "VT_BLOB"; tm1[66] = "VT_STREAM"; tm1[67] = "VT_STORAGE"; tm1[68] = "VT_STREAMED_OBJECT"; tm1[69] = "VT_STORED_OBJECT"; tm1[70] = "VT_BLOB_OBJECT"; tm1[71] = "VT_CF"; tm1[72] = "VT_CLSID"; numberToName = tm1; /* Initialize the number-to-Length map: */ Hashtable tm2 = new Hashtable(); tm2[0] = Length_0; tm2[1] = Length_UNKNOWN; tm2[2] = Length_2; tm2[3] = Length_4; tm2[4] = Length_4; tm2[5] = Length_8; tm2[6] = Length_UNKNOWN; tm2[7] = Length_UNKNOWN; tm2[8] = Length_UNKNOWN; tm2[9] = Length_UNKNOWN; tm2[10] = Length_UNKNOWN; tm2[11] = Length_UNKNOWN; tm2[12] = Length_UNKNOWN; tm2[13] = Length_UNKNOWN; tm2[14] = Length_UNKNOWN; tm2[16] = Length_UNKNOWN; tm2[17] = Length_UNKNOWN; tm2[18] = Length_UNKNOWN; tm2[19] = Length_UNKNOWN; tm2[20] = Length_UNKNOWN; tm2[21] = Length_UNKNOWN; tm2[22] = Length_UNKNOWN; tm2[23] = Length_UNKNOWN; tm2[24] = Length_UNKNOWN; tm2[25] = Length_UNKNOWN; tm2[26] = Length_UNKNOWN; tm2[27] = Length_UNKNOWN; tm2[28] = Length_UNKNOWN; tm2[29] = Length_UNKNOWN; tm2[30] = Length_VARIABLE; tm2[31] = Length_UNKNOWN; tm2[64] = Length_8; tm2[65] = Length_UNKNOWN; tm2[66] = Length_UNKNOWN; tm2[67] = Length_UNKNOWN; tm2[68] = Length_UNKNOWN; tm2[69] = Length_UNKNOWN; tm2[70] = Length_UNKNOWN; tm2[71] = Length_UNKNOWN; tm2[72] = Length_UNKNOWN; numberToLength = tm2; } /// <summary> /// Returns the variant type name associated with a variant type /// number. /// </summary> /// <param name="variantType">The variant type number.</param> /// <returns>The variant type name or the string "unknown variant type"</returns> public static String GetVariantName(long variantType) { String name = (String)numberToName[variantType]; return name != null ? name : "unknown variant type"; } /// <summary> /// Returns a variant type's Length. /// </summary> /// <param name="variantType">The variant type number.</param> /// <returns>The Length of the variant type's data in bytes. If the Length Is /// variable, i.e. the Length of a string, -1 is returned. If HPSF does not /// know the Length, -2 is returned. The latter usually indicates an /// unsupported variant type.</returns> public static int GetVariantLength(long variantType) { long key = (int)variantType; if (numberToLength.Contains(key)) return -2; long Length = (long)numberToLength[key]; return Convert.ToInt32(Length); } } }
// Copyright 2019 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArcGIS.Core; using ArcGIS.Core.CIM; using ArcGIS.Core.Data; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Editing.Attributes; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Framework.Dialogs; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; namespace CustomIdentify { /// <summary> /// Class to managed the related information for a given feature layer /// </summary> public class RelateInfo { private string _displayFieldName = ""; /// <summary> /// Finds all related children /// </summary> public HierarchyRow GetRelationshipChildren(Layer member, Geodatabase gdb, string featureClassName, long objectID, string rcException = "") { if (!QueuedTask.OnWorker) { throw new CalledOnWrongThreadException(); } string displayValue = ""; if (member != null) { if (string.IsNullOrEmpty(_displayFieldName)) { CIMFeatureLayer currentCIMFeatureLayer = member.GetDefinition() as CIMFeatureLayer; _displayFieldName = currentCIMFeatureLayer?.FeatureTable.DisplayField ?? ""; } var inspector = new Inspector(); inspector.Load(member, objectID); if (!string.IsNullOrEmpty(_displayFieldName)) { displayValue = $"{inspector[_displayFieldName]?.ToString() ?? ""}"; } } //Did the display value get set? if (string.IsNullOrEmpty(displayValue)) displayValue = $"OID: {objectID.ToString()}"; var newHRow = new HierarchyRow() { name = displayValue, type = $"{featureClassName}" }; //Check the layer for any relationships var children = GetRelationshipChildrenFromLayer(member as BasicFeatureLayer, objectID); if (children.Count > 0) { newHRow.children = children; return newHRow;//Give layer related precedence over GDB related } //If we are here we do not have any relates on the layer //See if we have relates in the GDB var relationshipClassDefinitions = GetRelationshipClassDefinitionsFromFeatureClass(gdb, featureClassName); foreach (var relationshipClassDefinition in relationshipClassDefinitions) { var rcName = relationshipClassDefinition.GetName(); //get the name if (rcException == rcName) //exception so we don't go in circles continue; //Alternate way of getting the features classes in the relationship (new at 1.3): //IReadOnlyList<Definition> definitions = GetRelatedDefinitions(relationshipClassDefinition, DefinitionRelationshipType.DatasetsRelatedThrough); var relationshipClass = gdb.OpenDataset<RelationshipClass>(rcName); //open the relationship class var origin = relationshipClassDefinition.GetOriginClass(); //get the origin of the relationship class var destination = relationshipClassDefinition.GetDestinationClass(); //get the destination of the relationship class string displayName; if (origin == featureClassName) { //the feature class is the origin. So we need the rows in the destination related to the origin var oids = new List<long> { objectID }; IReadOnlyList<Row> relatedOriginRows = relationshipClass.GetRowsRelatedToOriginRows(oids); if (relatedOriginRows.Count > 0) { displayName = string.Format("{0}: {1}", rcName, destination); var childHRow = new HierarchyRow() { name = displayName, type = rcName }; foreach (var row in relatedOriginRows) { //var lyr = GetRelationshipClassDefinitionsFromFeatureClass(); //childHRow.children.Add(GetRelationshipChildren(lyr, gdb, destination, row.GetObjectID(), rcName)); //recursive: to get the attributes of the related feature } newHRow.children.Add(childHRow); continue; } } IReadOnlyList<Row> relatedDestinationRows = relationshipClass.GetRowsRelatedToDestinationRows(new List<long> { objectID }); //Feature class is the destination so get the rows related to it if (relatedDestinationRows.Count > 0) { displayName = string.Format("{0}: {1}", rcName, origin); var childHRow = new HierarchyRow() { name = displayName, type = rcName }; foreach (var row in relatedDestinationRows) { //childHRow.children.Add(GetRelationshipChildren(null, gdb, origin, row.GetObjectID(), rcName)); } newHRow.children.Add(childHRow); } } return newHRow; } internal List<HierarchyRow> GetRelationshipChildrenFromLayer(BasicFeatureLayer member, long objectID) { var children = new List<HierarchyRow>(); CIMBasicFeatureLayer bfl = member.GetDefinition() as CIMBasicFeatureLayer; var relates = bfl.FeatureTable.Relates; if (relates == null || relates.Length == 0) return children; foreach (var relate in relates) { if (!(relate.DataConnection is CIMStandardDataConnection) && !(relate.DataConnection is CIMFeatureDatasetDataConnection)) continue;//Not supported in this sample var sdc = relate.DataConnection as CIMStandardDataConnection; var fdc = relate.DataConnection as CIMFeatureDatasetDataConnection; var factory = sdc?.WorkspaceFactory ?? fdc.WorkspaceFactory; var path = sdc?.WorkspaceConnectionString ?? fdc.WorkspaceConnectionString; if (string.IsNullOrEmpty(path)) continue;//No connection information we can use path = path.Replace("DATABASE=", ""); var dstype = sdc?.DatasetType ?? fdc.DatasetType; if (dstype != esriDatasetType.esriDTFeatureClass && dstype != esriDatasetType.esriDTTable) { continue;//Not supported in the sample } var dsname = sdc?.Dataset ?? fdc.Dataset; var featDatasetName = fdc?.FeatureDataset ?? ""; Geodatabase gdb = null; if (factory == WorkspaceFactory.FileGDB) { gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(path, UriKind.Absolute))); } else if (factory == WorkspaceFactory.SDE) { gdb = new Geodatabase(new DatabaseConnectionFile(new Uri(path, UriKind.Absolute))); } Table table = null; //We have to open a type specific dataset - FeatureClass or Table //We cannot simply use 'Table' for both if (dstype == esriDatasetType.esriDTFeatureClass) { table = GetDatasetFromGeodatabase<FeatureClass>(gdb, dsname, featDatasetName); } else { table = GetDatasetFromGeodatabase<Table>(gdb, dsname, featDatasetName); } if (table == null) continue;//Related dataset not found //Get any related rows var qry_fld = table.GetDefinition().GetFields().FirstOrDefault(f => f.Name == relate.ForeignKey); if (qry_fld == null) continue;//We cannot find the designated foreign key //Load relevant values var inspector = new Inspector(); inspector.Load(member, objectID); var need_quotes = qry_fld.FieldType == FieldType.String; var quote = need_quotes ? "'" : ""; var where = $"{relate.ForeignKey} = {quote}{inspector[relate.PrimaryKey]}{quote}"; var qf = new QueryFilter() { WhereClause = where, SubFields = $"{table.GetDefinition().GetObjectIDField()}, {relate.ForeignKey}" }; var childHRow = new HierarchyRow() { name = dsname, type = $"{inspector[relate.PrimaryKey]}" }; using (var rc = table.Search(qf)) { while (rc.MoveNext()) { using (var row = rc.Current) { var id = row.GetObjectID(); var HRow = new HierarchyRow() { name = $"{id}", type = relate.ForeignKey }; childHRow.children.Add(HRow); } } } children.Add(childHRow); } return children; } private T GetDatasetFromGeodatabase<T>(Geodatabase gdb, string dataset, string featureDataset) where T : Table { if (!string.IsNullOrEmpty(featureDataset)) { var fd = gdb.OpenDataset<FeatureDataset>(featureDataset); if (fd != null) { return fd.OpenDataset<T>(dataset); } } return gdb.OpenDataset<T>(dataset); } private IEnumerable<RelationshipClassDefinition> GetRelationshipClassDefinitionsFromFeatureClass( Geodatabase gdb, string featureClassName) { return gdb.GetDefinitions<RelationshipClassDefinition>(). Where(defn => defn.GetOriginClass().Equals(featureClassName) || defn.GetDestinationClass().Equals(featureClassName)); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Timers; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework.Monitoring.Interfaces; namespace OpenSim.Framework.Monitoring { /// <summary> /// Collects sim statistics which aren't already being collected for the linden viewer's statistics pane /// </summary> public class SimExtraStatsCollector : BaseStatsCollector { // private long assetsInCache; // private long texturesInCache; // private long assetCacheMemoryUsage; // private long textureCacheMemoryUsage; // private TimeSpan assetRequestTimeAfterCacheMiss; // private long blockedMissingTextureRequests; // private long assetServiceRequestFailures; // private long inventoryServiceRetrievalFailures; private Ping m_externalPingSender; private Timer m_externalPingTimer; private string m_externalServerName; private double m_externalPingFreq; private double m_avgPing = 0.0; private bool m_pingCompleted; private const string m_defaultServerName = "www.google.com"; private const double m_pingFrequency = 3.0; private volatile float timeDilation; private volatile float simFps; private volatile float physicsFps; private volatile float agentUpdates; private volatile float rootAgents; private volatile float childAgents; private volatile float totalPrims; private volatile float activePrims; private volatile float totalFrameTime; private volatile float netFrameTime; private volatile float physicsFrameTime; private volatile float otherFrameTime; private volatile float imageFrameTime; private volatile float inPacketsPerSecond; private volatile float outPacketsPerSecond; private volatile float unackedBytes; private volatile float agentFrameTime; private volatile float pendingDownloads; private volatile float pendingUploads; private volatile float activeScripts; private volatile float scriptLinesPerSecond; private volatile float m_frameDilation; private volatile float m_usersLoggingIn; private volatile float m_totalGeoPrims; private volatile float m_totalMeshes; private volatile float m_inUseThreads; private volatile float m_inByteRate; private volatile float m_outByteRate; private volatile float m_errorPacketRate; private volatile float m_queueSize; private volatile float m_clientPing; // /// <summary> // /// These statistics are being collected by push rather than pull. Pull would be simpler, but I had the // /// notion of providing some flow statistics (which pull wouldn't give us). Though admittedly these // /// haven't yet been implemented... // /// </summary> // public long AssetsInCache { get { return assetsInCache; } } // // /// <value> // /// Currently unused // /// </value> // public long TexturesInCache { get { return texturesInCache; } } // // /// <value> // /// Currently misleading since we can't currently subtract removed asset memory usage without a performance hit // /// </value> // public long AssetCacheMemoryUsage { get { return assetCacheMemoryUsage; } } // // /// <value> // /// Currently unused // /// </value> // public long TextureCacheMemoryUsage { get { return textureCacheMemoryUsage; } } public float TimeDilation { get { return timeDilation; } } public float SimFps { get { return simFps; } } public float PhysicsFps { get { return physicsFps; } } public float AgentUpdates { get { return agentUpdates; } } public float RootAgents { get { return rootAgents; } } public float ChildAgents { get { return childAgents; } } public float TotalPrims { get { return totalPrims; } } public float ActivePrims { get { return activePrims; } } public float TotalFrameTime { get { return totalFrameTime; } } public float NetFrameTime { get { return netFrameTime; } } public float PhysicsFrameTime { get { return physicsFrameTime; } } public float OtherFrameTime { get { return otherFrameTime; } } public float ImageFrameTime { get { return imageFrameTime; } } public float InPacketsPerSecond { get { return inPacketsPerSecond; } } public float OutPacketsPerSecond { get { return outPacketsPerSecond; } } public float UnackedBytes { get { return unackedBytes; } } public float AgentFrameTime { get { return agentFrameTime; } } public float PendingDownloads { get { return pendingDownloads; } } public float PendingUploads { get { return pendingUploads; } } public float ActiveScripts { get { return activeScripts; } } public float ScriptLinesPerSecond { get { return scriptLinesPerSecond; } } // /// <summary> // /// This is the time it took for the last asset request made in response to a cache miss. // /// </summary> // public TimeSpan AssetRequestTimeAfterCacheMiss { get { return assetRequestTimeAfterCacheMiss; } } // // /// <summary> // /// Number of persistent requests for missing textures we have started blocking from clients. To some extent // /// this is just a temporary statistic to keep this problem in view - the root cause of this lies either // /// in a mishandling of the reply protocol, related to avatar appearance or may even originate in graphics // /// driver bugs on clients (though this seems less likely). // /// </summary> // public long BlockedMissingTextureRequests { get { return blockedMissingTextureRequests; } } // // /// <summary> // /// Record the number of times that an asset request has failed. Failures are effectively exceptions, such as // /// request timeouts. If an asset service replies that a particular asset cannot be found, this is not counted // /// as a failure // /// </summary> // public long AssetServiceRequestFailures { get { return assetServiceRequestFailures; } } /// <summary> /// Number of known failures to retrieve avatar inventory from the inventory service. This does not /// cover situations where the inventory service accepts the request but never returns any data, since /// we do not yet timeout this situation. /// </summary> /// <remarks>Commented out because we do not cache inventory at this point</remarks> // public long InventoryServiceRetrievalFailures { get { return inventoryServiceRetrievalFailures; } } /// <summary> /// Retrieve the total frame time (in ms) of the last frame /// </summary> //public float TotalFrameTime { get { return totalFrameTime; } } /// <summary> /// Retrieve the physics update component (in ms) of the last frame /// </summary> //public float PhysicsFrameTime { get { return physicsFrameTime; } } /// <summary> /// Retain a dictionary of all packet queues stats reporters /// </summary> private IDictionary<UUID, PacketQueueStatsCollector> packetQueueStatsCollectors = new Dictionary<UUID, PacketQueueStatsCollector>(); /// <summary> /// List of various statistical data of connected agents. /// </summary> private List<AgentSimData> agentList = new List<AgentSimData>(); public SimExtraStatsCollector() { // Default constructor } public SimExtraStatsCollector(IConfigSource config) { // Acquire the statistics section of the OpenSim.ini file and check to see if it // exists IConfig statsConfig = config.Configs["Statistics"]; if (statsConfig != null) { // Check if the configuration enables pinging the external server; disabled // by default bool pingServer = statsConfig.GetBoolean("PingExternalServerEnabled", false); // Get the rest of the values, for ping requests, if enabled if (pingServer) { // Get the name for the external server to ping and the frequency to ping it; use // the default constant values of neither were found in the configuration m_externalServerName = statsConfig.GetString("ExternalServer", m_defaultServerName); m_externalPingFreq = statsConfig.GetDouble("ExternalPingFrequency", m_pingFrequency); // Begin pinging the external server StartPingRequests(); } } } ~SimExtraStatsCollector() { // Stop the timer to ping the external server if (m_externalPingTimer != null) m_externalPingTimer.Stop(); } // public void AddAsset(AssetBase asset) // { // assetsInCache++; // //assetCacheMemoryUsage += asset.Data.Length; // } // // public void RemoveAsset(UUID uuid) // { // assetsInCache--; // } // // public void AddTexture(AssetBase image) // { // if (image.Data != null) // { // texturesInCache++; // // // This could have been a pull stat, though there was originally a nebulous idea to measure flow rates // textureCacheMemoryUsage += image.Data.Length; // } // } // // /// <summary> // /// Signal that the asset cache has been cleared. // /// </summary> // public void ClearAssetCacheStatistics() // { // assetsInCache = 0; // assetCacheMemoryUsage = 0; // texturesInCache = 0; // textureCacheMemoryUsage = 0; // } // // public void AddAssetRequestTimeAfterCacheMiss(TimeSpan ts) // { // assetRequestTimeAfterCacheMiss = ts; // } // // public void AddBlockedMissingTextureRequest() // { // blockedMissingTextureRequests++; // } // // public void AddAssetServiceRequestFailure() // { // assetServiceRequestFailures++; // } // public void AddInventoryServiceRetrievalFailure() // { // inventoryServiceRetrievalFailures++; // } public void AddAgent(string name, string ipAddress, string timestamp) { // Save new agent data to the list of connected agents AgentSimData agentSimData = new AgentSimData(name, ipAddress, timestamp); agentList.Add(agentSimData); } public void RemoveAgent(string name) { // Search for the agent being removed in the list of agents currently connected to the server foreach (AgentSimData agent in agentList) { // Check if the given name matches the current one in the list if (agent.Name.CompareTo(name) == 0) { // Agent found, so remove them from the list and exit agentList.Remove(agent); return; } } } /// <summary> /// Register as a packet queue stats provider /// </summary> /// <param name="uuid">An agent UUID</param> /// <param name="provider"></param> public void RegisterPacketQueueStatsProvider(UUID uuid, IPullStatsProvider provider) { lock (packetQueueStatsCollectors) { // FIXME: If the region service is providing more than one region, then the child and root agent // queues are wrongly replacing each other here. packetQueueStatsCollectors[uuid] = new PacketQueueStatsCollector(provider); } } /// <summary> /// Deregister a packet queue stats provider /// </summary> /// <param name="uuid">An agent UUID</param> public void DeregisterPacketQueueStatsProvider(UUID uuid) { lock (packetQueueStatsCollectors) { packetQueueStatsCollectors.Remove(uuid); } } /// <summary> /// This is the method on which the classic sim stats reporter (which collects stats for /// client purposes) sends information to listeners. /// </summary> /// <param name="pack"></param> public void ReceiveClassicSimStatsPacket(SimStats stats) { // FIXME: SimStats shouldn't allow an arbitrary stat packing order (which is inherited from the original // SimStatsPacket that was being used). // For an unknown reason the original designers decided not to // include the spare MS statistic inside of this class, this is // located inside the StatsBlock at location 21, thus it is skipped timeDilation = stats.StatsBlock[0].StatValue; simFps = stats.StatsBlock[1].StatValue; physicsFps = stats.StatsBlock[2].StatValue; agentUpdates = stats.StatsBlock[3].StatValue; rootAgents = stats.StatsBlock[4].StatValue; childAgents = stats.StatsBlock[5].StatValue; totalPrims = stats.StatsBlock[6].StatValue; activePrims = stats.StatsBlock[7].StatValue; totalFrameTime = stats.StatsBlock[8].StatValue; netFrameTime = stats.StatsBlock[9].StatValue; physicsFrameTime = stats.StatsBlock[10].StatValue; otherFrameTime = stats.StatsBlock[11].StatValue; imageFrameTime = stats.StatsBlock[12].StatValue; inPacketsPerSecond = stats.StatsBlock[13].StatValue; outPacketsPerSecond = stats.StatsBlock[14].StatValue; unackedBytes = stats.StatsBlock[15].StatValue; agentFrameTime = stats.StatsBlock[16].StatValue; pendingDownloads = stats.StatsBlock[17].StatValue; pendingUploads = stats.StatsBlock[18].StatValue; activeScripts = stats.StatsBlock[19].StatValue; scriptLinesPerSecond = stats.StatsBlock[20].StatValue; m_frameDilation = stats.StatsBlock[22].StatValue; m_usersLoggingIn = stats.StatsBlock[23].StatValue; m_totalGeoPrims = stats.StatsBlock[24].StatValue; m_totalMeshes = stats.StatsBlock[25].StatValue; m_inUseThreads = stats.StatsBlock[26].StatValue; m_inByteRate = stats.StatsBlock[27].StatValue; m_outByteRate = stats.StatsBlock[28].StatValue; m_errorPacketRate = stats.StatsBlock[29].StatValue; m_queueSize = stats.StatsBlock[30].StatValue; m_clientPing = stats.StatsBlock[31].StatValue; } /// <summary> /// Report back collected statistical information. /// </summary> /// <returns></returns> public override string Report() { StringBuilder sb = new StringBuilder(Environment.NewLine); // sb.Append("ASSET STATISTICS"); // sb.Append(Environment.NewLine); /* sb.Append( string.Format( @"Asset cache contains {0,6} non-texture assets using {1,10} K Texture cache contains {2,6} texture assets using {3,10} K Latest asset request time after cache miss: {4}s Blocked client requests for missing textures: {5} Asset service request failures: {6}"+ Environment.NewLine, AssetsInCache, Math.Round(AssetCacheMemoryUsage / 1024.0), TexturesInCache, Math.Round(TextureCacheMemoryUsage / 1024.0), assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0, BlockedMissingTextureRequests, AssetServiceRequestFailures)); */ /* sb.Append( string.Format( @"Asset cache contains {0,6} assets Latest asset request time after cache miss: {1}s Blocked client requests for missing textures: {2} Asset service request failures: {3}" + Environment.NewLine, AssetsInCache, assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0, BlockedMissingTextureRequests, AssetServiceRequestFailures)); */ sb.Append(Environment.NewLine); sb.Append("CONNECTION STATISTICS"); sb.Append(Environment.NewLine); List<Stat> stats = StatsManager.GetStatsFromEachContainer("clientstack", "ClientLogoutsDueToNoReceives"); sb.AppendFormat( "Client logouts due to no data receive timeout: {0}\n\n", stats != null ? stats.Sum(s => s.Value).ToString() : "unknown"); // sb.Append(Environment.NewLine); // sb.Append("INVENTORY STATISTICS"); // sb.Append(Environment.NewLine); // sb.Append( // string.Format( // "Initial inventory caching failures: {0}" + Environment.NewLine, // InventoryServiceRetrievalFailures)); sb.Append(Environment.NewLine); sb.Append("SAMPLE FRAME STATISTICS"); sb.Append(Environment.NewLine); sb.Append("Dilatn SimFPS PhyFPS AgntUp RootAg ChldAg Prims AtvPrm AtvScr ScrLPS"); sb.Append(Environment.NewLine); sb.Append( string.Format( "{0,6:0.00} {1,6:0} {2,6:0.0} {3,6:0.0} {4,6:0} {5,6:0} {6,6:0} {7,6:0} {8,6:0} {9,6:0}", timeDilation, simFps, physicsFps, agentUpdates, rootAgents, childAgents, totalPrims, activePrims, activeScripts, scriptLinesPerSecond)); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); // There is no script frame time currently because we don't yet collect it sb.Append("PktsIn PktOut PendDl PendUl UnackB TotlFt NetFt PhysFt OthrFt AgntFt ImgsFt"); sb.Append(Environment.NewLine); sb.Append( string.Format( "{0,6:0} {1,6:0} {2,6:0} {3,6:0} {4,6:0} {5,6:0.0} {6,6:0.0} {7,6:0.0} {8,6:0.0} {9,6:0.0} {10,6:0.0}\n\n", inPacketsPerSecond, outPacketsPerSecond, pendingDownloads, pendingUploads, unackedBytes, totalFrameTime, netFrameTime, physicsFrameTime, otherFrameTime, agentFrameTime, imageFrameTime)); /* 20130319 RA: For the moment, disable the dump of 'scene' catagory as they are mostly output by * the two formatted printouts above. SortedDictionary<string, SortedDictionary<string, Stat>> sceneStats; if (StatsManager.TryGetStats("scene", out sceneStats)) { foreach (KeyValuePair<string, SortedDictionary<string, Stat>> kvp in sceneStats) { foreach (Stat stat in kvp.Value.Values) { if (stat.Verbosity == StatVerbosity.Info) { sb.AppendFormat("{0} ({1}): {2}{3}\n", stat.Name, stat.Container, stat.Value, stat.UnitName); } } } } */ /* sb.Append(Environment.NewLine); sb.Append("PACKET QUEUE STATISTICS"); sb.Append(Environment.NewLine); sb.Append("Agent UUID "); sb.Append( string.Format( " {0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}", "Send", "In", "Out", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset")); sb.Append(Environment.NewLine); foreach (UUID key in packetQueueStatsCollectors.Keys) { sb.Append(string.Format("{0}: ", key)); sb.Append(packetQueueStatsCollectors[key].Report()); sb.Append(Environment.NewLine); } */ sb.Append(base.Report()); return sb.ToString(); } /// <summary> /// Report back collected statistical information as json serialization. /// </summary> /// <returns></returns> public override string XReport(string uptime, string version) { return OSDParser.SerializeJsonString(OReport(uptime, version)); } /// <summary> /// Report back collected statistical information as an OSDMap /// </summary> /// <returns></returns> public override OSDMap OReport(string uptime, string version) { // Get the amount of physical memory, allocated with the instance of this program, in kilobytes; // the working set is the set of memory pages currently visible to this program in physical RAM // memory and includes both shared (e.g. system libraries) and private data double memUsage = Process.GetCurrentProcess().WorkingSet64 / 1024.0; // Get the number of threads from the system that are currently // running int numberThreadsRunning = 0; foreach (ProcessThread currentThread in Process.GetCurrentProcess().Threads) { // A known issue with the current .Threads property is that it // can return null threads, thus don't count those as running // threads and prevent the program function from failing if (currentThread != null && currentThread.ThreadState == ThreadState.Running) { numberThreadsRunning++; } } OSDMap args = new OSDMap(30); // args["AssetsInCache"] = OSD.FromString (String.Format ("{0:0.##}", AssetsInCache)); // args["TimeAfterCacheMiss"] = OSD.FromString (String.Format ("{0:0.##}", // assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0)); // args["BlockedMissingTextureRequests"] = OSD.FromString (String.Format ("{0:0.##}", // BlockedMissingTextureRequests)); // args["AssetServiceRequestFailures"] = OSD.FromString (String.Format ("{0:0.##}", // AssetServiceRequestFailures)); // args["abnormalClientThreadTerminations"] = OSD.FromString (String.Format ("{0:0.##}", // abnormalClientThreadTerminations)); // args["InventoryServiceRetrievalFailures"] = OSD.FromString (String.Format ("{0:0.##}", // InventoryServiceRetrievalFailures)); args["Dilatn"] = OSD.FromString (String.Format ("{0:0.##}", timeDilation)); args["SimFPS"] = OSD.FromString (String.Format ("{0:0.##}", simFps)); args["PhyFPS"] = OSD.FromString (String.Format ("{0:0.##}", physicsFps)); args["AgntUp"] = OSD.FromString (String.Format ("{0:0.##}", agentUpdates)); args["RootAg"] = OSD.FromString (String.Format ("{0:0.##}", rootAgents)); args["ChldAg"] = OSD.FromString (String.Format ("{0:0.##}", childAgents)); args["Prims"] = OSD.FromString (String.Format ("{0:0.##}", totalPrims)); args["AtvPrm"] = OSD.FromString (String.Format ("{0:0.##}", activePrims)); args["AtvScr"] = OSD.FromString (String.Format ("{0:0.##}", activeScripts)); args["ScrLPS"] = OSD.FromString (String.Format ("{0:0.##}", scriptLinesPerSecond)); args["PktsIn"] = OSD.FromString (String.Format ("{0:0.##}", inPacketsPerSecond)); args["PktOut"] = OSD.FromString (String.Format ("{0:0.##}", outPacketsPerSecond)); args["PendDl"] = OSD.FromString (String.Format ("{0:0.##}", pendingDownloads)); args["PendUl"] = OSD.FromString (String.Format ("{0:0.##}", pendingUploads)); args["UnackB"] = OSD.FromString (String.Format ("{0:0.##}", unackedBytes)); args["TotlFt"] = OSD.FromString (String.Format ("{0:0.##}", totalFrameTime)); args["NetEvtTime"] = OSD.FromString (String.Format ("{0:0.##}", netFrameTime)); args["NetQSize"] = OSD.FromString(String.Format("{0:0.##}", m_queueSize)); args["PhysFt"] = OSD.FromString (String.Format ("{0:0.##}", physicsFrameTime)); args["OthrFt"] = OSD.FromString (String.Format ("{0:0.##}", otherFrameTime)); args["AgntFt"] = OSD.FromString (String.Format ("{0:0.##}", agentFrameTime)); args["ImgsFt"] = OSD.FromString (String.Format ("{0:0.##}", imageFrameTime)); args["Memory"] = OSD.FromString (base.XReport (uptime, version)); args["Uptime"] = OSD.FromString (uptime); args["Version"] = OSD.FromString (version); args["FrameDilatn"] = OSD.FromString(String.Format("{0:0.##}", m_frameDilation)); args["Logging in Users"] = OSD.FromString(String.Format("{0:0.##}", m_usersLoggingIn)); args["GeoPrims"] = OSD.FromString(String.Format("{0:0.##}", m_totalGeoPrims)); args["Mesh Objects"] = OSD.FromString(String.Format("{0:0.##}", m_totalMeshes)); args["XEngine Thread Count"] = OSD.FromString(String.Format("{0:0.##}", m_inUseThreads)); args["Util Thread Count"] = OSD.FromString(String.Format("{0:0.##}", Util.GetSmartThreadPoolInfo().InUseThreads)); args["System Thread Count"] = OSD.FromString(String.Format( "{0:0.##}", numberThreadsRunning)); args["ProcMem"] = OSD.FromString(String.Format("{0:#,###,###.##}", memUsage)); args["UDPIn"] = OSD.FromString(String.Format("{0:0.##}", m_inByteRate)); args["UDPOut"] = OSD.FromString(String.Format("{0:0.##}", m_outByteRate)); args["UDPInError"] = OSD.FromString(String.Format("{0:0.##}", m_errorPacketRate)); args["ClientPing"] = OSD.FromString(String.Format("{0:0.##}", m_clientPing)); args["AvgPing"] = OSD.FromString(String.Format("{0:0.######}", m_avgPing)); return args; } /// <summary> /// Report back collected statistical information, of all connected agents, as a json serialization. /// </summary> /// <param name="uptime">Time that server has been running</param> /// <param name="version">Current version of OpenSim</param> /// <returns>JSON string of agent login data</returns> public string AgentReport(string uptime, string version) { // Create new OSDMap to hold the agent data OSDMap args = new OSDMap(agentList.Count); // Go through the list of connected agents foreach (AgentSimData agent in agentList) { // Add the agent statistical data (name, IP, and login time) to the OSDMap args[agent.Name] = OSD.FromString( String.Format("{0} | Login: {1}", agent.IPAddress, agent.Timestamp)); } // Add the given uptime and OpenSim version to the OSDMap args["Uptime"] = OSD.FromString(uptime); args["Version"] = OSD.FromString(version); // Serialize the OSDMap, that was just created, to JSON format and // return it return OSDParser.SerializeJsonString(args); } private void StartPingRequests() { // Create new object to allow for pinging an external server; add the PingCompletedCallback as // one of the methods to be called when the PingCompleted delegate is invoked (the // PingCompleted literally tracks which methods to call when it is called) m_externalPingSender = new Ping(); m_externalPingSender.PingCompleted += PingCompletedCallback; // Create timer to continually ping connected clients, within the specified frequency; add the // PingExternal method as one of the methods to be called when the Timer's Elapsed delegate is // invoked (Elapsed tracks the methods to call when it is called) m_externalPingTimer = new Timer(m_externalPingFreq * 1000); m_externalPingTimer.AutoReset = true; m_externalPingTimer.Elapsed += PingExternal; // Start the timer to ping the external server m_pingCompleted = true; m_externalPingTimer.Start(); } private void PingCompletedCallback(object sender, PingCompletedEventArgs e) { // Get the ping time if request succeeded, otherwise save a // value of -1 to indicate failure if (e.Reply.Status == IPStatus.Success) m_avgPing = e.Reply.RoundtripTime; else m_avgPing = -1; // Indicate that ping to external server has completed m_pingCompleted = true; } private void PingExternal(object sender, ElapsedEventArgs e) { // Make sure that there is no pending ping if (m_pingCompleted) { // Asynchronously send a ping to the designated external server's address m_externalPingSender.SendAsync(m_externalServerName, null); // Indicate that a ping was just sent m_pingCompleted = false; } } } /// <summary> /// Pull packet queue stats from packet queues and report /// </summary> public class PacketQueueStatsCollector : IStatsCollector { private IPullStatsProvider m_statsProvider; public PacketQueueStatsCollector(IPullStatsProvider provider) { m_statsProvider = provider; } /// <summary> /// Report back collected statistical information. /// </summary> /// <returns></returns> public string Report() { return m_statsProvider.GetStats(); } public string XReport(string uptime, string version) { return ""; } public OSDMap OReport(string uptime, string version) { OSDMap ret = new OSDMap(); return ret; } } public class AgentSimData { private string m_agentName; private string m_agentIPAddress; private string m_loginTimestamp; public AgentSimData(string name, string ipAddress, string loginTimestamp) { // Save the given agent data: their name, IP address, and login timestamp m_agentName = name; m_agentIPAddress = ipAddress; m_loginTimestamp = loginTimestamp; } public string Name { get { return m_agentName; } } public string IPAddress { get { return m_agentIPAddress; } } public string Timestamp { get { return m_loginTimestamp; } } } }
// 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.ObjectModel; using System.Diagnostics.Contracts; using System.Runtime; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal abstract class ConnectionOrientedTransportChannelFactory<TChannel> : TransportChannelFactory<TChannel>, IConnectionOrientedTransportChannelFactorySettings { private IConnectionInitiator _connectionInitiator; private ConnectionPool _connectionPool; private bool _exposeConnectionProperty; private int _maxOutboundConnectionsPerEndpoint; private ISecurityCapabilities _securityCapabilities; private StreamUpgradeProvider _upgrade; private bool _flowIdentity; internal ConnectionOrientedTransportChannelFactory( ConnectionOrientedTransportBindingElement bindingElement, BindingContext context, string connectionPoolGroupName, TimeSpan idleTimeout, int maxOutboundConnectionsPerEndpoint, bool supportsImpersonationDuringAsyncOpen) : base(bindingElement, context) { if (bindingElement.TransferMode == TransferMode.Buffered && bindingElement.MaxReceivedMessageSize > int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize", SR.MaxReceivedMessageSizeMustBeInIntegerRange)); } ConnectionBufferSize = bindingElement.ConnectionBufferSize; ConnectionPoolGroupName = connectionPoolGroupName; _exposeConnectionProperty = bindingElement.ExposeConnectionProperty; IdleTimeout = idleTimeout; MaxBufferSize = bindingElement.MaxBufferSize; _maxOutboundConnectionsPerEndpoint = maxOutboundConnectionsPerEndpoint; MaxOutputDelay = bindingElement.MaxOutputDelay; TransferMode = bindingElement.TransferMode; Collection<StreamUpgradeBindingElement> upgradeBindingElements = context.BindingParameters.FindAll<StreamUpgradeBindingElement>(); if (upgradeBindingElements.Count > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.MultipleStreamUpgradeProvidersInParameters)); } else if ((upgradeBindingElements.Count == 1) && SupportsUpgrade(upgradeBindingElements[0])) { _upgrade = upgradeBindingElements[0].BuildClientStreamUpgradeProvider(context); context.BindingParameters.Remove<StreamUpgradeBindingElement>(); _securityCapabilities = upgradeBindingElements[0].GetProperty<ISecurityCapabilities>(context); // flow the identity only if the channel factory supports impersonating during an async open AND // there is the binding is configured with security _flowIdentity = supportsImpersonationDuringAsyncOpen; } // We explicitly declare this type and all derived types support // async open/close. We currently must do this because the NET Native // toolchain does not recognize this type was granted Reflection degree. // Is it safe to do this only because this is an internal type and no // derived type is public or exposed in contract. SupportsAsyncOpenClose = true; } public int ConnectionBufferSize { get; } internal IConnectionInitiator ConnectionInitiator { get { if (_connectionInitiator == null) { lock (ThisLock) { if (_connectionInitiator == null) { _connectionInitiator = GetConnectionInitiator(); } } } return _connectionInitiator; } } public string ConnectionPoolGroupName { get; } public TimeSpan IdleTimeout { get; } public int MaxBufferSize { get; } public int MaxOutboundConnectionsPerEndpoint { get { return _maxOutboundConnectionsPerEndpoint; } } public TimeSpan MaxOutputDelay { get; } public StreamUpgradeProvider Upgrade { get { StreamUpgradeProvider localUpgrade = _upgrade; CommunicationObjectInternal.ThrowIfDisposed(this); return localUpgrade; } } public TransferMode TransferMode { get; } int IConnectionOrientedTransportFactorySettings.MaxBufferSize { get { return MaxBufferSize; } } TransferMode IConnectionOrientedTransportFactorySettings.TransferMode { get { return TransferMode; } } StreamUpgradeProvider IConnectionOrientedTransportFactorySettings.Upgrade { get { return Upgrade; } } public override T GetProperty<T>() { if (typeof(T) == typeof(ISecurityCapabilities)) { return (T)(object)_securityCapabilities; } T result = base.GetProperty<T>(); if (result == null && _upgrade != null) { result = _upgrade.GetProperty<T>(); } return result; } public override int GetMaxBufferSize() { return MaxBufferSize; } internal abstract IConnectionInitiator GetConnectionInitiator(); internal abstract ConnectionPool GetConnectionPool(); internal abstract void ReleaseConnectionPool(ConnectionPool pool, TimeSpan timeout); protected override TChannel OnCreateChannel(EndpointAddress address, Uri via) { base.ValidateScheme(via); if (TransferMode == TransferMode.Buffered) { // typeof(TChannel) == typeof(IDuplexSessionChannel) return (TChannel)(object)new ClientFramingDuplexSessionChannel(this, this, address, via, ConnectionInitiator, _connectionPool, _exposeConnectionProperty, _flowIdentity); } // typeof(TChannel) == typeof(IRequestChannel) return (TChannel)(object)new StreamedFramingRequestChannel(this, this, address, via, ConnectionInitiator, _connectionPool); } private bool GetUpgradeAndConnectionPool(out StreamUpgradeProvider upgradeCopy, out ConnectionPool poolCopy) { if (_upgrade != null || _connectionPool != null) { lock (ThisLock) { if (_upgrade != null || _connectionPool != null) { upgradeCopy = _upgrade; poolCopy = _connectionPool; _upgrade = null; _connectionPool = null; return true; } } } upgradeCopy = null; poolCopy = null; return false; } protected override void OnAbort() { StreamUpgradeProvider localUpgrade; ConnectionPool localConnectionPool; if (GetUpgradeAndConnectionPool(out localUpgrade, out localConnectionPool)) { if (localConnectionPool != null) { ReleaseConnectionPool(localConnectionPool, TimeSpan.Zero); } if (localUpgrade != null) { localUpgrade.Abort(); } } } protected override void OnClose(TimeSpan timeout) { StreamUpgradeProvider localUpgrade; ConnectionPool localConnectionPool; if (GetUpgradeAndConnectionPool(out localUpgrade, out localConnectionPool)) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (localConnectionPool != null) { ReleaseConnectionPool(localConnectionPool, timeoutHelper.RemainingTime()); } if (localUpgrade != null) { localUpgrade.Close(timeoutHelper.RemainingTime()); } } } protected override void OnOpening() { base.OnOpening(); _connectionPool = GetConnectionPool(); // returns an already opened pool Contract.Assert(_connectionPool != null, "ConnectionPool should always be found"); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { throw ExceptionHelper.PlatformNotSupported("ConnectionOrientedTransportChannelFactory async open path"); } protected override void OnEndOpen(IAsyncResult result) { throw ExceptionHelper.PlatformNotSupported("ConnectionOrientedTransportChannelFactory async open path"); } protected override void OnOpen(TimeSpan timeout) { StreamUpgradeProvider localUpgrade = Upgrade; if (localUpgrade != null) { localUpgrade.Open(timeout); } } protected internal override async Task OnOpenAsync(TimeSpan timeout) { StreamUpgradeProvider localUpgrade = Upgrade; if (localUpgrade != null) { await ((IAsyncCommunicationObject)localUpgrade).OpenAsync(timeout); } } protected internal override async Task OnCloseAsync(TimeSpan timeout) { StreamUpgradeProvider localUpgrade; ConnectionPool localConnectionPool; if (GetUpgradeAndConnectionPool(out localUpgrade, out localConnectionPool)) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (localConnectionPool != null) { ReleaseConnectionPool(localConnectionPool, timeoutHelper.RemainingTime()); } if (localUpgrade != null) { await ((IAsyncCommunicationObject)localUpgrade).CloseAsync(timeoutHelper.RemainingTime()); } } } protected virtual bool SupportsUpgrade(StreamUpgradeBindingElement upgradeBindingElement) { return true; } } }
using System; using System.Runtime.InteropServices; using System.Drawing.Imaging; using System.Text; using PlatformAPI.Runtime.InteropServices.ComTypes; namespace PlatformAPI.GDIPlus { public static partial class NativeMethods { //---------------------------------------------------------------------------- // Image APIs //---------------------------------------------------------------------------- [DllImport("gdiplus")] public static extern GpStatus GdipLoadImageFromStream(IStream stream, out GpImage image); [DllImport("gdiplus")] public static extern GpStatus GdipLoadImageFromFile([MarshalAs(UnmanagedType.BStr)]string filename, out GpImage image); //[DllImport("gdiplus")] public static extern GpStatus //GdipLoadImageFromStreamICM(IStream* stream, out GpImage image); //[DllImport("gdiplus")] public static extern GpStatus //GdipLoadImageFromFileICM(string filename, out GpImage image); [DllImport("gdiplus")] public static extern GpStatus GdipCloneImage(GpImage image, out GpImage cloneImage); [DllImport("gdiplus")] public static extern GpStatus GdipDisposeImage(GpImage image); [DllImport("gdiplus")] public static extern GpStatus GdipSaveImageToFile(GpImage image, string filename, ref Guid clsidEncoder, EncoderParameters encoderParams); //[DllImport("gdiplus")] public static extern GpStatus //GdipSaveImageToStream(GpImage image, IStream* stream, // ref Guid clsidEncoder, // EncoderParameters* encoderParams); [DllImport("gdiplus")] public static extern GpStatus GdipSaveAdd(GpImage image, EncoderParameters encoderParams); [DllImport("gdiplus")] public static extern GpStatus GdipSaveAddImage(GpImage image, GpImage newImage, EncoderParameters encoderParams); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageGraphicsContext(GpImage image, out GpGraphics graphics); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageBounds(GpImage image, out GpRectF srcRect, out Unit srcUnit); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageBounds(GpImage image, float[] srcRect, Unit srcUnit); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageBounds(GpImage image, byte[] srcRect, Unit srcUnit); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageDimension(GpImage image, out float width, out float height); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageType(GpImage image, out ImageType type); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageWidth(GpImage image, out uint width); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageHeight(GpImage image, out uint height); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageHorizontalResolution(GpImage image, out float resolution); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageVerticalResolution(GpImage image, out float resolution); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageFlags(GpImage image, out uint flags); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageRawFormat(GpImage image, out Guid format); [DllImport("gdiplus")] public static extern GpStatus GdipGetImagePixelFormat(GpImage image, out PixelFormat format); [DllImport("gdiplus")] public static extern GpStatus GdipGetImageThumbnail(GpImage image, uint thumbWidth, uint thumbHeight, out GpImage thumbImage, IntPtr /*GetThumbnailImageAbort*/ callback, IntPtr callbackData); [DllImport("gdiplus")] public static extern GpStatus GdipGetEncoderParameterListSize(GpImage image, ref Guid clsidEncoder, out uint size); [DllImport("gdiplus")] public static extern GpStatus GdipGetEncoderParameterList(GpImage image, ref Guid clsidEncoder, uint size, EncoderParameters buffer); [DllImport("gdiplus")] public static extern GpStatus GdipImageGetFrameDimensionsCount(GpImage image, out uint count); [DllImport("gdiplus")] public static extern GpStatus GdipImageGetFrameDimensionsList(GpImage image, Guid[] dimensionIDs, uint count); [DllImport("gdiplus")] public static extern GpStatus GdipImageGetFrameCount(GpImage image, ref Guid dimensionID, out uint count); [DllImport("gdiplus")] public static extern GpStatus GdipImageSelectActiveFrame(GpImage image, ref Guid dimensionID, uint frameIndex); [DllImport("gdiplus")] public static extern GpStatus GdipImageRotateFlip(GpImage image, RotateFlipType rfType); //[DllImport("gdiplus")] public static extern GpStatus //GdipGetImagePalette(GpImage image, ColorPalette *palette, int size); //[DllImport("gdiplus")] public static extern GpStatus //GdipSetImagePalette(GpImage image, ColorPalette *palette); //[DllImport("gdiplus")] public static extern GpStatus //GdipGetImagePaletteSize(GpImage image, out int size); [DllImport("gdiplus")] public static extern GpStatus GdipGetPropertyCount(GpImage image, out uint numOfProperty); [DllImport("gdiplus")] public static extern GpStatus GdipGetPropertyIdList(GpImage image, uint numOfProperty, PROPID[] list); [DllImport("gdiplus")] public static extern GpStatus GdipGetPropertyItemSize(GpImage image, PROPID propId, out uint size); /* [DllImport("gdiplus")] public static extern GpStatus GdipGetPropertyItem(GpImage image, PROPID propId, uint propSize, PropertyItem* buffer); [DllImport("gdiplus")] public static extern GpStatus GdipGetPropertySize(GpImage image, out uint totalBufferSize, out uint numProperties); [DllImport("gdiplus")] public static extern GpStatus GdipGetAllPropertyItems(GpImage image, uint totalBufferSize, uint numProperties, PropertyItem* allItems); [DllImport("gdiplus")] public static extern GpStatus GdipRemovePropertyItem(GpImage image, PROPID propId); [DllImport("gdiplus")] public static extern GpStatus GdipSetPropertyItem(GpImage image, PropertyItem* item); [DllImport("gdiplus")] public static extern GpStatus GdipImageForceValidation(GpImage image); */ [DllImport("gdiplus")] public static extern GpStatus GdipDrawImage(GpGraphics graphics, GpImage image, float x, float y); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImageI(GpGraphics graphics, GpImage image, int x, int y); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImageRect(GpGraphics graphics, GpImage image, float x, float y, float width, float height); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImageRectI(GpGraphics graphics, GpImage image, int x, int y, int width, int height); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImagePoints(GpGraphics graphics, GpImage image, GpPointF[] dstpoints, int count); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImagePointsI(GpGraphics graphics, GpImage image, GpPoint[] dstpoints, int count); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImagePointRect(GpGraphics graphics, GpImage image, float x, float y, float srcx, float srcy, float srcwidth, float srcheight, Unit srcUnit); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImagePointRectI(GpGraphics graphics, GpImage image, int x, int y, int srcx, int srcy, int srcwidth, int srcheight, Unit srcUnit); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImageRectRect(GpGraphics graphics, GpImage image, float dstx, float dsty, float dstwidth, float dstheight, float srcx, float srcy, float srcwidth, float srcheight, Unit srcUnit, GpImageAttributes imageAttributes, IntPtr callback, IntPtr callbackData); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImageRectRectI(GpGraphics graphics, GpImage image, int dstx, int dsty, int dstwidth, int dstheight, int srcx, int srcy, int srcwidth, int srcheight, Unit srcUnit, GpImageAttributes imageAttributes, IntPtr callback, IntPtr callbackData); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImagePointsRect(GpGraphics graphics, GpImage image, GpPointF[] points, int count, float srcx, float srcy, float srcwidth, float srcheight, Unit srcUnit, GpImageAttributes imageAttributes, IntPtr callback, IntPtr callbackData); [DllImport("gdiplus")] public static extern GpStatus GdipDrawImagePointsRectI(GpGraphics graphics, GpImage image, GpPoint[] points, int count, int srcx, int srcy, int srcwidth, int srcheight, Unit srcUnit, GpImageAttributes imageAttributes, IntPtr callback, IntPtr callbackData); } }
using System; using System.Data; using Csla; using Csla.Data; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERCLevel; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B03_SubContinentColl (editable child list).<br/> /// This is a generated base class of <see cref="B03_SubContinentColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="B02_Continent"/> editable child object.<br/> /// The items of the collection are <see cref="B04_SubContinent"/> objects. /// </remarks> [Serializable] public partial class B03_SubContinentColl : BusinessListBase<B03_SubContinentColl, B04_SubContinent> { #region Collection Business Methods /// <summary> /// Removes a <see cref="B04_SubContinent"/> item from the collection. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to be removed.</param> public void Remove(int subContinent_ID) { foreach (var b04_SubContinent in this) { if (b04_SubContinent.SubContinent_ID == subContinent_ID) { Remove(b04_SubContinent); break; } } } /// <summary> /// Determines whether a <see cref="B04_SubContinent"/> item is in the collection. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param> /// <returns><c>true</c> if the B04_SubContinent is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int subContinent_ID) { foreach (var b04_SubContinent in this) { if (b04_SubContinent.SubContinent_ID == subContinent_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="B04_SubContinent"/> item is in the collection's DeletedList. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param> /// <returns><c>true</c> if the B04_SubContinent is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int subContinent_ID) { foreach (var b04_SubContinent in DeletedList) { if (b04_SubContinent.SubContinent_ID == subContinent_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="B04_SubContinent"/> item of the <see cref="B03_SubContinentColl"/> collection, based on item key properties. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID.</param> /// <returns>A <see cref="B04_SubContinent"/> object.</returns> public B04_SubContinent FindB04_SubContinentByParentProperties(int subContinent_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].SubContinent_ID.Equals(subContinent_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B03_SubContinentColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="B03_SubContinentColl"/> collection.</returns> internal static B03_SubContinentColl NewB03_SubContinentColl() { return DataPortal.CreateChild<B03_SubContinentColl>(); } /// <summary> /// Factory method. Loads a <see cref="B03_SubContinentColl"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="B03_SubContinentColl"/> object.</returns> internal static B03_SubContinentColl GetB03_SubContinentColl(SafeDataReader dr) { B03_SubContinentColl obj = new B03_SubContinentColl(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B03_SubContinentColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B03_SubContinentColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads all <see cref="B03_SubContinentColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; var args = new DataPortalHookArgs(dr); OnFetchPre(args); while (dr.Read()) { Add(B04_SubContinent.GetB04_SubContinent(dr)); } OnFetchPost(args); RaiseListChangedEvents = rlce; } /// <summary> /// Loads <see cref="B04_SubContinent"/> items on the B03_SubContinentObjects collection. /// </summary> /// <param name="collection">The grand parent <see cref="B01_ContinentColl"/> collection.</param> internal void LoadItems(B01_ContinentColl collection) { foreach (var item in this) { var obj = collection.FindB02_ContinentByParentProperties(item.parent_Continent_ID); var rlce = obj.B03_SubContinentObjects.RaiseListChangedEvents; obj.B03_SubContinentObjects.RaiseListChangedEvents = false; obj.B03_SubContinentObjects.Add(item); obj.B03_SubContinentObjects.RaiseListChangedEvents = rlce; } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.Common.Lib; using Google.Api.Ads.Common.Util; using System.Collections.Generic; using System.Xml; namespace Google.Api.Ads.Common.Logging { /// <summary> /// Listens to SOAP messages sent and received by this library. /// </summary> public abstract class TraceListener : SoapListener { /// <summary> /// The config class to be used with this class. /// </summary> private AppConfig config; /// <summary> /// The date and time provider. /// </summary> private DateTimeProvider dateTimeProvider; /// <summary> /// The ITraceWriter to use when writing SOAP messages. /// </summary> internal ITraceWriter TraceWriter { get; set; } /// <summary> /// Gets or sets the date and time provider. /// </summary> public DateTimeProvider DateTimeProvider { get { return dateTimeProvider; } set { dateTimeProvider = value; } } /// <summary> /// Gets the config class to be used with this class. /// </summary> public AppConfig Config { get { return config; } } /// <summary> /// Protected constructor. /// </summary> /// <param name="config">The config class.</param> protected TraceListener(AppConfig config) { this.config = config; this.dateTimeProvider = new DefaultDateTimeProvider(); this.TraceWriter = new DefaultTraceWriter(); } /// <summary> /// Initializes the listener for handling an API call. /// </summary> public void InitForCall() { } /// <summary> /// Handles the SOAP message. /// </summary> /// <param name="requestInfo">Request info.</param> /// <param name="responseInfo">Response info.</param> public virtual void HandleMessage(RequestInfo requestInfo, ResponseInfo responseInfo) { PerformLogging(requestInfo, responseInfo); } /// <summary> /// Cleans up any resources after an API call. /// </summary> public void CleanupAfterCall() { ContextStore.RemoveKey("SoapRequest"); ContextStore.RemoveKey("SoapResponse"); ContextStore.RemoveKey("FormattedSoapLog"); ContextStore.RemoveKey("FormattedRequestLog"); } /// <summary> /// Performs the SOAP and HTTP logging. /// </summary> /// <param name="request">The request information.</param> /// <param name="response">The response information.</param> private void PerformLogging(RequestInfo request, ResponseInfo response) { LogEntry logEntry = new LogEntry(config, dateTimeProvider, TraceWriter); PopulateRequestInfo(ref request); logEntry.LogRequest(request, GetFieldsToMask(), new SoapTraceFormatter()); PopulateResponseInfo(ref response); logEntry.LogResponse(response, GetFieldsToMask(), new SoapTraceFormatter()); logEntry.Flush(); ContextStore.AddKey("FormattedSoapLog", logEntry.DetailedLog); ContextStore.AddKey("FormattedRequestLog", logEntry.SummaryLog); } /// <summary> /// Gets a list of fields to be masked in xml logs. /// </summary> /// <returns>The list of fields to be masked.</returns> protected abstract ISet<string> GetFieldsToMask(); /// <summary> /// Parses the body of the request and populates fields in the request info. /// </summary> /// <param name="info">The request info for this SOAP call.</param> protected virtual void PopulateRequestInfo(ref RequestInfo info) { XmlDocument xDoc = XmlUtilities.CreateDocument(info.Body); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); // Retrieve method. XmlNode methodNode = xDoc.SelectSingleNode("soap:Envelope/soap:Body/*", xmlns); if (methodNode != null) { info.Method = methodNode.Name; } } /// <summary> /// Parses the body of the response and populates fields in the repsonse info. /// </summary> /// <param name="info">The response info for this SOAP call.</param> protected virtual void PopulateResponseInfo(ref ResponseInfo info) { XmlDocument xDoc = XmlUtilities.CreateDocument(info.Body); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); // Retrieve loggable headers. XmlNode headerNode = xDoc.SelectSingleNode("soap:Envelope/soap:Header/*", xmlns); if (headerNode != null && headerNode.Name == "ResponseHeader") { info.RequestId = RetrieveLoggableHeader(headerNode, "requestId"); long operations; if (long.TryParse(RetrieveLoggableHeader(headerNode, "operations"), out operations)) { info.OperationCount = operations; } long responseTime; if (long.TryParse(RetrieveLoggableHeader(headerNode, "responseTime"), out responseTime)) { info.ResponseTimeMs = responseTime; } } //Retrieve fault string (if one exists). XmlNode faultNode = xDoc.SelectSingleNode("soap:Envelope/soap:Body/soap:Fault/faultstring", xmlns); if (faultNode != null) { info.ErrorMessage = faultNode.InnerText; } } /// <summary> /// Returns a string containing the specified loggable headers, retrieved from the specified /// header XML node. /// </summary> /// <param name="headerNode">An XML node containing loggable headers.</param> /// <param name="loggableHeader">The loggable header to retrieve.</param> /// <returns>A string containing the specified loggable headers.</returns> private string RetrieveLoggableHeader(XmlNode headerNode, string loggableHeader) { string xPath = string.Format("descendant::*[local-name()='{0}']", loggableHeader); XmlNode childHeaderNode = headerNode.SelectSingleNode(xPath); if (childHeaderNode != null) { return childHeaderNode.InnerText; } return ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SwaggerEx.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.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using SoupToNuts.Final.WebApi.Areas.HelpPage.ModelDescriptions; using SoupToNuts.Final.WebApi.Areas.HelpPage.Models; namespace SoupToNuts.Final.WebApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcatQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Concatenates one data source with another. Order preservation is used to ensure /// the output is actually a concatenation -- i.e. one after the other. The only /// special synchronization required is to find the largest index N in the first data /// source so that the indices of elements in the second data source can be offset /// by adding N+1. This makes it appear to the order preservation infrastructure as /// though all elements in the second came after all elements in the first, which is /// precisely what we want. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class ConcatQueryOperator<TSource> : BinaryQueryOperator<TSource, TSource, TSource> { private readonly bool _prematureMergeLeft = false; // Whether to prematurely merge the left data source private readonly bool _prematureMergeRight = false; // Whether to prematurely merge the right data source //--------------------------------------------------------------------------------------- // Initializes a new concatenation operator. // // Arguments: // child - the child whose data we will reverse // internal ConcatQueryOperator(ParallelQuery<TSource> firstChild, ParallelQuery<TSource> secondChild) : base(firstChild, secondChild) { Debug.Assert(firstChild != null, "first child data source cannot be null"); Debug.Assert(secondChild != null, "second child data source cannot be null"); _outputOrdered = LeftChild.OutputOrdered || RightChild.OutputOrdered; _prematureMergeLeft = LeftChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); _prematureMergeRight = RightChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); if ((LeftChild.OrdinalIndexState == OrdinalIndexState.Indexable) && (RightChild.OrdinalIndexState == OrdinalIndexState.Indexable)) { SetOrdinalIndex(OrdinalIndexState.Indexable); } else { SetOrdinalIndex( ExchangeUtilities.Worse(OrdinalIndexState.Increasing, ExchangeUtilities.Worse(LeftChild.OrdinalIndexState, RightChild.OrdinalIndexState))); } } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { // We just open the children operators. QueryResults<TSource> leftChildResults = LeftChild.Open(settings, preferStriping); QueryResults<TSource> rightChildResults = RightChild.Open(settings, preferStriping); return ConcatQueryOperatorResults.NewResults(leftChildResults, rightChildResults, this, settings, preferStriping); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStream, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, bool preferStriping, QuerySettings settings) { // Prematurely merge the left results, if necessary if (_prematureMergeLeft) { ListQueryResults<TSource> leftStreamResults = ExecuteAndCollectResults(leftStream, leftStream.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> leftStreamInc = leftStreamResults.GetPartitionedStream(); WrapHelper<int, TRightKey>(leftStreamInc, rightStream, outputRecipient, settings, preferStriping); } else { Debug.Assert(!ExchangeUtilities.IsWorseThan(leftStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper<TLeftKey, TRightKey>(leftStream, rightStream, outputRecipient, settings, preferStriping); } } private void WrapHelper<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, QuerySettings settings, bool preferStriping) { // Prematurely merge the right results, if necessary if (_prematureMergeRight) { ListQueryResults<TSource> rightStreamResults = ExecuteAndCollectResults(rightStream, leftStreamInc.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> rightStreamInc = rightStreamResults.GetPartitionedStream(); WrapHelper2<TLeftKey, int>(leftStreamInc, rightStreamInc, outputRecipient); } else { Debug.Assert(!ExchangeUtilities.IsWorseThan(rightStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper2<TLeftKey, TRightKey>(leftStreamInc, rightStream, outputRecipient); } } private void WrapHelper2<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStreamInc, IPartitionedStreamRecipient<TSource> outputRecipient) { int partitionCount = leftStreamInc.PartitionCount; // Generate the shared data. IComparer<ConcatKey<TLeftKey, TRightKey>> comparer = ConcatKey<TLeftKey, TRightKey>.MakeComparer( leftStreamInc.KeyComparer, rightStreamInc.KeyComparer); var outputStream = new PartitionedStream<TSource, ConcatKey<TLeftKey, TRightKey>>(partitionCount, comparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ConcatQueryOperatorEnumerator<TLeftKey, TRightKey>(leftStreamInc[i], rightStreamInc[i]); } outputRecipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { return LeftChild.AsSequentialQuery(token).Concat(RightChild.AsSequentialQuery(token)); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for concatenating two data sources. // private sealed class ConcatQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TSource, ConcatKey<TLeftKey, TRightKey>> { private readonly QueryOperatorEnumerator<TSource, TLeftKey> _firstSource; // The first data source to enumerate. private readonly QueryOperatorEnumerator<TSource, TRightKey> _secondSource; // The second data source to enumerate. private bool _begunSecond; // Whether this partition has begun enumerating the second source yet. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal ConcatQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TLeftKey> firstSource, QueryOperatorEnumerator<TSource, TRightKey> secondSource) { Debug.Assert(firstSource != null); Debug.Assert(secondSource != null); _firstSource = firstSource; _secondSource = secondSource; } //--------------------------------------------------------------------------------------- // MoveNext advances to the next element in the output. While the first data source has // elements, this consists of just advancing through it. After this, all partitions must // synchronize at a barrier and publish the maximum index N. Finally, all partitions can // move on to the second data source, adding N+1 to indices in order to get the correct // index offset. // internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TSource currentElement, ref ConcatKey<TLeftKey, TRightKey> currentKey) { Debug.Assert(_firstSource != null); Debug.Assert(_secondSource != null); // If we are still enumerating the first source, fetch the next item. if (!_begunSecond) { // If elements remain, just return true and continue enumerating the left. TLeftKey leftKey = default(TLeftKey)!; if (_firstSource.MoveNext(ref currentElement!, ref leftKey)) { currentKey = ConcatKey<TLeftKey, TRightKey>.MakeLeft(leftKey); return true; } _begunSecond = true; } // Now either move on to, or continue, enumerating the right data source. TRightKey rightKey = default(TRightKey)!; if (_secondSource.MoveNext(ref currentElement!, ref rightKey)) { currentKey = ConcatKey<TLeftKey, TRightKey>.MakeRight(rightKey); return true; } return false; } protected override void Dispose(bool disposing) { _firstSource.Dispose(); _secondSource.Dispose(); } } //----------------------------------------------------------------------------------- // Query results for a Concat operator. The results are indexable if the child // results were indexable. // private class ConcatQueryOperatorResults : BinaryQueryOperatorResults { private readonly int _leftChildCount; // The number of elements in the left child result set private readonly int _rightChildCount; // The number of elements in the right child result set public static QueryResults<TSource> NewResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> op, QuerySettings settings, bool preferStriping) { if (leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible) { return new ConcatQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } else { return new BinaryQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } } private ConcatQueryOperatorResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> concatOp, QuerySettings settings, bool preferStriping) : base(leftChildQueryResults, rightChildQueryResults, concatOp, settings, preferStriping) { Debug.Assert(leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible); _leftChildCount = leftChildQueryResults.ElementsCount; _rightChildCount = rightChildQueryResults.ElementsCount; } internal override bool IsIndexible { get { return true; } } internal override int ElementsCount { get { Debug.Assert(_leftChildCount >= 0 && _rightChildCount >= 0); return _leftChildCount + _rightChildCount; } } internal override TSource GetElement(int index) { if (index < _leftChildCount) { return _leftChildQueryResults.GetElement(index); } else { return _rightChildQueryResults.GetElement(index - _leftChildCount); } } } } //--------------------------------------------------------------------------------------- // ConcatKey represents an ordering key for the Concat operator. It knows whether the // element it is associated with is from the left source or the right source, and also // the elements ordering key. // internal struct ConcatKey<TLeftKey, TRightKey> { private readonly TLeftKey _leftKey; private readonly TRightKey _rightKey; private readonly bool _isLeft; private ConcatKey([AllowNull] TLeftKey leftKey, [AllowNull] TRightKey rightKey, bool isLeft) { _leftKey = leftKey; _rightKey = rightKey; _isLeft = isLeft; } internal static ConcatKey<TLeftKey, TRightKey> MakeLeft([AllowNull] TLeftKey leftKey) { return new ConcatKey<TLeftKey, TRightKey>(leftKey, default, isLeft: true); } internal static ConcatKey<TLeftKey, TRightKey> MakeRight([AllowNull] TRightKey rightKey) { return new ConcatKey<TLeftKey, TRightKey>(default, rightKey, isLeft: false); } internal static IComparer<ConcatKey<TLeftKey, TRightKey>> MakeComparer( IComparer<TLeftKey> leftComparer, IComparer<TRightKey> rightComparer) { return new ConcatKeyComparer(leftComparer, rightComparer); } //--------------------------------------------------------------------------------------- // ConcatKeyComparer compares ConcatKeys, so that elements from the left source come // before elements from the right source, and elements within each source are ordered // according to the corresponding order key. // private class ConcatKeyComparer : IComparer<ConcatKey<TLeftKey, TRightKey>> { private readonly IComparer<TLeftKey> _leftComparer; private readonly IComparer<TRightKey> _rightComparer; internal ConcatKeyComparer(IComparer<TLeftKey> leftComparer, IComparer<TRightKey> rightComparer) { _leftComparer = leftComparer; _rightComparer = rightComparer; } public int Compare(ConcatKey<TLeftKey, TRightKey> x, ConcatKey<TLeftKey, TRightKey> y) { // If one element is from the left source and the other not, the element from the left source // comes earlier. if (x._isLeft != y._isLeft) { return x._isLeft ? -1 : 1; } // Elements are from the same source (left or right). Compare the corresponding keys. if (x._isLeft) { return _leftComparer.Compare(x._leftKey, y._leftKey); } return _rightComparer.Compare(x._rightKey, y._rightKey); } } } }
//--------------------------------------------------------------------------- // // (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Limited Permissive License. // See http://www.microsoft.com/resources/sharedsource/licensingbasics/limitedpermissivelicense.mspx // All other rights reserved. // // This file is part of the 3D Tools for Windows Presentation Foundation // project. For more information, see: // // http://CodePlex.com/Wiki/View.aspx?ProjectName=3DTools // // The following article discusses the mechanics behind this // trackball implementation: http://viewport3d.com/trackball.htm // // Reading the article is not required to use this sample code, // but skimming it might be useful. // //--------------------------------------------------------------------------- using System; using System.Windows; using System.Windows.Media.Media3D; using Smellyriver.Wpf; namespace Smellyriver.TankInspector.Graphics { /// <summary> /// Trackball is a utility class which observes the mouse events /// on a specified FrameworkElement and produces a Transform3D /// with the resultant rotation and scale. /// /// Example Usage: /// /// Trackball trackball = new Trackball(); /// trackball.EventSource = myElement; /// myViewport3D.Camera.Transform = trackball.Transform; /// /// Because Viewport3Ds only raise events when the mouse is over the /// rendered 3D geometry (as opposed to not when the mouse is within /// the layout bounds) you usually want to use another element as /// your EventSource. For example, a transparent border placed on /// top of your Viewport3D works well: /// /// <Grid> /// <ColumnDefinition /> /// <RowDefinition /> /// <Viewport3D Name="myViewport" ClipToBounds="True" Grid.Row="0" Grid.Column="0" /> /// <Border Name="myElement" Background="Transparent" Grid.Row="0" Grid.Column="0" /> /// </Grid> /// /// NOTE: The Transform property may be shared by multiple Cameras /// if you want to have auxilary views following the trackball. /// /// It can also be useful to share the Transform property with /// models in the scene that you want to move with the camera. /// (For example, the Trackport3D's headlight is implemented /// this way.) /// /// You may also use a Transform3DGroup to combine the /// Transform property with additional Transforms. /// </summary> public class Trackball : DependencyNotificationObject { //private FrameworkElement _eventSource; private Point _previousPosition2D; private Vector _vPreviousPosition = new Vector(0, 1); private Vector _hPreviousPosition = new Vector(0, 1); private readonly Transform3DGroup _transform; private readonly AxisAngleRotation3D _yawRotation = new AxisAngleRotation3D(); private readonly AxisAngleRotation3D _pitchRotation = new AxisAngleRotation3D(); private readonly InertiaValue _yawInertia = new InertiaValue(-145.31973875630851, double.MaxValue, double.MinValue, 1, 4.0, double.MaxValue); private readonly InertiaValue _pitchInertia = new InertiaValue(-37.364639593462712, 4, -85, 2, 6.0, double.MaxValue); private readonly InertiaValue _zoomInertia = new InertiaValue(1.4,2,0.2,10,0.5,2); private Vector3D _lookDirection = new Vector3D(0, 0, 1); public class InertiaValue { private readonly double _inertia; private readonly double _max; private readonly double _min; private double _impulse; private readonly double _damping; private readonly double _maxImpulse; public double Value { get; private set; } public InertiaValue(double initial, double max, double min, double inertia, double damping, double maxImpulse) { Value = initial; _max = max; _min = min; _inertia = Math.Abs(inertia); _damping = Math.Abs(damping); _maxImpulse = Math.Abs(maxImpulse); } public EventHandler ValueChanged; public void UpdateInertia(double delta) { if (_impulse > 0) { _impulse -= delta * _damping / _inertia; if (_impulse < 0) { _impulse = 0; return; } } else if(_impulse < 0) { _impulse += delta * _damping / _inertia; if (_impulse > 0) { _impulse = 0; return; } } Value += _impulse; if (Value > _max) { Value = _max; _impulse = 0; } else if (Value < _min) { Value = _min; _impulse = 0; } if (ValueChanged != null) { ValueChanged(this, new EventArgs()); } } public void Push(double impulse) { _impulse = impulse / _inertia; if (_impulse > _maxImpulse) _impulse = _maxImpulse; else if(_impulse < -_maxImpulse) _impulse = -_maxImpulse; UpdateInertia(0.0); } } private bool _hasTrackStarted; public Trackball() { _yawRotation.Axis = new Vector3D(0, 1, 0); _pitchRotation.Axis = new Vector3D(1, 0, 0); _transform = new Transform3DGroup(); _transform.Children.Add(new RotateTransform3D(_yawRotation)); _transform.Children.Add(new RotateTransform3D(_pitchRotation)); _yawInertia.ValueChanged = Yaw; _pitchInertia.ValueChanged = Pitch; } public void UpdateInertia(double delta) { _yawInertia.UpdateInertia(delta); _pitchInertia.UpdateInertia(delta); _zoomInertia.UpdateInertia(delta); } /// <summary> /// A transform to move the camera or scene to the trackball's /// current orientation and scale. /// </summary> public Transform3D Transform => _transform; public double YawFactor => _yawInertia.Value; public double ZoomFactor => _zoomInertia.Value; public Vector3D LookDirection => _lookDirection; private Vector ProjectToRound(double width, double x) { if (x < 0) x = 0; if (x > width) x = width; x = x / (width / 2); x = x - 1; double z = 1 - x * x; return new Vector(x, z); } public void TrackStart(Point trackPosition,double trackWidth, double trackHeight) { _previousPosition2D = trackPosition; _hPreviousPosition = ProjectToRound( trackWidth, _previousPosition2D.X); _vPreviousPosition = ProjectToRound( trackHeight, _previousPosition2D.Y); _hasTrackStarted = true; } public void TrackEnd() { _hasTrackStarted = false; } public void Zoom(int delta) { _zoomInertia.Push((double)(delta) / 500); } public void Track(Point currentPosition,double width,double height) { if (_hasTrackStarted) { var hCurrentPosition = ProjectToRound(width, currentPosition.X); double hangle = Vector.AngleBetween(_hPreviousPosition, hCurrentPosition); _yawInertia.Push(hangle); _hPreviousPosition = hCurrentPosition; var vCurrentPosition = ProjectToRound(height, currentPosition.Y); double vangle = Vector.AngleBetween(_vPreviousPosition, vCurrentPosition); _pitchInertia.Push(vangle); _vPreviousPosition = vCurrentPosition; } _previousPosition2D = currentPosition; } public void TrackLook(Point delta) { double hangle = delta.X/80.0; double vangle = delta.Y/80.0; _lookDirection.X = hangle; _lookDirection.Y = vangle; _lookDirection.Z = _lookDirection.Z+0.1; } private void Yaw(object sender, EventArgs e) { _yawRotation.Angle = _yawInertia.Value; } private void Pitch(object sender, EventArgs e) { _pitchRotation.Angle = _pitchInertia.Value; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Numerics.Tests { public class DivideTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunDivideTwoLargeBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [Fact] public static void RunDivideTwoSmallBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [Fact] public static void RunDivideOneLargeOneSmallBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [Fact] public static void RunDivideOneLargeOneZeroBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); Assert.Throws<DivideByZeroException>(() => { VerifyDivideString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivide"); }); } } [Fact] public static void RunDivideOneSmallOneZeroBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); Assert.Throws<DivideByZeroException>(() => { VerifyDivideString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivide"); }); } } [Fact] public static void RunDivideOneOverOne() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X/1 = X VerifyIdentityString(BigInteger.One + " " + Int32.MaxValue + " bDivide", Int32.MaxValue.ToString()); VerifyIdentityString(BigInteger.One + " " + Int64.MaxValue + " bDivide", Int64.MaxValue.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(BigInteger.One + " " + randBigInt + "bDivide", randBigInt.Substring(0, randBigInt.Length - 1)); } } [Fact] public static void RunDivideZeroOverBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: 0/X = 0 VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); } } [Fact] public static void RunDivideBoundary() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyDivideString(Math.Pow(2, 32) + " 2 bDivide"); // 32 bit boundary n1=0 n2=1 VerifyDivideString(Math.Pow(2, 33) + " 2 bDivide"); } [Fact] public static void RunOverflow() { // these values lead to an "overflow", if dividing digit by digit // we need to ensure that this case is being handled accordingly... var x = new BigInteger(new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); var y = new BigInteger(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); var z = new BigInteger(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); Assert.Equal(z, BigInteger.Divide(x, y)); } private static void VerifyDivideString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetNonZeroRandomByteArray(random, size); } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
// Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.IO; using System.Linq; #if NET40 using System.NET40; #endif using System.Web.UI; using OpenGamingLibrary.Json.Serialization; using OpenGamingLibrary.Json.Test.TestObjects; using OpenGamingLibrary.Json.Linq; using OpenGamingLibrary.Json.Utilities; using OpenGamingLibrary.Xunit.Extensions; using Xunit; namespace OpenGamingLibrary.Json.Test.Linq { public class JObjectTests : TestFixtureBase { [Fact] public void JObjectWithComments() { const string json = @"{ /*comment2*/ ""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/ ""ExpiryDate"": ""\/Date(1230422400000)\/"", ""Price"": 3.99, ""Sizes"": /*comment6*/ [ /*comment7*/ ""Small"", /*comment8*/ ""Medium"" /*comment9*/, /*comment10*/ ""Large"" /*comment11*/ ] /*comment12*/ } /*comment13*/"; JToken o = JToken.Parse(json); Assert.Equal("Apple", (string) o["Name"]); } [Fact] public void WritePropertyWithNoValue() { var o = new JObject(); o.Add(new JProperty("novalue")); StringAssert.Equal(@"{ ""novalue"": null }", o.ToString()); } [Fact] public void Keys() { var o = new JObject(); var d = (IDictionary<string, JToken>)o; Assert.Equal(0, d.Keys.Count); o["value"] = true; Assert.Equal(1, d.Keys.Count); } [Fact] public void TryGetValue() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.Equal(1, o.Children().Count()); JToken t; Assert.Equal(false, o.TryGetValue("sdf", out t)); Assert.Equal(null, t); Assert.Equal(false, o.TryGetValue(null, out t)); Assert.Equal(null, t); Assert.Equal(true, o.TryGetValue("PropertyNameValue", out t)); Assert.Equal(true, JToken.DeepEquals(new JValue(1), t)); } [Fact] public void DictionaryItemShouldSet() { var o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.Equal(1, o.Children().Count()); JToken t; Assert.Equal(true, o.TryGetValue("PropertyNameValue", out t)); Assert.Equal(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.Equal(1, o.Children().Count()); Assert.Equal(true, o.TryGetValue("PropertyNameValue", out t)); Assert.Equal(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.Equal(1, o.Children().Count()); Assert.Equal(true, o.TryGetValue("PropertyNameValue", out t)); Assert.Equal(true, JToken.DeepEquals(JValue.CreateNull(), t)); } [Fact] public void Remove() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.Equal(1, o.Children().Count()); Assert.Equal(false, o.Remove("sdf")); Assert.Equal(false, o.Remove(null)); Assert.Equal(true, o.Remove("PropertyNameValue")); Assert.Equal(0, o.Children().Count()); } [Fact] public void GenericCollectionRemove() { JValue v = new JValue(1); var o = new JObject(); o.Add("PropertyNameValue", v); Assert.Equal(1, o.Children().Count()); Assert.Equal(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.Equal(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.Equal(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.Equal(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.Equal(0, o.Children().Count()); } [Fact] public void DuplicatePropertyNameShouldThrow() { AssertException.Throws<ArgumentException>(() => { var o = new JObject(); o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null); }, "Can not add property PropertyNameValue to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object."); } [Fact] public void GenericDictionaryAdd() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.Equal(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.Equal(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.Equal(2, o.Children().Count()); } [Fact] public void GenericCollectionAdd() { var o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.Equal(1, (int)o["PropertyNameValue"]); Assert.Equal(1, o.Children().Count()); } [Fact] public void GenericCollectionClear() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.Equal(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.Equal(0, o.Children().Count()); Assert.Equal(null, p.Parent); } [Fact] public void GenericCollectionContains() { JValue v = new JValue(1); var o = new JObject(); o.Add("PropertyNameValue", v); Assert.Equal(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.Equal(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.Equal(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.Equal(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.Equal(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.Equal(false, contains); } [Fact] public void GenericDictionaryContains() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.Equal(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.Equal(true, contains); } [Fact] public void GenericCollectionCopyTo() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.Equal(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.Equal(default(KeyValuePair<string, JToken>), a[0]); Assert.Equal("PropertyNameValue", a[1].Key); Assert.Equal(1, (int)a[1].Value); Assert.Equal("PropertyNameValue2", a[2].Key); Assert.Equal(2, (int)a[2].Value); Assert.Equal("PropertyNameValue3", a[3].Key); Assert.Equal(3, (int)a[3].Value); Assert.Equal(default(KeyValuePair<string, JToken>), a[4]); } [Fact] public void GenericCollectionCopyToNullArrayShouldThrow() { AssertException.Throws<ArgumentException>(() => { var o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); }, @"Value cannot be null. Parameter name: array"); } [Fact] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { AssertException.Throws<ArgumentOutOfRangeException>(() => { var o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); }, @"arrayIndex is less than 0. Parameter name: arrayIndex"); } [Fact] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { AssertException.Throws<ArgumentException>(() => { var o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); }, @"arrayIndex is equal to or greater than the length of array."); } [Fact] public void GenericCollectionCopyToInsufficientArrayCapacity() { AssertException.Throws<ArgumentException>(() => { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); }, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } [Fact] public void FromObjectRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); Assert.Equal("FirstNameValue", (string)o["first_name"]); Assert.Equal(JTokenType.Raw, ((JValue)o["RawContent"]).Type); Assert.Equal("[1,2,3,4,5]", (string)o["RawContent"]); Assert.Equal("LastNameValue", (string)o["last_name"]); } [Fact] public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.True(reader.Read()); Assert.Equal(JsonToken.StartObject, reader.TokenType); Assert.True(reader.Read()); Assert.Equal(JsonToken.PropertyName, reader.TokenType); Assert.True(reader.Read()); Assert.Equal(JsonToken.String, reader.TokenType); Assert.True(reader.Read()); Assert.Equal(JsonToken.PropertyName, reader.TokenType); Assert.True(reader.Read()); Assert.Equal(JsonToken.Raw, reader.TokenType); Assert.True(reader.Read()); Assert.Equal(JsonToken.PropertyName, reader.TokenType); Assert.True(reader.Read()); Assert.Equal(JsonToken.String, reader.TokenType); Assert.True(reader.Read()); Assert.Equal(JsonToken.EndObject, reader.TokenType); Assert.False(reader.Read()); } [Fact] public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.Equal("FirstNameValue", raw.FirstName); Assert.Equal("LastNameValue", raw.LastName); Assert.Equal("[1,2,3,4,5]", raw.RawContent.Value); } [Fact] public void Parse_ShouldThrowOnUnexpectedToken() { AssertException.Throws<JsonReaderException>(() => { const string json = @"[""prop""]"; JObject.Parse(json); }, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."); } [Fact] public void ParseJavaScriptDate() { const string json = @"[new Date(1207285200000)]"; JArray a = (JArray)JsonConvert.DeserializeObject(json); JValue v = (JValue)a[0]; Assert.Equal(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v); } [Fact] public void GenericValueCast() { string json = @"{""foo"":true}"; var o = JsonConvert.DeserializeObject(json) as JObject; bool? value = o.Value<bool?>("foo"); Assert.Equal(true, value); json = @"{""foo"":null}"; o = (JObject)JsonConvert.DeserializeObject(json); value = o.Value<bool?>("foo"); Assert.Equal(null, value); } [Fact] public void Blog() { AssertException.Throws<JsonReaderException>(() => { JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 5."); } [Fact] public void RawChildValues() { var o = new JObject(); o["val1"] = new JRaw("1"); o["val2"] = new JRaw("1"); string json = o.ToString(); StringAssert.Equal(@"{ ""val1"": 1, ""val2"": 1 }", json); } [Fact] public void Iterate() { var o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); JToken t = o; int i = 1; foreach (JProperty property in t) { Assert.Equal("PropertyNameValue" + i, property.Name); Assert.Equal(i, (int)property.Value); i++; } } [Fact] public void KeyValuePairIterate() { var o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); int i = 1; foreach (KeyValuePair<string, JToken> pair in o) { Assert.Equal("PropertyNameValue" + i, pair.Key); Assert.Equal(i, (int)pair.Value); i++; } } [Fact] public void WriteObjectNullStringValue() { string s = null; JValue v = new JValue(s); Assert.Equal(null, v.Value); Assert.Equal(JTokenType.String, v.Type); var o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.Equal(@"{ ""title"": null }", output); } [Fact] public void Example() { const string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small Console.WriteLine(name); Console.WriteLine(smallest); } [Fact] public void DeserializeClassManually() { const string jsonText = @"{ ""short"": { ""original"":""http://www.foo.com/"", ""short"":""krehqk"", ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Console.WriteLine(shortie.Original); // http://www.foo.com/ Console.WriteLine(shortie.Error.ErrorMessage); // No action taken Assert.Equal("http://www.foo.com/", shortie.Original); Assert.Equal("krehqk", shortie.Short); Assert.Equal(null, shortie.Shortened); Assert.Equal(0, shortie.Error.Code); Assert.Equal("No action taken", shortie.Error.ErrorMessage); } [Fact] public void JObjectContainingHtml() { var o = new JObject(); o["rc"] = new JValue(200); o["m"] = new JValue(""); o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>"); StringAssert.Equal(@"{ ""rc"": 200, ""m"": """", ""o"": ""<div class='s1'>\r\n</div>"" }", o.ToString()); } [Fact] public void ImplicitValueConversions() { JObject moss = new JObject(); moss["FirstName"] = new JValue("Maurice"); moss["LastName"] = new JValue("Moss"); moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30)); moss["Department"] = new JValue("IT"); moss["JobTitle"] = new JValue("Support"); Console.WriteLine(moss.ToString()); //{ // "FirstName": "Maurice", // "LastName": "Moss", // "BirthDate": "\/Date(252241200000+1300)\/", // "Department": "IT", // "JobTitle": "Support" //} JObject jen = new JObject(); jen["FirstName"] = "Jen"; jen["LastName"] = "Barber"; jen["BirthDate"] = new DateTime(1978, 3, 15); jen["Department"] = "IT"; jen["JobTitle"] = "Manager"; Console.WriteLine(jen.ToString()); //{ // "FirstName": "Jen", // "LastName": "Barber", // "BirthDate": "\/Date(258721200000+1300)\/", // "Department": "IT", // "JobTitle": "Manager" //} } [Fact] public void ReplaceJPropertyWithJPropertyWithSameName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); var o = new JObject(p1, p2); IList l = o; Assert.Equal(p1, l[0]); Assert.Equal(p2, l[1]); JProperty p3 = new JProperty("Test1", "III"); p1.Replace(p3); Assert.Equal(null, p1.Parent); Assert.Equal(l, p3.Parent); Assert.Equal(p3, l[0]); Assert.Equal(p2, l[1]); Assert.Equal(2, l.Count); Assert.Equal(2, o.Properties().Count()); JProperty p4 = new JProperty("Test4", "IV"); p2.Replace(p4); Assert.Equal(null, p2.Parent); Assert.Equal(l, p4.Parent); Assert.Equal(p3, l[0]); Assert.Equal(p4, l[1]); } #if !(NET20 || NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40) [Fact] public void PropertyChanging() { object changing = null; object changed = null; int changingCount = 0; int changedCount = 0; var o = new JObject(); o.PropertyChanging += (sender, args) => { JObject s = (JObject)sender; changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changingCount++; }; o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.Equal(null, changing); Assert.Equal("value1", changed); Assert.Equal("value1", (string)o["StringValue"]); Assert.Equal(1, changingCount); Assert.Equal(1, changedCount); o["StringValue"] = "value1"; Assert.Equal(1, changingCount); Assert.Equal(1, changedCount); o["StringValue"] = "value2"; Assert.Equal("value1", changing); Assert.Equal("value2", changed); Assert.Equal("value2", (string)o["StringValue"]); Assert.Equal(2, changingCount); Assert.Equal(2, changedCount); o["StringValue"] = null; Assert.Equal("value2", changing); Assert.Equal(null, changed); Assert.Equal(null, (string)o["StringValue"]); Assert.Equal(3, changingCount); Assert.Equal(3, changedCount); o["NullValue"] = null; Assert.Equal(null, changing); Assert.Equal(null, changed); Assert.Equal(JValue.CreateNull(), o["NullValue"]); Assert.Equal(4, changingCount); Assert.Equal(4, changedCount); o["NullValue"] = null; Assert.Equal(4, changingCount); Assert.Equal(4, changedCount); } #endif [Fact] public void PropertyChanged() { object changed = null; int changedCount = 0; var o = new JObject(); o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.Equal("value1", changed); Assert.Equal("value1", (string)o["StringValue"]); Assert.Equal(1, changedCount); o["StringValue"] = "value1"; Assert.Equal(1, changedCount); o["StringValue"] = "value2"; Assert.Equal("value2", changed); Assert.Equal("value2", (string)o["StringValue"]); Assert.Equal(2, changedCount); o["StringValue"] = null; Assert.Equal(null, changed); Assert.Equal(null, (string)o["StringValue"]); Assert.Equal(3, changedCount); o["NullValue"] = null; Assert.Equal(null, changed); Assert.Equal(JValue.CreateNull(), o["NullValue"]); Assert.Equal(4, changedCount); o["NullValue"] = null; Assert.Equal(4, changedCount); } [Fact] public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.True(l.Contains(p)); Assert.False(l.Contains(new JProperty("Test", 1))); } [Fact] public void IListIndexOf() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.Equal(0, l.IndexOf(p)); Assert.Equal(-1, l.IndexOf(new JProperty("Test", 1))); } [Fact] public void IListClear() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.Equal(1, l.Count); l.Clear(); Assert.Equal(0, l.Count); } [Fact] public void IListCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); object[] a = new object[l.Count]; l.CopyTo(a, 0); Assert.Equal(p1, a[0]); Assert.Equal(p2, a[1]); } [Fact] public void IListAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.Equal(3, l.Count); Assert.Equal(p3, l[2]); } [Fact] public void IListAddBadToken() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject."); } [Fact] public void IListAddBadValue() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add("Bad!"); }, "Argument is not a JToken."); } [Fact] public void IListAddPropertyWithExistingName() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object."); } [Fact] public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.Equal(2, l.Count); l.Remove(p1); Assert.Equal(1, l.Count); Assert.False(l.Contains(p1)); Assert.True(l.Contains(p2)); l.Remove(p2); Assert.Equal(0, l.Count); Assert.False(l.Contains(p2)); Assert.Equal(null, p2.Parent); } [Fact] public void IListRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.Equal(1, l.Count); l.Remove(p2); Assert.Equal(0, l.Count); } [Fact] public void IListInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.Equal(l, p3.Parent); Assert.Equal(p1, l[0]); Assert.Equal(p3, l[1]); Assert.Equal(p2, l[2]); } [Fact] public void IListIsReadOnly() { IList l = new JObject(); Assert.False(l.IsReadOnly); } [Fact] public void IListIsFixedSize() { IList l = new JObject(); Assert.False(l.IsFixedSize); } [Fact] public void IListSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.Equal(p3, l[0]); Assert.Equal(p2, l[1]); } [Fact] public void IListSetItemAlreadyExists() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object."); } [Fact] public void IListSetItemInvalid() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l[0] = new JValue(true); }, @"Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject."); } [Fact] public void IListSyncRoot() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.NotNull(l.SyncRoot); } [Fact] public void IListIsSynchronized() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.False(l.IsSynchronized); } [Fact] public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.True(l.Contains(p)); Assert.False(l.Contains(new JProperty("Test", 1))); } [Fact] public void GenericListJTokenIndexOf() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.Equal(0, l.IndexOf(p)); Assert.Equal(-1, l.IndexOf(new JProperty("Test", 1))); } [Fact] public void GenericListJTokenClear() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.Equal(1, l.Count); l.Clear(); Assert.Equal(0, l.Count); } [Fact] public void GenericListJTokenCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JToken[] a = new JToken[l.Count]; l.CopyTo(a, 0); Assert.Equal(p1, a[0]); Assert.Equal(p2, a[1]); } [Fact] public void GenericListJTokenAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.Equal(3, l.Count); Assert.Equal(p3, l[2]); } [Fact] public void GenericListJTokenAddBadToken() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject."); } [Fact] public void GenericListJTokenAddBadValue() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // string is implicitly converted to JValue l.Add("Bad!"); }, "Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject."); } [Fact] public void GenericListJTokenAddPropertyWithExistingName() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object."); } [Fact] public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.False(l.Remove(p3)); Assert.Equal(2, l.Count); Assert.True(l.Remove(p1)); Assert.Equal(1, l.Count); Assert.False(l.Contains(p1)); Assert.True(l.Contains(p2)); Assert.True(l.Remove(p2)); Assert.Equal(0, l.Count); Assert.False(l.Contains(p2)); Assert.Equal(null, p2.Parent); } [Fact] public void GenericListJTokenRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.Equal(1, l.Count); l.Remove(p2); Assert.Equal(0, l.Count); } [Fact] public void GenericListJTokenInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.Equal(l, p3.Parent); Assert.Equal(p1, l[0]); Assert.Equal(p3, l[1]); Assert.Equal(p2, l[2]); } [Fact] public void GenericListJTokenIsReadOnly() { IList<JToken> l = new JObject(); Assert.False(l.IsReadOnly); } [Fact] public void GenericListJTokenSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.Equal(p3, l[0]); Assert.Equal(p2, l[1]); } [Fact] public void GenericListJTokenSetItemAlreadyExists() { AssertException.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object."); } [Fact] public void IBindingListSortDirection() { IBindingList l = new JObject(); Assert.Equal(ListSortDirection.Ascending, l.SortDirection); } [Fact] public void IBindingListSortProperty() { IBindingList l = new JObject(); Assert.Equal(null, l.SortProperty); } [Fact] public void IBindingListSupportsChangeNotification() { IBindingList l = new JObject(); Assert.Equal(true, l.SupportsChangeNotification); } [Fact] public void IBindingListSupportsSearching() { IBindingList l = new JObject(); Assert.Equal(false, l.SupportsSearching); } [Fact] public void IBindingListSupportsSorting() { IBindingList l = new JObject(); Assert.Equal(false, l.SupportsSorting); } [Fact] public void IBindingListAllowEdit() { IBindingList l = new JObject(); Assert.Equal(true, l.AllowEdit); } [Fact] public void IBindingListAllowNew() { IBindingList l = new JObject(); Assert.Equal(true, l.AllowNew); } [Fact] public void IBindingListAllowRemove() { IBindingList l = new JObject(); Assert.Equal(true, l.AllowRemove); } [Fact] public void IBindingListAddIndex() { IBindingList l = new JObject(); // do nothing l.AddIndex(null); } [Fact] public void IBindingListApplySort() { AssertException.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.ApplySort(null, ListSortDirection.Ascending); }, "Specified method is not supported."); } [Fact] public void IBindingListRemoveSort() { AssertException.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.RemoveSort(); }, "Specified method is not supported."); } [Fact] public void IBindingListRemoveIndex() { IBindingList l = new JObject(); // do nothing l.RemoveIndex(null); } [Fact] public void IBindingListFind() { AssertException.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.Find(null, null); }, "Specified method is not supported."); } [Fact] public void IBindingListIsSorted() { IBindingList l = new JObject(); Assert.Equal(false, l.IsSorted); } [Fact] public void IBindingListAddNew() { AssertException.Throws<JsonException>(() => { IBindingList l = new JObject(); l.AddNew(); }, "Could not determine new value to add to 'OpenGamingLibrary.Json.Linq.JObject'."); } [Fact] public void IBindingListAddNewWithEvent() { var o = new JObject(); o._addingNew += (s, e) => e.NewObject = new JProperty("Property!"); IBindingList l = o; object newObject = l.AddNew(); Assert.NotNull(newObject); JProperty p = (JProperty)newObject; Assert.Equal("Property!", p.Name); Assert.Equal(o, p.Parent); } [Fact] public void ITypedListGetListName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); Assert.Equal(string.Empty, l.GetListName(null)); } [Fact] public void ITypedListGetItemProperties() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); Assert.Null(propertyDescriptors); } [Fact] public void ListChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); var o = new JObject(p1, p2); ListChangedType? changedType = null; int? index = null; o.ListChanged += (s, a) => { changedType = a.ListChangedType; index = a.NewIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.Equal(changedType, ListChangedType.ItemAdded); Assert.Equal(index, 2); Assert.Equal(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.Equal(changedType, ListChangedType.ItemChanged); Assert.Equal(index, 2); Assert.Equal(p4, ((IList<JToken>)o)[index.Value]); Assert.False(((IList<JToken>)o).Contains(p3)); Assert.True(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.Equal(changedType, ListChangedType.ItemChanged); Assert.Equal(index, 0); Assert.Equal(2, (int)o["Test1"]); } [Fact] public void GetGeocodeAddress() { const string json = @"{ ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""id"": ""p1"", ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"", ""AddressDetails"": { ""Accuracy"" : 8, ""Country"" : { ""AdministrativeArea"" : { ""AdministrativeAreaName"" : ""IL"", ""SubAdministrativeArea"" : { ""Locality"" : { ""LocalityName"" : ""Rockford"", ""PostalCode"" : { ""PostalCodeNumber"" : ""61107"" }, ""Thoroughfare"" : { ""ThoroughfareName"" : ""435 N Mulford Rd"" } }, ""SubAdministrativeAreaName"" : ""Winnebago"" } }, ""CountryName"" : ""USA"", ""CountryNameCode"" : ""US"" } }, ""ExtendedData"": { ""LatLonBox"": { ""north"": 42.2753076, ""south"": 42.2690124, ""east"": -88.9964645, ""west"": -89.0027597 } }, ""Point"": { ""coordinates"": [ -88.9995886, 42.2721596, 0 ] } } ] }"; JObject o = JObject.Parse(json); string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"]; Assert.Equal("435 N Mulford Rd", searchAddress); } [Fact] public void SetValueWithInvalidPropertyName() { AssertException.Throws<ArgumentException>(() => { var o = new JObject(); o[0] = new JValue(3); }, "Set JObject values with invalid key value: 0. Object property name expected."); } [Fact] public void SetValue() { object key = "TestKey"; var o = new JObject(); o[key] = new JValue(3); Assert.Equal(3, (int)o[key]); } [Fact] public void ParseMultipleProperties() { const string json = @"{ ""Name"": ""Name1"", ""Name"": ""Name2"" }"; JObject o = JObject.Parse(json); string value = (string)o["Name"]; Assert.Equal("Name2", value); } #if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40) [Fact] public void WriteObjectNullDBNullValue() { DBNull dbNull = DBNull.Value; JValue v = new JValue(dbNull); Assert.Equal(DBNull.Value, v.Value); Assert.Equal(JTokenType.Null, v.Type); var o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.Equal(@"{ ""title"": null }", output); } #endif [Fact] public void InvalidValueCastExceptionMessage() { AssertException.Throws<ArgumentException>(() => { const string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o["responseData"]; }, "Can not convert Object to String."); } [Fact] public void InvalidPropertyValueCastExceptionMessage() { AssertException.Throws<ArgumentException>(() => { const string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o.Property("responseData"); }, "Can not convert Object to String."); } [Fact] public void ParseIncomplete() { AssertException.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6."); } [Fact] public void LoadFromNestedObject() { const string jsonText = @"{ ""short"": { ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JObject o = (JObject)JToken.ReadFrom(reader); Assert.NotNull(o); StringAssert.Equal(@"{ ""code"": 0, ""msg"": ""No action taken"" }", o.ToString(Formatting.Indented)); } [Fact] public void LoadFromNestedObjectIncomplete() { AssertException.Throws<JsonReaderException>(() => { const string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JToken.ReadFrom(reader); }, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15."); } #if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40) [Fact] public void GetProperties() { JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}"); ICustomTypeDescriptor descriptor = o; PropertyDescriptorCollection properties = descriptor.GetProperties(); Assert.Equal(4, properties.Count); PropertyDescriptor prop1 = properties[0]; Assert.Equal("prop1", prop1.Name); Assert.Equal(typeof(object), prop1.PropertyType); Assert.Equal(typeof(JObject), prop1.ComponentType); Assert.Equal(false, prop1.CanResetValue(o)); Assert.Equal(false, prop1.ShouldSerializeValue(o)); PropertyDescriptor prop2 = properties[1]; Assert.Equal("prop2", prop2.Name); Assert.Equal(typeof(object), prop2.PropertyType); Assert.Equal(typeof(JObject), prop2.ComponentType); Assert.Equal(false, prop2.CanResetValue(o)); Assert.Equal(false, prop2.ShouldSerializeValue(o)); PropertyDescriptor prop3 = properties[2]; Assert.Equal("prop3", prop3.Name); Assert.Equal(typeof(object), prop3.PropertyType); Assert.Equal(typeof(JObject), prop3.ComponentType); Assert.Equal(false, prop3.CanResetValue(o)); Assert.Equal(false, prop3.ShouldSerializeValue(o)); PropertyDescriptor prop4 = properties[3]; Assert.Equal("prop4", prop4.Name); Assert.Equal(typeof(object), prop4.PropertyType); Assert.Equal(typeof(JObject), prop4.ComponentType); Assert.Equal(false, prop4.CanResetValue(o)); Assert.Equal(false, prop4.ShouldSerializeValue(o)); } #endif [Fact] public void ParseEmptyObjectWithComment() { JObject o = JObject.Parse("{ /* A Comment */ }"); Assert.Equal(0, o.Count); } [Fact] public void FromObjectTimeSpan() { JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1)); Assert.Equal(v.Value, TimeSpan.FromDays(1)); Assert.Equal("1.00:00:00", v.ToString()); } [Fact] public void FromObjectUri() { JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz")); Assert.Equal(v.Value, new Uri("http://www.stuff.co.nz")); Assert.Equal("http://www.stuff.co.nz/", v.ToString()); } [Fact] public void FromObjectGuid() { JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.Equal(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.Equal("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString()); } [Fact] public void ParseAdditionalContent() { AssertException.Throws<JsonReaderException>(() => { const string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }, 987987"; JObject o = JObject.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2."); } [Fact] public void DeepEqualsIgnoreOrder() { JObject o1 = new JObject( new JProperty("null", null), new JProperty("integer", 1), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("array", new JArray(1, 2))); Assert.True(o1.DeepEquals(o1)); JObject o2 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(1, 2))); Assert.True(o1.DeepEquals(o2)); JObject o3 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 2), new JProperty("array", new JArray(1, 2))); Assert.False(o1.DeepEquals(o3)); JObject o4 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(2, 1))); Assert.False(o1.DeepEquals(o4)); JObject o5 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1)); Assert.False(o1.DeepEquals(o5)); Assert.False(o1.DeepEquals(null)); } [Fact] public void ToListOnEmptyObject() { JObject o = JObject.Parse(@"{}"); IList<JToken> l1 = o.ToList<JToken>(); Assert.Equal(0, l1.Count); IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.Equal(0, l2.Count); o = JObject.Parse(@"{'hi':null}"); l1 = o.ToList<JToken>(); Assert.Equal(1, l1.Count); l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.Equal(1, l2.Count); } [Fact] public void EmptyObjectDeepEquals() { Assert.True(JToken.DeepEquals(new JObject(), new JObject())); JObject a = new JObject(); JObject b = new JObject(); b.Add("hi", "bye"); b.Remove("hi"); Assert.True(JToken.DeepEquals(a, b)); Assert.True(JToken.DeepEquals(b, a)); } [Fact] public void GetValueBlogExample() { JObject o = JObject.Parse(@"{ 'name': 'Lower', 'NAME': 'Upper' }"); string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase); // Upper string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase); // Lower Assert.Equal("Upper", exactMatch); Assert.Equal("Lower", ignoreCase); } [Fact] public void GetValue() { JObject a = new JObject(); a["Name"] = "Name!"; a["name"] = "name!"; a["title"] = "Title!"; Assert.Equal(null, a.GetValue("NAME", StringComparison.Ordinal)); Assert.Equal(null, a.GetValue("NAME")); Assert.Equal(null, a.GetValue("TITLE")); Assert.Equal("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase)); Assert.Equal("name!", (string)a.GetValue("name", StringComparison.Ordinal)); Assert.Equal(null, a.GetValue(null, StringComparison.Ordinal)); Assert.Equal(null, a.GetValue(null)); JToken v; Assert.False(a.TryGetValue("NAME", StringComparison.Ordinal, out v)); Assert.Equal(null, v); Assert.False(a.TryGetValue("NAME", out v)); Assert.False(a.TryGetValue("TITLE", out v)); Assert.True(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v)); Assert.Equal("Name!", (string)v); Assert.True(a.TryGetValue("name", StringComparison.Ordinal, out v)); Assert.Equal("name!", (string)v); Assert.False(a.TryGetValue(null, StringComparison.Ordinal, out v)); } public class FooJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var token = JToken.FromObject(value, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); if (token.Type == JTokenType.Object) { var o = (JObject)token; o.AddFirst(new JProperty("foo", "bar")); o.WriteTo(writer); } else token.WriteTo(writer); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException("This custom converter only supportes serialization and not deserialization."); } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return true; } } [Fact] public void FromObjectInsideConverterWithCustomSerializer() { var p = new Person { Name = "Daniel Wertheim", }; var settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new FooJsonConverter() }, ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(p, settings); Assert.Equal(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json); } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System.Globalization; namespace Quartz.Impl.AdoJobStore { /// <summary> /// This class extends <see cref="AdoConstants" /> /// to include the query string constants in use by the <see cref="StdAdoDelegate" /> /// class. /// </summary> /// <author><a href="mailto:[email protected]">Jeffrey Wescott</a></author> /// <author>Marko Lahma (.NET)</author> public class StdAdoConstants : AdoConstants { public const string TablePrefixSubst = "{0}"; // table prefix substitution string public const string SchedulerNameSubst = "{1}"; // DELETE public static readonly string SqlDeleteBlobTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableBlobTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlDeleteCalendar = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @calendarName", TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlDeleteCronTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableCronTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlDeleteFiredTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerEntryId", TablePrefixSubst, TableFiredTriggers,ColumnSchedulerName, SchedulerNameSubst, ColumnEntryId); public static readonly string SqlDeleteFiredTriggers = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3}", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteInstancesFiredTriggers = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlDeleteJobDetail = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @jobName AND {5} = @jobGroup", TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlDeleteNoRecoveryFiredTriggers = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName AND {5} = @requestsRecovery", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName, ColumnRequestsRecovery); public static readonly string SqlDeletePausedTriggerGroup = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} LIKE @triggerGroup", TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlDeletePausedTriggerGroups = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3}", TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteSchedulerState = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName", TablePrefixSubst, TableSchedulerState, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlDeleteSimpleTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableSimpleTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlDeleteTrigger = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlDeleteAllSimpleTriggers = string.Format("DELETE FROM {0}SIMPLE_TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllSimpropTriggers = string.Format("DELETE FROM {0}SIMPROP_TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllCronTriggers = string.Format("DELETE FROM {0}CRON_TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllBlobTriggers = string.Format("DELETE FROM {0}BLOB_TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllTriggers = string.Format("DELETE FROM {0}TRIGGERS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllJobDetails = string.Format("DELETE FROM {0}JOB_DETAILS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllCalendars = string.Format("DELETE FROM {0}CALENDARS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlDeleteAllPausedTriggerGrps = string.Format("DELETE FROM {0}PAUSED_TRIGGER_GRPS WHERE {1} = {2}", TablePrefixSubst, ColumnSchedulerName, SchedulerNameSubst); // INSERT public static readonly string SqlInsertBlobTrigger = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}) VALUES({6}, @triggerName, @triggerGroup, @blob)", TablePrefixSubst, TableBlobTriggers, ColumnSchedulerName, ColumnTriggerName, ColumnTriggerGroup, ColumnBlob, SchedulerNameSubst); public static readonly string SqlInsertCalendar = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}) VALUES({5}, @calendarName, @calendar)", TablePrefixSubst, TableCalendars, ColumnSchedulerName, ColumnCalendarName, ColumnCalendar, SchedulerNameSubst); public static readonly string SqlInsertCronTrigger = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}) VALUES({7}, @triggerName, @triggerGroup, @triggerCronExpression, @triggerTimeZone)", TablePrefixSubst, TableCronTriggers, ColumnSchedulerName, ColumnTriggerName, ColumnTriggerGroup, ColumnCronExpression, ColumnTimeZoneId, SchedulerNameSubst); public static readonly string SqlInsertFiredTrigger = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}) VALUES({15}, @triggerEntryId, @triggerName, @triggerGroup, @triggerInstanceName, @triggerFireTime, @triggerScheduledTime, @triggerState, @triggerJobName, @triggerJobGroup, @triggerJobStateful, @triggerJobRequestsRecovery, @triggerPriority)", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, ColumnEntryId, ColumnTriggerName, ColumnTriggerGroup, ColumnInstanceName, ColumnFiredTime, ColumnScheduledTime, ColumnEntryState, ColumnJobName, ColumnJobGroup, ColumnIsNonConcurrent, ColumnRequestsRecovery, ColumnPriority, SchedulerNameSubst); public static readonly string SqlInsertJobDetail = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}) VALUES({12}, @jobName, @jobGroup, @jobDescription, @jobType, @jobDurable, @jobVolatile, @jobStateful, @jobRequestsRecovery, @jobDataMap)", TablePrefixSubst, TableJobDetails, ColumnSchedulerName, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnJobClass, ColumnIsDurable, ColumnIsNonConcurrent, ColumnIsUpdateData, ColumnRequestsRecovery, ColumnJobDataMap, SchedulerNameSubst); public static readonly string SqlInsertPausedTriggerGroup = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}) VALUES ({4}, @triggerGroup)", TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, ColumnTriggerGroup, SchedulerNameSubst); public static readonly string SqlInsertSchedulerState = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}) VALUES({6}, @instanceName, @lastCheckinTime, @checkinInterval)", TablePrefixSubst, TableSchedulerState, ColumnSchedulerName, ColumnInstanceName, ColumnLastCheckinTime, ColumnCheckinInterval, SchedulerNameSubst); public static readonly string SqlInsertSimpleTrigger = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}, {7}) VALUES({8}, @triggerName, @triggerGroup, @triggerRepeatCount, @triggerRepeatInterval, @triggerTimesTriggered)", TablePrefixSubst, TableSimpleTriggers, ColumnSchedulerName, ColumnTriggerName, ColumnTriggerGroup, ColumnRepeatCount, ColumnRepeatInterval, ColumnTimesTriggered, SchedulerNameSubst); public static readonly string SqlInsertTrigger = string.Format(CultureInfo.InvariantCulture, @"INSERT INTO {0}{1} ({2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}) VALUES({18}, @triggerName, @triggerGroup, @triggerJobName, @triggerJobGroup, @triggerDescription, @triggerNextFireTime, @triggerPreviousFireTime, @triggerState, @triggerType, @triggerStartTime, @triggerEndTime, @triggerCalendarName, @triggerMisfireInstruction, @triggerJobJobDataMap, @triggerPriority)", TablePrefixSubst, TableTriggers, ColumnSchedulerName, ColumnTriggerName, ColumnTriggerGroup, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnNextFireTime, ColumnPreviousFireTime, ColumnTriggerState, ColumnTriggerType, ColumnStartTime, ColumnEndTime, ColumnCalendarName, ColumnMifireInstruction, ColumnJobDataMap, ColumnPriority, SchedulerNameSubst); // SELECT public static readonly string SqlSelectBlobTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT {6} FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableBlobTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnBlob); public static readonly string SqlSelectCalendar = string.Format(CultureInfo.InvariantCulture, "SELECT {5} FROM {0}{1} WHERE {2} = {3} AND {4} = @calendarName", TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName, ColumnCalendar); public static readonly string SqlSelectCalendarExistence = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @calendarName", ColumnCalendarName, TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlSelectCalendars = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4}", ColumnCalendarName, TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectCronTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableCronTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectFiredTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectFiredTriggerGroup = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerGroup", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectFiredTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3}", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectFiredTriggerInstanceNames = string.Format(CultureInfo.InvariantCulture, "SELECT DISTINCT {0} FROM {1}{2} WHERE {3} = {4}", ColumnInstanceName, TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectFiredTriggersOfJob = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @jobName AND {5} = @jobGroup", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectFiredTriggersOfJobGroup = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @jobGroup", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobGroup); public static readonly string SqlSelectInstancesFiredTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlSelectInstancesRecoverableFiredTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName AND {5} = @requestsRecovery", TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName, ColumnRequestsRecovery); public static readonly string SqlSelectJobDetail = string.Format(CultureInfo.InvariantCulture, "SELECT {6},{7},{8},{9},{10},{11},{12} FROM {0}{1} WHERE {2} = {3} AND {4} = @jobName AND {5} = @jobGroup", TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnJobClass, ColumnIsDurable, ColumnRequestsRecovery, ColumnJobDataMap); public static readonly string SqlSelectJobExecutionCount = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", ColumnTriggerName, TablePrefixSubst, TableFiredTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectJobExistence = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", ColumnJobName, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectJobForTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT J.{0}, J.{1}, J.{2}, J.{3}, J.{4} FROM {5}{6} T, {7}{8} J WHERE T.{9} = {10} AND T.{11} = {12} AND T.{13} = @triggerName AND T.{14} = @triggerGroup AND T.{15} = J.{16} AND T.{17} = J.{18}", ColumnJobName, ColumnJobGroup, ColumnIsDurable, ColumnJobClass, ColumnRequestsRecovery, TablePrefixSubst, TableTriggers, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnJobName, ColumnJobName, ColumnJobGroup, ColumnJobGroup); public static readonly string SqlSelectJobGroups = string.Format(CultureInfo.InvariantCulture, "SELECT DISTINCT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnJobGroup, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectJobNonConcurrent = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", ColumnIsNonConcurrent, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectJobsInGroupLike = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} LIKE @jobGroup", ColumnJobName, ColumnJobGroup, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobGroup); public static readonly string SqlSelectJobsInGroup = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @jobGroup", ColumnJobName, ColumnJobGroup, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst, ColumnJobGroup); public static readonly string SqlSelectMisfiredTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} <> {5} AND {6} < @nextFireTime ORDER BY {7} ASC, {8} DESC", TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnNextFireTime, ColumnPriority); public static readonly string SqlSelectMisfiredTriggersInGroupInState = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} <> {6} AND {7} < @nextFireTime AND {8} = @triggerGroup AND {9} = @state ORDER BY {10} ASC, {11} DESC", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnTriggerGroup, ColumnTriggerState, ColumnNextFireTime, ColumnPriority); public static readonly string SqlSelectMisfiredTriggersInState = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} <> {7} AND {8} < @nextFireTime AND {9} = @state ORDER BY {10} ASC, {11} DESC", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnTriggerState, ColumnNextFireTime, ColumnPriority); public static readonly string SqlCountMisfiredTriggersInStates = string.Format("SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4} AND {5} <> {6} AND {7} < @nextFireTime AND {8} = @state1", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnTriggerState); public static readonly string SqlSelectHasMisfiredTriggersInState = string.Format("SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} <> {7} AND {8} < @nextFireTime AND {9} = @state1 ORDER BY {10} ASC, {11} DESC", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnMifireInstruction, (int)MisfireInstruction.IgnoreMisfirePolicy, ColumnNextFireTime, ColumnTriggerState, ColumnNextFireTime, ColumnPriority); public static readonly string SqlSelectNextTriggerToAcquire = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1}, {2}, {3} FROM {4}{5} WHERE {6} = {7} AND {8} = @state AND {9} <= @noLaterThan AND ({10} = -1 OR ({10} <> -1 AND {9} >= @noEarlierThan)) ORDER BY {9} ASC, {11} DESC", ColumnTriggerName, ColumnTriggerGroup, ColumnNextFireTime, ColumnPriority, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerState, ColumnNextFireTime, ColumnMifireInstruction, ColumnPriority); public static readonly string SqlSelectNumCalendars = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnCalendarName, TablePrefixSubst, TableCalendars, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectNumJobs = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnJobName, TablePrefixSubst, TableJobDetails, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectNumTriggers = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectNumTriggersForJob = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectNumTriggersInGroup = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT({0}) FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerGroup", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectPausedTriggerGroup = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerGroup", ColumnTriggerGroup, TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectPausedTriggerGroups = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4}", ColumnTriggerGroup, TablePrefixSubst, TablePausedTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectReferencedCalendar = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @calendarName", ColumnCalendarName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlSelectSchedulerState = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @instanceName", TablePrefixSubst, TableSchedulerState, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlSelectSchedulerStates = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3}", TablePrefixSubst, TableSchedulerState, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectSimpleTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableSimpleTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTrigger = string.Format(CultureInfo.InvariantCulture, "SELECT {6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17} FROM {0}{1} WHERE {2} = {3} AND {4} = @triggerName AND {5} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnNextFireTime, ColumnPreviousFireTime, ColumnTriggerType, ColumnStartTime, ColumnEndTime, ColumnCalendarName, ColumnMifireInstruction, ColumnPriority, ColumnJobDataMap); public static readonly string SqlSelectTriggerData = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", ColumnJobDataMap, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTriggerExistence = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", ColumnTriggerName, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTriggerForFireTime = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @state AND {7} = @nextFireTime", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerState, ColumnNextFireTime); public static readonly string SqlSelectTriggerGroups = string.Format(CultureInfo.InvariantCulture, "SELECT DISTINCT({0}) FROM {1}{2} WHERE {3} = {4}", ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectTriggerGroupsFiltered = string.Format(CultureInfo.InvariantCulture, "SELECT DISTINCT({0}) FROM {1}{2} WHERE {3} = {4} AND {0} LIKE @triggerGroup", ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst); public static readonly string SqlSelectTriggerState = string.Format(CultureInfo.InvariantCulture, "SELECT {0} FROM {1}{2} WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", ColumnTriggerState, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTriggerStatus = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1}, {2}, {3} FROM {4}{5} WHERE {6} = {7} AND {8} = @triggerName AND {9} = @triggerGroup", ColumnTriggerState, ColumnNextFireTime, ColumnJobName, ColumnJobGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlSelectTriggersForCalendar = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @calendarName", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlSelectTriggersForJob = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @jobName AND {7} = @jobGroup", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlSelectTriggersInGroupLike = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} LIKE @triggerGroup", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectTriggersInGroup = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @triggerGroup", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup); public static readonly string SqlSelectTriggersInState = string.Format(CultureInfo.InvariantCulture, "SELECT {0}, {1} FROM {2}{3} WHERE {4} = {5} AND {6} = @state", ColumnTriggerName, ColumnTriggerGroup, TablePrefixSubst, TableTriggers, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerState); // UPDATE public static readonly string SqlUpdateBlobTrigger = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @blob WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", TablePrefixSubst, TableBlobTriggers, ColumnBlob, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateCalendar = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @calendar WHERE {3} = {4} AND {5} = @calendarName", TablePrefixSubst, TableCalendars, ColumnCalendar, ColumnSchedulerName, SchedulerNameSubst, ColumnCalendarName); public static readonly string SqlUpdateCronTrigger = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @triggerCronExpression, {3} = @timeZoneId WHERE {4} = {5} AND {6} = @triggerName AND {7} = @triggerGroup", TablePrefixSubst, TableCronTriggers, ColumnCronExpression, ColumnTimeZoneId, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateJobData = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @jobDataMap WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", TablePrefixSubst, TableJobDetails, ColumnJobDataMap, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlUpdateJobDetail = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @jobDescription, {3} = @jobType, {4} = @jobDurable, {5} = @jobVolatile, {6} = @jobStateful, {7} = @jobRequestsRecovery, {8} = @jobDataMap WHERE {9} = {10} AND {11} = @jobName AND {12} = @jobGroup", TablePrefixSubst, TableJobDetails, ColumnDescription, ColumnJobClass, ColumnIsDurable, ColumnIsNonConcurrent, ColumnIsUpdateData, ColumnRequestsRecovery, ColumnJobDataMap, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlUpdateJobTriggerStates = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @state WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup); public static readonly string SqlUpdateJobTriggerStatesFromOtherState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @state WHERE {3} = {4} AND {5} = @jobName AND {6} = @jobGroup AND {7} = @oldState", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnJobName, ColumnJobGroup, ColumnTriggerState); public static readonly string SqlUpdateSchedulerState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @lastCheckinTime WHERE {3} = {4} AND {5} = @instanceName", TablePrefixSubst, TableSchedulerState, ColumnLastCheckinTime, ColumnSchedulerName, SchedulerNameSubst, ColumnInstanceName); public static readonly string SqlUpdateSimpleTrigger = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @triggerRepeatCount, {3} = @triggerRepeatInterval, {4} = @triggerTimesTriggered WHERE {5} = {6} AND {7} = @triggerName AND {8} = @triggerGroup", TablePrefixSubst, TableSimpleTriggers, ColumnRepeatCount, ColumnRepeatInterval, ColumnTimesTriggered, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateTrigger = string.Format(CultureInfo.InvariantCulture, @"UPDATE {0}{1} SET {2} = @triggerJobName, {3} = @triggerJobGroup, {4} = @triggerDescription, {5} = @triggerNextFireTime, {6} = @triggerPreviousFireTime, {7} = @triggerState, {8} = @triggerType, {9} = @triggerStartTime, {10} = @triggerEndTime, {11} = @triggerCalendarName, {12} = @triggerMisfireInstruction, {13} = @triggerPriority, {14} = @triggerJobJobDataMap WHERE {15} = {16} AND {17} = @triggerName AND {18} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnNextFireTime, ColumnPreviousFireTime, ColumnTriggerState, ColumnTriggerType, ColumnStartTime, ColumnEndTime, ColumnCalendarName, ColumnMifireInstruction, ColumnPriority, ColumnJobDataMap, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateFiredTrigger = string.Format( CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @instanceName, {3} = @firedTime, {12} = @scheduledTime, {4} = @entryState, {5} = @jobName, {6} = @jobGroup, {7} = @isNonConcurrent, {8} = @requestsRecover WHERE {9} = {10} AND {11} = @entryId", TablePrefixSubst, TableFiredTriggers, ColumnInstanceName, ColumnFiredTime, ColumnEntryState, ColumnJobName, ColumnJobGroup, ColumnIsNonConcurrent, ColumnRequestsRecovery, ColumnSchedulerName, SchedulerNameSubst, ColumnEntryId, ColumnScheduledTime); public static readonly string SqlUpdateTriggerGroupStateFromState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND {5} LIKE @triggerGroup AND {6} = @oldState", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup, ColumnTriggerState); public static readonly string SqlUpdateTriggerGroupStateFromStates = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND {5} LIKE @groupName AND ({6} = @oldState1 OR {7} = @oldState2 OR {8} = @oldState3)", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerGroup, ColumnTriggerState, ColumnTriggerState, ColumnTriggerState); public static readonly string SqlUpdateTriggerSkipData = string.Format(CultureInfo.InvariantCulture, @"UPDATE {0}{1} SET {2} = @triggerJobName, {3} = @triggerJobGroup, {4} = @triggerDescription, {5} = @triggerNextFireTime, {6} = @triggerPreviousFireTime, {7} = @triggerState, {8} = @triggerType, {9} = @triggerStartTime, {10} = @triggerEndTime, {11} = @triggerCalendarName, {12} = @triggerMisfireInstruction, {13} = @triggerPriority WHERE {14} = {15} AND {16} = @triggerName AND {17} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnJobName, ColumnJobGroup, ColumnDescription, ColumnNextFireTime, ColumnPreviousFireTime, ColumnTriggerState, ColumnTriggerType, ColumnStartTime, ColumnEndTime, ColumnCalendarName, ColumnMifireInstruction, ColumnPriority, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateTriggerState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @state WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup); public static readonly string SqlUpdateTriggerStateFromState = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup AND {7} = @oldState", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnTriggerState); public static readonly string SqlUpdateTriggerStateFromStates = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND {5} = @triggerName AND {6} = @triggerGroup AND ({7} = @oldState1 OR {8} = @oldState2 OR {9} = @oldState3)", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerName, ColumnTriggerGroup, ColumnTriggerState, ColumnTriggerState, ColumnTriggerState); public static readonly string SqlUpdateTriggerStatesFromOtherStates = string.Format(CultureInfo.InvariantCulture, "UPDATE {0}{1} SET {2} = @newState WHERE {3} = {4} AND ({5} = @oldState1 OR {6} = @oldState2)", TablePrefixSubst, TableTriggers, ColumnTriggerState, ColumnSchedulerName, SchedulerNameSubst, ColumnTriggerState, ColumnTriggerState); } }
using System; using System.Globalization; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// Extensible enum type used in many places. /// compared to the base class, this one /// adds a default value which is the text content inside the /// element node. /// </summary> public abstract class SimpleElement : ExtensionBase { private string value; /// <summary> /// constructor /// </summary> /// <param name="name">the xml name</param> /// <param name="prefix">the xml prefix</param> /// <param name="ns">the xml namespace</param> protected SimpleElement(string name, string prefix, string ns) : base(name, prefix, ns) { } /// <summary> /// constructor /// </summary> /// <param name="name">the xml name</param> /// <param name="prefix">the xml prefix</param> /// <param name="ns">the xml namespace</param> /// <param name="value">the intial value</param> protected SimpleElement(string name, string prefix, string ns, string value) : base(name, prefix, ns) { this.value = value; } /// <summary> /// Accessor Method for the value as string /// </summary> public virtual string Value { get { return value; } set { this.value = value; } } /// <summary> /// Accessor Method for the value as integer /// </summary> public int IntegerValue { get { return Convert.ToInt32(Value, CultureInfo.InvariantCulture); } set { Value = value.ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Accessor Method for the value as unsigned integer /// </summary> [CLSCompliant(false)] public uint UnsignedIntegerValue { get { return Convert.ToUInt32(Value, CultureInfo.InvariantCulture); } set { Value = value.ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Accessor Method for the value as unsigned long /// </summary> [CLSCompliant(false)] public ulong UnsignedLongValue { get { return Convert.ToUInt64(Value, CultureInfo.InvariantCulture); } set { Value = value.ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Accessor Method for the value as float /// </summary> public double FloatValue { get { return Convert.ToDouble(Value, CultureInfo.InvariantCulture); } set { Value = value.ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Accessor Method for the value as boolean /// </summary> public virtual bool BooleanValue { get { return Utilities.XSDTrue == Value; } set { Value = value ? Utilities.XSDTrue : Utilities.XSDFalse; } } #region overloaded for persistence /// <summary> /// debugging helper /// </summary> /// <returns></returns> public override string ToString() { return base.ToString() + " for: " + XmlNameSpace + " - " + XmlName; } /// <summary>Parses an xml node to create an instance object.</summary> /// <param name="node">the parsed xml node, can be NULL</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created SimpleElement object</returns> public override IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall(); SimpleElement e = null; if (node != null) { object localname = node.LocalName; if (!localname.Equals(XmlName) || !node.NamespaceURI.Equals(XmlNameSpace)) { return null; } } // memberwise close is fine here, as everything is identical besides the value e = MemberwiseClone() as SimpleElement; e.InitInstance(this); if (node != null) { e.ProcessAttributes(node); if (node.HasChildNodes) { XmlNode n = node.ChildNodes[0]; if (n.NodeType == XmlNodeType.Text && node.ChildNodes.Count == 1) { e.Value = node.InnerText; } else { e.ProcessChildNodes(node, parser); } } } return e; } /// <summary> /// saves the value, is called from Save /// </summary> /// <param name="writer"></param> public override void SaveInnerXml(XmlWriter writer) { if (value != null) { writer.WriteString(value); } } #endregion } /// <summary> /// a simple element with one attribute, called value, that exposes /// the given value as the Value property /// </summary> public abstract class SimpleAttribute : SimpleElement { /// <summary> /// constructor /// </summary> /// <param name="name">the xml name</param> /// <param name="prefix">the xml prefix</param> /// <param name="ns">the xml namespace</param> protected SimpleAttribute(string name, string prefix, string ns) : base(name, prefix, ns) { Attributes.Add(BaseNameTable.XmlValue, null); } /// <summary> /// constructor /// </summary> /// <param name="name">the xml name</param> /// <param name="prefix">the xml prefix</param> /// <param name="ns">the xml namespace</param> /// <param name="value">the initial value</param> protected SimpleAttribute(string name, string prefix, string ns, string value) : base(name, prefix, ns) { Attributes.Add(BaseNameTable.XmlValue, value); } /// <summary>Accessor for "value" attribute.</summary> /// <returns> </returns> public override string Value { get { return Attributes[BaseNameTable.XmlValue] as string; } set { Attributes[BaseNameTable.XmlValue] = value; } } } /// <summary> /// a simple element with two attributes, called value and name, that exposes /// the given value as the Value property /// </summary> public abstract class SimpleNameValueAttribute : SimpleAttribute { /// <summary> /// constructor /// </summary> /// <param name="name">the xml name</param> /// <param name="prefix">the xml prefix</param> /// <param name="ns">the xml namespace</param> protected SimpleNameValueAttribute(string localName, string prefix, string ns) : base(localName, prefix, ns) { Attributes.Add(BaseNameTable.XmlName, null); } /// <summary>Accessor for "name" attribute.</summary> /// <returns> </returns> public string Name { get { return Attributes[BaseNameTable.XmlName] as string; } set { Attributes[BaseNameTable.XmlName] = value; } } } }
using System; using System.Collections.Generic; using Avalonia.Data; using Avalonia.Utilities; using Xunit; namespace Avalonia.Base.UnitTests { public class AvaloniaPropertyTests { [Fact] public void Constructor_Sets_Properties() { var target = new TestProperty<string>("test", typeof(Class1)); Assert.Equal("test", target.Name); Assert.Equal(typeof(string), target.PropertyType); Assert.Equal(typeof(Class1), target.OwnerType); } [Fact] public void Name_Cannot_Contain_Periods() { Assert.Throws<ArgumentException>(() => new TestProperty<string>("Foo.Bar", typeof(Class1))); } [Fact] public void GetMetadata_Returns_Supplied_Value() { var metadata = new AvaloniaPropertyMetadata(); var target = new TestProperty<string>("test", typeof(Class1), metadata); Assert.Same(metadata, target.GetMetadata<Class1>()); } [Fact] public void GetMetadata_Returns_Supplied_Value_For_Derived_Class() { var metadata = new AvaloniaPropertyMetadata(); var target = new TestProperty<string>("test", typeof(Class1), metadata); Assert.Same(metadata, target.GetMetadata<Class2>()); } [Fact] public void GetMetadata_Returns_Supplied_Value_For_Unrelated_Class() { var metadata = new AvaloniaPropertyMetadata(); var target = new TestProperty<string>("test", typeof(Class3), metadata); Assert.Same(metadata, target.GetMetadata<Class2>()); } [Fact] public void GetMetadata_Returns_Overridden_Value() { var metadata = new AvaloniaPropertyMetadata(); var overridden = new AvaloniaPropertyMetadata(); var target = new TestProperty<string>("test", typeof(Class1), metadata); target.OverrideMetadata<Class2>(overridden); Assert.Same(overridden, target.GetMetadata<Class2>()); } [Fact] public void OverrideMetadata_Should_Merge_Values() { var metadata = new AvaloniaPropertyMetadata(BindingMode.TwoWay); var notify = (Action<IAvaloniaObject, bool>)((a, b) => { }); var overridden = new AvaloniaPropertyMetadata(); var target = new TestProperty<string>("test", typeof(Class1), metadata); target.OverrideMetadata<Class2>(overridden); var result = target.GetMetadata<Class2>(); Assert.Equal(BindingMode.TwoWay, result.DefaultBindingMode); } [Fact] public void Changed_Observable_Fired() { var target = new Class1(); string value = null; Class1.FooProperty.Changed.Subscribe(x => value = x.NewValue.GetValueOrDefault()); target.SetValue(Class1.FooProperty, "newvalue"); Assert.Equal("newvalue", value); } [Fact] public void Changed_Observable_Fired_Only_On_Effective_Value_Change() { var target = new Class1(); var result = new List<string>(); Class1.FooProperty.Changed.Subscribe(x => result.Add(x.NewValue.GetValueOrDefault())); target.SetValue(Class1.FooProperty, "animated", BindingPriority.Animation); target.SetValue(Class1.FooProperty, "local"); Assert.Equal(new[] { "animated" }, result); } [Fact] public void Notify_Fired_Only_On_Effective_Value_Change() { var target = new Class1(); target.SetValue(Class1.FooProperty, "animated", BindingPriority.Animation); target.SetValue(Class1.FooProperty, "local"); Assert.Equal(2, target.NotifyCount); } [Fact] public void Property_Equals_Should_Handle_Null() { var p1 = new TestProperty<string>("p1", typeof(Class1)); Assert.NotNull(p1); Assert.NotNull(p1); Assert.False(p1 == null); Assert.False(null == p1); Assert.False(p1.Equals(null)); Assert.True((AvaloniaProperty)null == (AvaloniaProperty)null); } [Fact] public void PropertyMetadata_BindingMode_Default_Returns_OneWay() { var data = new AvaloniaPropertyMetadata(defaultBindingMode: BindingMode.Default); Assert.Equal(BindingMode.OneWay, data.DefaultBindingMode); } private class TestProperty<TValue> : AvaloniaProperty<TValue> { public TestProperty(string name, Type ownerType, AvaloniaPropertyMetadata metadata = null) : base(name, ownerType, metadata ?? new AvaloniaPropertyMetadata()) { } public void OverrideMetadata<T>(AvaloniaPropertyMetadata metadata) { OverrideMetadata(typeof(T), metadata); } public override void Accept<TData>(IAvaloniaPropertyVisitor<TData> vistor, ref TData data) { throw new NotImplementedException(); } internal override IDisposable RouteBind( IAvaloniaObject o, IObservable<BindingValue<object>> source, BindingPriority priority) { throw new NotImplementedException(); } internal override void RouteClearValue(IAvaloniaObject o) { throw new NotImplementedException(); } internal override object RouteGetValue(IAvaloniaObject o) { throw new NotImplementedException(); } internal override object RouteGetBaseValue(IAvaloniaObject o, BindingPriority maxPriority) { throw new NotImplementedException(); } internal override void RouteInheritanceParentChanged(AvaloniaObject o, IAvaloniaObject oldParent) { throw new NotImplementedException(); } internal override IDisposable RouteSetValue( IAvaloniaObject o, object value, BindingPriority priority) { throw new NotImplementedException(); } } private class Class1 : AvaloniaObject { public static readonly StyledProperty<string> FooProperty = AvaloniaProperty.Register<Class1, string>("Foo", "default", notifying: FooNotifying); public int NotifyCount { get; private set; } private static void FooNotifying(IAvaloniaObject o, bool n) { ++((Class1)o).NotifyCount; } } private class Class2 : Class1 { } private class Class3 : AvaloniaObject { } } }
// 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.Net.Sockets { public enum AddressFamily { AppleTalk = 16, Atm = 22, Banyan = 21, Ccitt = 10, Chaos = 5, Cluster = 24, DataKit = 9, DataLink = 13, DecNet = 12, Ecma = 8, FireFox = 19, HyperChannel = 15, Ieee12844 = 25, ImpLink = 3, InterNetwork = 2, InterNetworkV6 = 23, Ipx = 6, Irda = 26, Iso = 7, Lat = 14, Max = 29, NetBios = 17, NetworkDesigners = 28, NS = 6, Osi = 7, Pup = 4, Sna = 11, Unix = 1, Unknown = -1, Unspecified = 0, VoiceView = 18, } public enum IOControlCode : long { AbsorbRouterAlert = (long)2550136837, AddMulticastGroupOnInterface = (long)2550136842, AddressListChange = (long)671088663, AddressListQuery = (long)1207959574, AddressListSort = (long)3355443225, AssociateHandle = (long)2281701377, AsyncIO = (long)2147772029, BindToInterface = (long)2550136840, DataToRead = (long)1074030207, DeleteMulticastGroupFromInterface = (long)2550136843, EnableCircularQueuing = (long)671088642, Flush = (long)671088644, GetBroadcastAddress = (long)1207959557, GetExtensionFunctionPointer = (long)3355443206, GetGroupQos = (long)3355443208, GetQos = (long)3355443207, KeepAliveValues = (long)2550136836, LimitBroadcasts = (long)2550136839, MulticastInterface = (long)2550136841, MulticastScope = (long)2281701386, MultipointLoopback = (long)2281701385, NamespaceChange = (long)2281701401, NonBlockingIO = (long)2147772030, OobDataRead = (long)1074033415, QueryTargetPnpHandle = (long)1207959576, ReceiveAll = (long)2550136833, ReceiveAllIgmpMulticast = (long)2550136835, ReceiveAllMulticast = (long)2550136834, RoutingInterfaceChange = (long)2281701397, RoutingInterfaceQuery = (long)3355443220, SetGroupQos = (long)2281701388, SetQos = (long)2281701387, TranslateHandle = (long)3355443213, UnicastInterface = (long)2550136838, } public partial struct IPPacketInformation { private object _dummy; public System.Net.IPAddress Address { get { throw null; } } public int Interface { get { throw null; } } public override bool Equals(object comparand) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; } public static bool operator !=(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; } } public enum IPProtectionLevel { EdgeRestricted = 20, Restricted = 30, Unrestricted = 10, Unspecified = -1, } public partial class IPv6MulticastOption { public IPv6MulticastOption(System.Net.IPAddress group) { } public IPv6MulticastOption(System.Net.IPAddress group, long ifindex) { } public System.Net.IPAddress Group { get { throw null; } set { } } public long InterfaceIndex { get { throw null; } set { } } } public partial class LingerOption { public LingerOption(bool enable, int seconds) { } public bool Enabled { get { throw null; } set { } } public int LingerTime { get { throw null; } set { } } } public partial class MulticastOption { public MulticastOption(System.Net.IPAddress group) { } public MulticastOption(System.Net.IPAddress group, int interfaceIndex) { } public MulticastOption(System.Net.IPAddress group, System.Net.IPAddress mcint) { } public System.Net.IPAddress Group { get { throw null; } set { } } public int InterfaceIndex { get { throw null; } set { } } public System.Net.IPAddress LocalAddress { get { throw null; } set { } } } public partial class NetworkStream : System.IO.Stream { public NetworkStream(System.Net.Sockets.Socket socket) { } public NetworkStream(System.Net.Sockets.Socket socket, bool ownsSocket) { } public NetworkStream(System.Net.Sockets.Socket socket, System.IO.FileAccess access) { } public NetworkStream(System.Net.Sockets.Socket socket, System.IO.FileAccess access, bool ownsSocket) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanTimeout { get { throw null; } } public override bool CanWrite { get { throw null; } } public virtual bool DataAvailable { get { throw null; } } public override long Length { get { throw null; } } public override long Position { get { throw null; } set { } } protected bool Readable { get { throw null; } set { } } public override int ReadTimeout { get { throw null; } set { } } protected System.Net.Sockets.Socket Socket { get { throw null; } } protected bool Writeable { get { throw null; } set { } } public override int WriteTimeout { get { throw null; } set { } } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int size, System.AsyncCallback callback, object state) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int size, System.AsyncCallback callback, object state) { throw null; } public void Close(int timeout) { } protected override void Dispose(bool disposing) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { } ~NetworkStream() { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public override int Read(byte[] buffer, int offset, int size) { throw null; } public override int Read(System.Span<byte> buffer) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int size, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override int ReadByte() { throw null; } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int size) { } public override void Write(System.ReadOnlySpan<byte> buffer) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int size, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override void WriteByte(byte value) { } } public enum ProtocolFamily { AppleTalk = 16, Atm = 22, Banyan = 21, Ccitt = 10, Chaos = 5, Cluster = 24, DataKit = 9, DataLink = 13, DecNet = 12, Ecma = 8, FireFox = 19, HyperChannel = 15, Ieee12844 = 25, ImpLink = 3, InterNetwork = 2, InterNetworkV6 = 23, Ipx = 6, Irda = 26, Iso = 7, Lat = 14, Max = 29, NetBios = 17, NetworkDesigners = 28, NS = 6, Osi = 7, Pup = 4, Sna = 11, Unix = 1, Unknown = -1, Unspecified = 0, VoiceView = 18, } public enum ProtocolType { Ggp = 3, Icmp = 1, IcmpV6 = 58, Idp = 22, Igmp = 2, IP = 0, IPSecAuthenticationHeader = 51, IPSecEncapsulatingSecurityPayload = 50, IPv4 = 4, IPv6 = 41, IPv6DestinationOptions = 60, IPv6FragmentHeader = 44, IPv6HopByHopOptions = 0, IPv6NoNextHeader = 59, IPv6RoutingHeader = 43, Ipx = 1000, ND = 77, Pup = 12, Raw = 255, Spx = 1256, SpxII = 1257, Tcp = 6, Udp = 17, Unknown = -1, Unspecified = 0, } public enum SelectMode { SelectError = 2, SelectRead = 0, SelectWrite = 1, } public partial class SendPacketsElement { public SendPacketsElement(byte[] buffer) { } public SendPacketsElement(byte[] buffer, int offset, int count) { } public SendPacketsElement(byte[] buffer, int offset, int count, bool endOfPacket) { } public SendPacketsElement(string filepath) { } public SendPacketsElement(string filepath, int offset, int count) { } public SendPacketsElement(string filepath, int offset, int count, bool endOfPacket) { } public byte[] Buffer { get { throw null; } } public int Count { get { throw null; } } public bool EndOfPacket { get { throw null; } } public string FilePath { get { throw null; } } public int Offset { get { throw null; } } } public partial class Socket : System.IDisposable { public Socket(System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } public Socket(System.Net.Sockets.SocketInformation socketInformation) { } public Socket(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } public System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } } public int Available { get { throw null; } } public bool Blocking { get { throw null; } set { } } public bool Connected { get { throw null; } } public bool DontFragment { get { throw null; } set { } } public bool DualMode { get { throw null; } set { } } public bool EnableBroadcast { get { throw null; } set { } } public bool ExclusiveAddressUse { get { throw null; } set { } } public System.IntPtr Handle { get { throw null; } } public bool IsBound { get { throw null; } } public System.Net.Sockets.LingerOption LingerState { get { throw null; } set { } } public System.Net.EndPoint LocalEndPoint { get { throw null; } } public bool MulticastLoopback { get { throw null; } set { } } public bool NoDelay { get { throw null; } set { } } public static bool OSSupportsIPv4 { get { throw null; } } public static bool OSSupportsIPv6 { get { throw null; } } public System.Net.Sockets.ProtocolType ProtocolType { get { throw null; } } public int ReceiveBufferSize { get { throw null; } set { } } public int ReceiveTimeout { get { throw null; } set { } } public System.Net.EndPoint RemoteEndPoint { get { throw null; } } public int SendBufferSize { get { throw null; } set { } } public int SendTimeout { get { throw null; } set { } } public System.Net.Sockets.SocketType SocketType { get { throw null; } } [System.ObsoleteAttribute("SupportsIPv4 is obsoleted for this type, please use OSSupportsIPv4 instead. https://go.microsoft.com/fwlink/?linkid=14202")] public static bool SupportsIPv4 { get { throw null; } } [System.ObsoleteAttribute("SupportsIPv6 is obsoleted for this type, please use OSSupportsIPv6 instead. https://go.microsoft.com/fwlink/?linkid=14202")] public static bool SupportsIPv6 { get { throw null; } } public short Ttl { get { throw null; } set { } } public bool UseOnlyOverlappedIO { get { throw null; } set { } } public System.Net.Sockets.Socket Accept() { throw null; } public bool AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public System.IAsyncResult BeginAccept(System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginAccept(int receiveSize, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginAccept(System.Net.Sockets.Socket acceptSocket, int receiveSize, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback requestCallback, object state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback requestCallback, object state) { throw null; } public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback requestCallback, object state) { throw null; } public System.IAsyncResult BeginDisconnect(bool reuseSocket, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSendFile(string fileName, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; } public void Bind(System.Net.EndPoint localEP) { } public static void CancelConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { } public void Close() { } public void Close(int timeout) { } public void Connect(System.Net.EndPoint remoteEP) { } public void Connect(System.Net.IPAddress address, int port) { } public void Connect(System.Net.IPAddress[] addresses, int port) { } public void Connect(string host, int port) { } public bool ConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public static bool ConnectAsync(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType, System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public void Disconnect(bool reuseSocket) { } public bool DisconnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.Net.Sockets.SocketInformation DuplicateAndClose(int targetProcessId) { throw null; } public System.Net.Sockets.Socket EndAccept(out byte[] buffer, System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.Socket EndAccept(out byte[] buffer, out int bytesTransferred, System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.Socket EndAccept(System.IAsyncResult asyncResult) { throw null; } public void EndConnect(System.IAsyncResult asyncResult) { } public void EndDisconnect(System.IAsyncResult asyncResult) { } public int EndReceive(System.IAsyncResult asyncResult) { throw null; } public int EndReceive(System.IAsyncResult asyncResult, out System.Net.Sockets.SocketError errorCode) { throw null; } public int EndReceiveFrom(System.IAsyncResult asyncResult, ref System.Net.EndPoint endPoint) { throw null; } public int EndReceiveMessageFrom(System.IAsyncResult asyncResult, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint endPoint, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; } public int EndSend(System.IAsyncResult asyncResult) { throw null; } public int EndSend(System.IAsyncResult asyncResult, out System.Net.Sockets.SocketError errorCode) { throw null; } public void EndSendFile(System.IAsyncResult asyncResult) { } public int EndSendTo(System.IAsyncResult asyncResult) { throw null; } ~Socket() { } public object GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { throw null; } public void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionLength) { throw null; } public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue) { throw null; } public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue) { throw null; } public void Listen(int backlog) { } public bool Poll(int microSeconds, System.Net.Sockets.SelectMode mode) { throw null; } public int Receive(byte[] buffer) { throw null; } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Receive(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Receive(System.Span<byte> buffer) { throw null; } public int Receive(System.Span<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Span<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public bool ReceiveAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int ReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public bool ReceiveFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; } public bool ReceiveMessageFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public static void Select(System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, int microSeconds) { } public int Send(byte[] buffer) { throw null; } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Send(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public bool SendAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public void SendFile(string fileName) { } public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, System.Net.Sockets.TransmitFileOptions flags) { } public bool SendPacketsAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int SendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public bool SendToAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public void SetIPProtectionLevel(System.Net.Sockets.IPProtectionLevel level) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, bool optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, object optionValue) { } public void Shutdown(System.Net.Sockets.SocketShutdown how) { } } public partial class SocketAsyncEventArgs : System.EventArgs, System.IDisposable { public SocketAsyncEventArgs() { } public System.Net.Sockets.Socket AcceptSocket { get { throw null; } set { } } public byte[] Buffer { get { throw null; } } public System.Collections.Generic.IList<System.ArraySegment<byte>> BufferList { get { throw null; } set { } } public int BytesTransferred { get { throw null; } } public System.Exception ConnectByNameError { get { throw null; } } public System.Net.Sockets.Socket ConnectSocket { get { throw null; } } public int Count { get { throw null; } } public bool DisconnectReuseSocket { get { throw null; } set { } } public System.Net.Sockets.SocketAsyncOperation LastOperation { get { throw null; } } public System.Memory<byte> MemoryBuffer { get { throw null; } } public int Offset { get { throw null; } } public System.Net.Sockets.IPPacketInformation ReceiveMessageFromPacketInfo { get { throw null; } } public System.Net.EndPoint RemoteEndPoint { get { throw null; } set { } } public System.Net.Sockets.SendPacketsElement[] SendPacketsElements { get { throw null; } set { } } public System.Net.Sockets.TransmitFileOptions SendPacketsFlags { get { throw null; } set { } } public int SendPacketsSendSize { get { throw null; } set { } } public System.Net.Sockets.SocketError SocketError { get { throw null; } set { } } public System.Net.Sockets.SocketFlags SocketFlags { get { throw null; } set { } } public object UserToken { get { throw null; } set { } } public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs> Completed { add { } remove { } } public void Dispose() { } ~SocketAsyncEventArgs() { } protected virtual void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { } public void SetBuffer(byte[] buffer, int offset, int count) { } public void SetBuffer(int offset, int count) { } public void SetBuffer(System.Memory<byte> buffer) { } } public enum SocketAsyncOperation { Accept = 1, Connect = 2, Disconnect = 3, None = 0, Receive = 4, ReceiveFrom = 5, ReceiveMessageFrom = 6, Send = 7, SendPackets = 8, SendTo = 9, } public enum SocketError { AccessDenied = 10013, AddressAlreadyInUse = 10048, AddressFamilyNotSupported = 10047, AddressNotAvailable = 10049, AlreadyInProgress = 10037, ConnectionAborted = 10053, ConnectionRefused = 10061, ConnectionReset = 10054, DestinationAddressRequired = 10039, Disconnecting = 10101, Fault = 10014, HostDown = 10064, HostNotFound = 11001, HostUnreachable = 10065, InProgress = 10036, Interrupted = 10004, InvalidArgument = 10022, IOPending = 997, IsConnected = 10056, MessageSize = 10040, NetworkDown = 10050, NetworkReset = 10052, NetworkUnreachable = 10051, NoBufferSpaceAvailable = 10055, NoData = 11004, NoRecovery = 11003, NotConnected = 10057, NotInitialized = 10093, NotSocket = 10038, OperationAborted = 995, OperationNotSupported = 10045, ProcessLimit = 10067, ProtocolFamilyNotSupported = 10046, ProtocolNotSupported = 10043, ProtocolOption = 10042, ProtocolType = 10041, Shutdown = 10058, SocketError = -1, SocketNotSupported = 10044, Success = 0, SystemNotReady = 10091, TimedOut = 10060, TooManyOpenSockets = 10024, TryAgain = 11002, TypeNotFound = 10109, VersionNotSupported = 10092, WouldBlock = 10035, } public partial class SocketException : System.ComponentModel.Win32Exception { public SocketException() { } public SocketException(int errorCode) { } protected SocketException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public override int ErrorCode { get { throw null; } } public override string Message { get { throw null; } } public System.Net.Sockets.SocketError SocketErrorCode { get { throw null; } } } [System.FlagsAttribute] public enum SocketFlags { Broadcast = 1024, ControlDataTruncated = 512, DontRoute = 4, // Enum value isn't used but keeping commented out so we don't reuse the slot in the future // MaxIOVectorLength = 16, Multicast = 2048, None = 0, OutOfBand = 1, Partial = 32768, Peek = 2, Truncated = 256, } public partial struct SocketInformation { private object _dummy; public System.Net.Sockets.SocketInformationOptions Options { get { throw null; } set { } } public byte[] ProtocolInformation { get { throw null; } set { } } } [System.FlagsAttribute] public enum SocketInformationOptions { Connected = 2, Listening = 4, NonBlocking = 1, UseOnlyOverlappedIO = 8, } public enum SocketOptionLevel { IP = 0, IPv6 = 41, Socket = 65535, Tcp = 6, Udp = 17, } public enum SocketOptionName { AcceptConnection = 2, AddMembership = 12, AddSourceMembership = 15, BlockSource = 17, Broadcast = 32, BsdUrgent = 2, ChecksumCoverage = 20, Debug = 1, DontFragment = 14, DontLinger = -129, DontRoute = 16, DropMembership = 13, DropSourceMembership = 16, Error = 4103, ExclusiveAddressUse = -5, Expedited = 2, HeaderIncluded = 2, HopLimit = 21, IPOptions = 1, IPProtectionLevel = 23, IpTimeToLive = 4, IPv6Only = 27, KeepAlive = 8, Linger = 128, MaxConnections = 2147483647, MulticastInterface = 9, MulticastLoopback = 11, MulticastTimeToLive = 10, NoChecksum = 1, NoDelay = 1, OutOfBandInline = 256, PacketInformation = 19, ReceiveBuffer = 4098, ReceiveLowWater = 4100, ReceiveTimeout = 4102, ReuseAddress = 4, ReuseUnicastPort = 12295, SendBuffer = 4097, SendLowWater = 4099, SendTimeout = 4101, Type = 4104, TypeOfService = 3, UnblockSource = 18, UpdateAcceptContext = 28683, UpdateConnectContext = 28688, UseLoopback = 64, } public partial struct SocketReceiveFromResult { public int ReceivedBytes; public System.Net.EndPoint RemoteEndPoint; } public partial struct SocketReceiveMessageFromResult { public System.Net.Sockets.IPPacketInformation PacketInformation; public int ReceivedBytes; public System.Net.EndPoint RemoteEndPoint; public System.Net.Sockets.SocketFlags SocketFlags; } public enum SocketShutdown { Both = 2, Receive = 0, Send = 1, } public static partial class SocketTaskExtensions { public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket) { throw null; } public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket acceptSocket) { throw null; } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP) { throw null; } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port) { throw null; } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port) { throw null; } public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, string host, int port) { throw null; } public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public static System.Threading.Tasks.ValueTask<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public static System.Threading.Tasks.ValueTask<int> SendAsync(this System.Net.Sockets.Socket socket, System.ReadOnlyMemory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.Threading.Tasks.Task<int> SendToAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } } public enum SocketType { Dgram = 2, Raw = 3, Rdm = 4, Seqpacket = 5, Stream = 1, Unknown = -1, } public partial class TcpClient : System.IDisposable { public TcpClient() { } public TcpClient(System.Net.IPEndPoint localEP) { } public TcpClient(System.Net.Sockets.AddressFamily family) { } public TcpClient(string hostname, int port) { } protected bool Active { get { throw null; } set { } } public int Available { get { throw null; } } public System.Net.Sockets.Socket Client { get { throw null; } set { } } public bool Connected { get { throw null; } } public bool ExclusiveAddressUse { get { throw null; } set { } } public System.Net.Sockets.LingerOption LingerState { get { throw null; } set { } } public bool NoDelay { get { throw null; } set { } } public int ReceiveBufferSize { get { throw null; } set { } } public int ReceiveTimeout { get { throw null; } set { } } public int SendBufferSize { get { throw null; } set { } } public int SendTimeout { get { throw null; } set { } } public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback requestCallback, object state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback requestCallback, object state) { throw null; } public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback requestCallback, object state) { throw null; } public void Close() { } public void Connect(System.Net.IPAddress address, int port) { } public void Connect(System.Net.IPAddress[] ipAddresses, int port) { } public void Connect(System.Net.IPEndPoint remoteEP) { } public void Connect(string hostname, int port) { } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress address, int port) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress[] addresses, int port) { throw null; } public System.Threading.Tasks.Task ConnectAsync(string host, int port) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void EndConnect(System.IAsyncResult asyncResult) { } ~TcpClient() { } public System.Net.Sockets.NetworkStream GetStream() { throw null; } } public partial class TcpListener { [System.ObsoleteAttribute("This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port) instead. https://go.microsoft.com/fwlink/?linkid=14202")] public TcpListener(int port) { } public TcpListener(System.Net.IPAddress localaddr, int port) { } public TcpListener(System.Net.IPEndPoint localEP) { } protected bool Active { get { throw null; } } public bool ExclusiveAddressUse { get { throw null; } set { } } public System.Net.EndPoint LocalEndpoint { get { throw null; } } public System.Net.Sockets.Socket Server { get { throw null; } } public System.Net.Sockets.Socket AcceptSocket() { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptSocketAsync() { throw null; } public System.Net.Sockets.TcpClient AcceptTcpClient() { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.TcpClient> AcceptTcpClientAsync() { throw null; } public void AllowNatTraversal(bool allowed) { } public System.IAsyncResult BeginAcceptSocket(System.AsyncCallback callback, object state) { throw null; } public System.IAsyncResult BeginAcceptTcpClient(System.AsyncCallback callback, object state) { throw null; } public static System.Net.Sockets.TcpListener Create(int port) { throw null; } public System.Net.Sockets.Socket EndAcceptSocket(System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.TcpClient EndAcceptTcpClient(System.IAsyncResult asyncResult) { throw null; } public bool Pending() { throw null; } public void Start() { } public void Start(int backlog) { } public void Stop() { } } [System.FlagsAttribute] public enum TransmitFileOptions { Disconnect = 1, ReuseSocket = 2, UseDefaultWorkerThread = 0, UseKernelApc = 32, UseSystemThread = 16, WriteBehind = 4, } public partial class UdpClient : System.IDisposable { public UdpClient() { } public UdpClient(int port) { } public UdpClient(int port, System.Net.Sockets.AddressFamily family) { } public UdpClient(System.Net.IPEndPoint localEP) { } public UdpClient(System.Net.Sockets.AddressFamily family) { } public UdpClient(string hostname, int port) { } protected bool Active { get { throw null; } set { } } public int Available { get { throw null; } } public System.Net.Sockets.Socket Client { get { throw null; } set { } } public bool DontFragment { get { throw null; } set { } } public bool EnableBroadcast { get { throw null; } set { } } public bool ExclusiveAddressUse { get { throw null; } set { } } public bool MulticastLoopback { get { throw null; } set { } } public short Ttl { get { throw null; } set { } } public void AllowNatTraversal(bool allowed) { } public System.IAsyncResult BeginReceive(System.AsyncCallback requestCallback, object state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.AsyncCallback requestCallback, object state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint, System.AsyncCallback requestCallback, object state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, System.AsyncCallback requestCallback, object state) { throw null; } public void Close() { } public void Connect(System.Net.IPAddress addr, int port) { } public void Connect(System.Net.IPEndPoint endPoint) { } public void Connect(string hostname, int port) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr, int ifindex) { } public byte[] EndReceive(System.IAsyncResult asyncResult, ref System.Net.IPEndPoint remoteEP) { throw null; } public int EndSend(System.IAsyncResult asyncResult) { throw null; } public void JoinMulticastGroup(int ifindex, System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, int timeToLive) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress) { } public byte[] Receive(ref System.Net.IPEndPoint remoteEP) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> ReceiveAsync() { throw null; } public int Send(byte[] dgram, int bytes) { throw null; } public int Send(byte[] dgram, int bytes, System.Net.IPEndPoint endPoint) { throw null; } public int Send(byte[] dgram, int bytes, string hostname, int port) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port) { throw null; } } public partial struct UdpReceiveResult : System.IEquatable<System.Net.Sockets.UdpReceiveResult> { private object _dummy; public UdpReceiveResult(byte[] buffer, System.Net.IPEndPoint remoteEndPoint) { throw null; } public byte[] Buffer { get { throw null; } } public System.Net.IPEndPoint RemoteEndPoint { get { throw null; } } public bool Equals(System.Net.Sockets.UdpReceiveResult other) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; } public static bool operator !=(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; } } public sealed partial class UnixDomainSocketEndPoint : System.Net.EndPoint { public UnixDomainSocketEndPoint(string path) { } } }
using System; using System.Runtime.InteropServices; namespace Godot { /// <summary> /// 2D axis-aligned bounding box using integers. Rect2i consists of a position, a size, and /// several utility functions. It is typically used for fast overlap tests. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Rect2i : IEquatable<Rect2i> { private Vector2i _position; private Vector2i _size; /// <summary> /// Beginning corner. Typically has values lower than End. /// </summary> /// <value>Directly uses a private field.</value> public Vector2i Position { get { return _position; } set { _position = value; } } /// <summary> /// Size from Position to End. Typically all components are positive. /// If the size is negative, you can use <see cref="Abs"/> to fix it. /// </summary> /// <value>Directly uses a private field.</value> public Vector2i Size { get { return _size; } set { _size = value; } } /// <summary> /// Ending corner. This is calculated as <see cref="Position"/> plus /// <see cref="Size"/>. Setting this value will change the size. /// </summary> /// <value>Getting is equivalent to `value = Position + Size`, setting is equivalent to `Size = value - Position`.</value> public Vector2i End { get { return _position + _size; } set { _size = value - _position; } } /// <summary> /// The area of this Rect2i. /// </summary> /// <value>Equivalent to <see cref="GetArea()"/>.</value> public int Area { get { return GetArea(); } } /// <summary> /// Returns a Rect2i with equivalent position and size, modified so that /// the top-left corner is the origin and width and height are positive. /// </summary> /// <returns>The modified Rect2i.</returns> public Rect2i Abs() { Vector2i end = End; Vector2i topLeft = new Vector2i(Mathf.Min(_position.x, end.x), Mathf.Min(_position.y, end.y)); return new Rect2i(topLeft, _size.Abs()); } /// <summary> /// Returns the intersection of this Rect2i and `b`. /// If the rectangles do not intersect, an empty Rect2i is returned. /// </summary> /// <param name="b">The other Rect2i.</param> /// <returns>The intersection of this Rect2i and `b`, or an empty Rect2i if they do not intersect.</returns> public Rect2i Intersection(Rect2i b) { var newRect = b; if (!Intersects(newRect)) { return new Rect2i(); } newRect._position.x = Mathf.Max(b._position.x, _position.x); newRect._position.y = Mathf.Max(b._position.y, _position.y); Vector2i bEnd = b._position + b._size; Vector2i end = _position + _size; newRect._size.x = Mathf.Min(bEnd.x, end.x) - newRect._position.x; newRect._size.y = Mathf.Min(bEnd.y, end.y) - newRect._position.y; return newRect; } /// <summary> /// Returns true if this Rect2i completely encloses another one. /// </summary> /// <param name="b">The other Rect2i that may be enclosed.</param> /// <returns>A bool for whether or not this Rect2i encloses `b`.</returns> public bool Encloses(Rect2i b) { return b._position.x >= _position.x && b._position.y >= _position.y && b._position.x + b._size.x < _position.x + _size.x && b._position.y + b._size.y < _position.y + _size.y; } /// <summary> /// Returns this Rect2i expanded to include a given point. /// </summary> /// <param name="to">The point to include.</param> /// <returns>The expanded Rect2i.</returns> public Rect2i Expand(Vector2i to) { var expanded = this; Vector2i begin = expanded._position; Vector2i end = expanded._position + expanded._size; if (to.x < begin.x) { begin.x = to.x; } if (to.y < begin.y) { begin.y = to.y; } if (to.x > end.x) { end.x = to.x; } if (to.y > end.y) { end.y = to.y; } expanded._position = begin; expanded._size = end - begin; return expanded; } /// <summary> /// Returns the area of the Rect2. /// </summary> /// <returns>The area.</returns> public int GetArea() { return _size.x * _size.y; } /// <summary> /// Returns a copy of the Rect2i grown by the specified amount on all sides. /// </summary> /// <param name="by">The amount to grow by.</param> /// <returns>The grown Rect2i.</returns> public Rect2i Grow(int by) { var g = this; g._position.x -= by; g._position.y -= by; g._size.x += by * 2; g._size.y += by * 2; return g; } /// <summary> /// Returns a copy of the Rect2i grown by the specified amount on each side individually. /// </summary> /// <param name="left">The amount to grow by on the left side.</param> /// <param name="top">The amount to grow by on the top side.</param> /// <param name="right">The amount to grow by on the right side.</param> /// <param name="bottom">The amount to grow by on the bottom side.</param> /// <returns>The grown Rect2i.</returns> public Rect2i GrowIndividual(int left, int top, int right, int bottom) { var g = this; g._position.x -= left; g._position.y -= top; g._size.x += left + right; g._size.y += top + bottom; return g; } /// <summary> /// Returns a copy of the Rect2i grown by the specified amount on the specified Side. /// </summary> /// <param name="side">The side to grow.</param> /// <param name="by">The amount to grow by.</param> /// <returns>The grown Rect2i.</returns> public Rect2i GrowSide(Side side, int by) { var g = this; g = g.GrowIndividual(Side.Left == side ? by : 0, Side.Top == side ? by : 0, Side.Right == side ? by : 0, Side.Bottom == side ? by : 0); return g; } /// <summary> /// Returns true if the Rect2i is flat or empty, or false otherwise. /// </summary> /// <returns>A bool for whether or not the Rect2i has area.</returns> public bool HasNoArea() { return _size.x <= 0 || _size.y <= 0; } /// <summary> /// Returns true if the Rect2i contains a point, or false otherwise. /// </summary> /// <param name="point">The point to check.</param> /// <returns>A bool for whether or not the Rect2i contains `point`.</returns> public bool HasPoint(Vector2i point) { if (point.x < _position.x) return false; if (point.y < _position.y) return false; if (point.x >= _position.x + _size.x) return false; if (point.y >= _position.y + _size.y) return false; return true; } /// <summary> /// Returns true if the Rect2i overlaps with `b` /// (i.e. they have at least one point in common). /// /// If `includeBorders` is true, they will also be considered overlapping /// if their borders touch, even without intersection. /// </summary> /// <param name="b">The other Rect2i to check for intersections with.</param> /// <param name="includeBorders">Whether or not to consider borders.</param> /// <returns>A bool for whether or not they are intersecting.</returns> public bool Intersects(Rect2i b, bool includeBorders = false) { if (includeBorders) { if (_position.x > b._position.x + b._size.x) return false; if (_position.x + _size.x < b._position.x) return false; if (_position.y > b._position.y + b._size.y) return false; if (_position.y + _size.y < b._position.y) return false; } else { if (_position.x >= b._position.x + b._size.x) return false; if (_position.x + _size.x <= b._position.x) return false; if (_position.y >= b._position.y + b._size.y) return false; if (_position.y + _size.y <= b._position.y) return false; } return true; } /// <summary> /// Returns a larger Rect2i that contains this Rect2i and `b`. /// </summary> /// <param name="b">The other Rect2i.</param> /// <returns>The merged Rect2i.</returns> public Rect2i Merge(Rect2i b) { Rect2i newRect; newRect._position.x = Mathf.Min(b._position.x, _position.x); newRect._position.y = Mathf.Min(b._position.y, _position.y); newRect._size.x = Mathf.Max(b._position.x + b._size.x, _position.x + _size.x); newRect._size.y = Mathf.Max(b._position.y + b._size.y, _position.y + _size.y); newRect._size -= newRect._position; // Make relative again return newRect; } /// <summary> /// Constructs a Rect2i from a position and size. /// </summary> /// <param name="position">The position.</param> /// <param name="size">The size.</param> public Rect2i(Vector2i position, Vector2i size) { _position = position; _size = size; } /// <summary> /// Constructs a Rect2i from a position, width, and height. /// </summary> /// <param name="position">The position.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public Rect2i(Vector2i position, int width, int height) { _position = position; _size = new Vector2i(width, height); } /// <summary> /// Constructs a Rect2i from x, y, and size. /// </summary> /// <param name="x">The position's X coordinate.</param> /// <param name="y">The position's Y coordinate.</param> /// <param name="size">The size.</param> public Rect2i(int x, int y, Vector2i size) { _position = new Vector2i(x, y); _size = size; } /// <summary> /// Constructs a Rect2i from x, y, width, and height. /// </summary> /// <param name="x">The position's X coordinate.</param> /// <param name="y">The position's Y coordinate.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public Rect2i(int x, int y, int width, int height) { _position = new Vector2i(x, y); _size = new Vector2i(width, height); } public static bool operator ==(Rect2i left, Rect2i right) { return left.Equals(right); } public static bool operator !=(Rect2i left, Rect2i right) { return !left.Equals(right); } public static implicit operator Rect2(Rect2i value) { return new Rect2(value._position, value._size); } public static explicit operator Rect2i(Rect2 value) { return new Rect2i((Vector2i)value.Position, (Vector2i)value.Size); } public override bool Equals(object obj) { if (obj is Rect2i) { return Equals((Rect2i)obj); } return false; } public bool Equals(Rect2i other) { return _position.Equals(other._position) && _size.Equals(other._size); } public override int GetHashCode() { return _position.GetHashCode() ^ _size.GetHashCode(); } public override string ToString() { return $"{_position}, {_size}"; } public string ToString(string format) { return $"{_position.ToString(format)}, {_size.ToString(format)}"; } } }
/* * 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 log4net; using Mono.Addins; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGAssetBroker")] public class HGAssetBroker : ISharedRegionModule, IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private IImprovedAssetCache m_Cache = null; private IAssetService m_GridService; private IAssetService m_HGService; private Scene m_aScene; private string m_LocalAssetServiceURI; private bool m_Enabled = false; private AssetPermissions m_AssetPerms; public Type ReplaceableInterface { get { return null; } } public string Name { get { return "HGAssetBroker"; } } public HGAssetBroker() {} public HGAssetBroker(IConfigSource config) { Initialise(config); } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetServices", ""); if (name == Name) { IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[HG ASSET CONNECTOR]: AssetService missing from OpenSim.ini"); return; } string localDll = assetConfig.GetString("LocalGridAssetService", String.Empty); string HGDll = assetConfig.GetString("HypergridAssetService", String.Empty); if (localDll == String.Empty) { m_log.Error("[HG ASSET CONNECTOR]: No LocalGridAssetService named in section AssetService"); return; } if (HGDll == String.Empty) { m_log.Error("[HG ASSET CONNECTOR]: No HypergridAssetService named in section AssetService"); return; } Object[] args = new Object[] { source }; m_GridService = ServerUtils.LoadPlugin<IAssetService>(localDll, args); m_HGService = ServerUtils.LoadPlugin<IAssetService>(HGDll, args); if (m_GridService == null) { m_log.Error("[HG ASSET CONNECTOR]: Can't load local asset service"); return; } if (m_HGService == null) { m_log.Error("[HG ASSET CONNECTOR]: Can't load hypergrid asset service"); return; } m_LocalAssetServiceURI = assetConfig.GetString("AssetServerURI", string.Empty); if (m_LocalAssetServiceURI == string.Empty) { IConfig netConfig = source.Configs["Network"]; m_LocalAssetServiceURI = netConfig.GetString("asset_server_url", string.Empty); } if (m_LocalAssetServiceURI != string.Empty) m_LocalAssetServiceURI = m_LocalAssetServiceURI.Trim('/'); IConfig hgConfig = source.Configs["HGAssetService"]; m_AssetPerms = new AssetPermissions(hgConfig); // it's ok if arg is null m_Enabled = true; m_log.Info("[HG ASSET CONNECTOR]: HG asset broker enabled"); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_aScene = scene; m_aScene.RegisterModuleInterface<IAssetService>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_Cache == null) { m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>(); if (!(m_Cache is ISharedRegionModule)) m_Cache = null; } m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled hypergrid asset broker for region {0}", scene.RegionInfo.RegionName); if (m_Cache != null) { m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName); } } private bool IsHG(string id) { Uri assetUri; if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) && assetUri.Scheme == Uri.UriSchemeHttp) return true; return false; } public AssetBase Get(string id) { //m_log.DebugFormat("[HG ASSET CONNECTOR]: Get {0}", id); AssetBase asset = null; if (m_Cache != null) { asset = m_Cache.Get(id); if (asset != null) return asset; } if (IsHG(id)) { asset = m_HGService.Get(id); if (asset != null) { // Now store it locally, if allowed if (m_AssetPerms.AllowedImport(asset.Type)) m_GridService.Store(asset); else return null; } } else asset = m_GridService.Get(id); if (m_Cache != null) m_Cache.Cache(asset); return asset; } public AssetBase GetCached(string id) { if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { AssetBase asset = null; if (m_Cache != null) { if (m_Cache != null) m_Cache.Get(id); if (asset != null) return asset.Metadata; } AssetMetadata metadata; if (IsHG(id)) metadata = m_HGService.GetMetadata(id); else metadata = m_GridService.GetMetadata(id); return metadata; } public byte[] GetData(string id) { AssetBase asset = null; if (m_Cache != null) { if (m_Cache != null) m_Cache.Get(id); if (asset != null) return asset.Data; } if (IsHG(id)) return m_HGService.GetData(id); else return m_GridService.GetData(id); } public bool Get(string id, Object sender, AssetRetrieved handler) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) { Util.FireAndForget(delegate { handler(id, sender, asset); }, null, "HGAssetBroker.GotFromCache"); return true; } if (IsHG(id)) { return m_HGService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if (m_Cache != null) m_Cache.Cache(a); handler(assetID, s, a); }); } else { return m_GridService.Get(id, sender, delegate (string assetID, Object s, AssetBase a) { if (m_Cache != null) m_Cache.Cache(a); handler(assetID, s, a); }); } } public virtual bool[] AssetsExist(string[] ids) { int numHG = 0; foreach (string id in ids) { if (IsHG(id)) ++numHG; } if (numHG == 0) return m_GridService.AssetsExist(ids); else if (numHG == ids.Length) return m_HGService.AssetsExist(ids); else throw new Exception("[HG ASSET CONNECTOR]: AssetsExist: all the assets must be either local or foreign"); } public string Store(AssetBase asset) { bool isHG = IsHG(asset.ID); if ((m_Cache != null) && !isHG) // Don't store it in the cache if the asset is to // be sent to the other grid, because this is already // a copy of the local asset. m_Cache.Cache(asset); if (asset.Local) { if (m_Cache != null) m_Cache.Cache(asset); return asset.ID; } string id; if (IsHG(asset.ID)) { if (m_AssetPerms.AllowedExport(asset.Type)) id = m_HGService.Store(asset); else return String.Empty; } else id = m_GridService.Store(asset); if (String.IsNullOrEmpty(id)) return string.Empty; asset.ID = id; if (m_Cache != null) m_Cache.Cache(asset); return id; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset != null) { asset.Data = data; m_Cache.Cache(asset); } if (IsHG(id)) return m_HGService.UpdateContent(id, data); else return m_GridService.UpdateContent(id, data); } public bool Delete(string id) { if (m_Cache != null) m_Cache.Expire(id); bool result = false; if (IsHG(id)) result = m_HGService.Delete(id); else result = m_GridService.Delete(id); if (result && m_Cache != null) m_Cache.Expire(id); return result; } } }
// Errors.cs HDO, 2006-08-28 // --------- // Error handling, storage of error messages and listing generation. //=====================================|======================================== #undef TEST_ERRORS using System; using System.IO; public class Errors { public const String MODULENAME = "Errors"; public static void ErrorsMethod(Utils.ModuleAction action, out String moduleName) { //-----------------------------------|---------------------------------------- moduleName = MODULENAME; switch (action) { case Utils.ModuleAction.getModuleName: return; case Utils.ModuleAction.initModule: aps = new AbortMethod[MAXABORTPROCS]; sp = 0; PushAbortMethod(DefaultAbort); stopParsing = null; eowCnt = new int[4]; curEoW = new ErrorWarn[4]; break; case Utils.ModuleAction.resetModule: break; case Utils.ModuleAction.cleanupModule: eowl = null; eowCnt = null; curEoW = null; return; } // switch // --- for initModule and resetModule --- eowl = null; numOfErrs = 0; numOfWarns = 0; for (int i = 0; i < 4; i++) eowCnt[i] = 0; } // ErrorsMethod public const int MAXABORTPROCS = 3; public const int MAXNUMOFERRS = 30; // sum of lex., syn. and sem. errors public const int MAXNUMOFWARNS = 50; public delegate void StopParsingMethod(); public delegate void AbortMethod(String abortKind, String moduleName, String methodName, String descr); enum EoWKind { lexErr, synErr, semErr, warn } // EoWKind public class ErrorWarnInfo { public String msg; public int line, col; } // ErrorWarnInfo private class ErrorWarn { public EoWKind kind; public ErrorWarnInfo info; public ErrorWarn next; } // ErrorWarn private static AbortMethod[] aps; // abort method stack private static int sp; // stack pointer for aps private static StopParsingMethod stopParsing; // --- errors and/or warnings handling --- private static ErrorWarn eowl; // sorted list of errors or warnings private static int numOfErrs, numOfWarns; private static int[] eowCnt; private static void DefaultAbort(String abortKind, String moduleName, String funcName, String descr) { Console.WriteLine(); Console.WriteLine("*** {0} in module {1} function {2}", abortKind, moduleName, funcName); Console.WriteLine("*** {0}", descr); Utils.Modules(Utils.ModuleAction.cleanupModule); Environment.Exit(Utils.EXIT_FAILURE); } // DefaultAbort // --- install stop parsing and abort functions --- public static void InstallStopParsingMethod(StopParsingMethod spp) { //-----------------------------------|---------------------------------------- stopParsing = spp; } // InstallStopParsingMethod public static void PushAbortMethod(AbortMethod ap) { //-----------------------------------|---------------------------------------- if (sp == MAXABORTPROCS) Restriction(MODULENAME, "PushAbortFunc", "too many abort functions"); aps[sp++] = ap; } // PushAbortMethod // --- report error or restriction and call abort functions --- public static void CompilerError(String moduleName, String funcName, String fmt, params Object[] p) { //-----------------------------------|---------------------------------------- TextWriter w = new StringWriter(); w.WriteLine(fmt, p); String msg = w.ToString(); for (int i = sp - 1; i >= 0; i--) aps[i]("compiler error", moduleName, funcName, msg); // should not return* DefaultAbort("compiler error", moduleName, funcName, msg); } // CompilerError public static void Restriction(String moduleName, String funcName, String fmt, params Object[] p) { //-----------------------------------|---------------------------------------- TextWriter w = new StringWriter(); w.WriteLine(fmt, p); String msg = w.ToString(); for (int i = sp - 1; i >= 0; i--) aps[i]("restriction", moduleName, funcName, msg); // should not return DefaultAbort("restriction", moduleName, funcName, msg); } // Restriction public static void CallStopParsing() { //-----------------------------------|---------------------------------------- if (stopParsing != null) stopParsing(); } // CallStopParsing // --- storage of errors found on compilation --- private static void EnterMessage(EoWKind knd, int line, int col, String msg) { ErrorWarn eow, prveow, nxteow; eowCnt[(int)knd]++; eow = new ErrorWarn(); eow.kind = knd; eow.info = new ErrorWarnInfo(); eow.info.line = line; eow.info.col = col; eow.info.msg = msg; prveow = null; nxteow = eowl; while (nxteow != null && nxteow.info.line <= line) { prveow = nxteow; nxteow = nxteow.next; } // while while (nxteow != null && nxteow.info.line == line && nxteow.info.col <= col) { prveow = nxteow; nxteow = nxteow.next; } // while if (prveow == null) eowl = eow; else prveow.next = eow; eow.next = nxteow; } // EnterMessage private static void CheckForLimits(EoWKind knd, int line, int col) { if (knd == EoWKind.lexErr || knd == EoWKind.synErr || knd == EoWKind.semErr) { numOfErrs++; if (numOfErrs == MAXNUMOFERRS) { Warning(line, col, "too many errors, parsing stopped"); CallStopParsing(); } // if } else { // knd == EoWKind.warn numOfWarns++; if (numOfWarns == MAXNUMOFWARNS) { Warning(line, col, "too many warnings, parsing stopped"); CallStopParsing(); } // if } // else } // CheckForLimits public static void LexError(int line, int col, String fmt, params Object[] p) { //-----------------------------------|---------------------------------------- if (numOfErrs == MAXNUMOFERRS) return; TextWriter w = new StringWriter(); w.WriteLine(fmt, p); String msg = w.ToString(); EnterMessage(EoWKind.lexErr, line, col, msg); CheckForLimits(EoWKind.lexErr, line, col); } // SynError public static void SynError(int line, int col, String fmt, params Object[] p) { //-----------------------------------|---------------------------------------- if (numOfErrs == MAXNUMOFERRS) return; TextWriter w = new StringWriter(); w.WriteLine(fmt, p); String msg = w.ToString(); EnterMessage(EoWKind.synErr, line, col, msg); CheckForLimits(EoWKind.synErr, line, col); } // SynError public static void SemError(int line, int col, String fmt, params Object[] p) { //-----------------------------------|---------------------------------------- if (numOfErrs == MAXNUMOFERRS) return; TextWriter w = new StringWriter(); w.WriteLine(fmt, p); String msg = w.ToString(); EnterMessage(EoWKind.semErr, line, col, msg); CheckForLimits(EoWKind.semErr, line, col); } // SemError public static void Warning(int line, int col, String fmt, params Object[] p) { //-----------------------------------|---------------------------------------- if (numOfWarns == MAXNUMOFWARNS) return; TextWriter w = new StringWriter(); w.WriteLine(fmt, p); String msg = w.ToString(); EnterMessage(EoWKind.warn, line, col, msg); CheckForLimits(EoWKind.warn, line, col); } // Warning // --- retrieval of stored source errors and warnings --- public static int NumOfErrors() { //-----------------------------------|---------------------------------------- return numOfErrs; } // NumOfErrors public static int NumOfLexErrors() { //-----------------------------------|---------------------------------------- return eowCnt[(int)EoWKind.lexErr]; } // NumOfLexErrors public static int NumOfSynErrors() { //-----------------------------------|---------------------------------------- return eowCnt[(int)EoWKind.synErr]; } // NumOfSynErrors public static int NumOfSemErrors() { //-----------------------------------|---------------------------------------- return eowCnt[(int)EoWKind.semErr]; } // NumOfSemErrors public static int NumOfWarnings() { //-----------------------------------|---------------------------------------- return eowCnt[(int)EoWKind.warn]; } // NumOfWarnings private static ErrorWarn[] curEoW; private static ErrorWarnInfo GetMessage(bool first, EoWKind knd) { ErrorWarn eow = null; ErrorWarnInfo eowi = null; if (first) eow = eowl; else eow = curEoW[(int)knd].next; while (eow != null && eow.kind != knd) eow = eow.next; curEoW[(int)knd] = eow; if (eow == null) { eowi = new ErrorWarnInfo(); eowi.msg = ""; eowi.line = 0; eowi.col = 0; } else eowi = eow.info; return eowi; } // GetMessage public static ErrorWarnInfo GetLexError(bool first) { //-----------------------------------|---------------------------------------- return GetMessage(first, EoWKind.lexErr); } // ErrorWarnInfo public static ErrorWarnInfo GetSynError(bool first) { //-----------------------------------|---------------------------------------- return GetMessage(first, EoWKind.synErr); } // ErrorWarnInfo public static ErrorWarnInfo GetSemError(bool first) { //-----------------------------------|---------------------------------------- return GetMessage(first, EoWKind.semErr); } // ErrorWarnInfo public static ErrorWarnInfo GetWarning(bool first) { //-----------------------------------|---------------------------------------- return GetMessage(first, EoWKind.warn); } // ErrorWarnInfo // --- listing generation --- private static void PutMsg(TextWriter lst, ErrorWarn eow) { switch (eow.kind) { case EoWKind.lexErr: lst.Write("+LEX+"); break; case EoWKind.synErr: lst.Write("*SYN*"); break; case EoWKind.semErr: lst.Write("#SEM#"); break; case EoWKind.warn: lst.Write("!WRN!"); break; } // switch for (int i = 0; i < eow.info.col; i++) lst.Write(" "); lst.Write(" ^{0}", eow.info.msg); } // PutMsg public enum ListingShape { longListing, shortListing } // ListingShape public static void GenerateListing(TextReader src, TextWriter lst, ListingShape listShape) { //-----------------------------------|---------------------------------------- ErrorWarn eow = null; int lnr, skip; String srcLine; ((StreamReader)src).BaseStream.Seek(0, SeekOrigin.Begin); eow = eowl; if (eow != null) { while (eow != null && eow.info.line < 1) { PutMsg(lst, eow); eow = eow.next; } // while lst.WriteLine(); } // if lnr = 1; for (; ; ) { if (listShape == ListingShape.shortListing) { if (eow == null) { lst.WriteLine("..."); break; } // if skip = eow.info.line - lnr; if (skip > 0) { lst.WriteLine("..."); lnr = eow.info.line; while (skip-- > 0) { srcLine = src.ReadLine(); if (srcLine == null) break; } // while } // if } // if srcLine = src.ReadLine(); if (srcLine == null) break; lst.WriteLine("{0,5}| {1}", lnr, srcLine); while (eow != null && eow.info.line == lnr) { PutMsg(lst, eow); eow = eow.next; } // while lnr++; } // for lst.WriteLine(); while (eow != null) { PutMsg(lst, eow); eow = eow.next; } // while lst.WriteLine(); lst.WriteLine("error(s) and warning(s):"); lst.WriteLine("-----------------------"); lst.WriteLine(); lst.WriteLine("{0,5} lexical error(s) ", NumOfLexErrors()); lst.WriteLine("{0,5} syntax error(s) ", NumOfSynErrors()); lst.WriteLine("{0,5} semantic error(s)", NumOfSemErrors()); lst.WriteLine("{0,5} warning(s) ", NumOfWarnings()); } // GenerateListing #if TEST_ERRORS public static void Main(String[] args) { Console.WriteLine("START: Errors"); Console.WriteLine("installing ..."); Utils.InstallModule("Utils", new Utils.ModuleMethodDelegate(Utils.UtilsMethod)); Utils.InstallModule("Sets", new Utils.ModuleMethodDelegate(Sets.SetsMethod )); Utils.InstallModule("Errors", new Utils.ModuleMethodDelegate(Errors.ErrorsMethod)); Console.WriteLine("initModule ..."); Utils.Modules(Utils.ModuleAction.initModule); LexError(1, 1, "LexError at {0}, {1}", 1, 1); SynError(3, 10, "SynError at {0}, {1}", 2, 10); SemError(5, 5, "SemError at {0}, {1}", 5, 5); Warning(0, 0, "Warning at {0}, {1}", 0, 0); Warning(9, 0, "Warning at {0}, {1}", 9, 0); String srcName; Utils.GetInputFileName("source file name > ", out srcName); FileStream srcFs = new FileStream(srcName, FileMode.Open); StreamReader src = new StreamReader(srcFs); FileStream lstFs = new FileStream(srcName + ".lst", FileMode.Create); StreamWriter lst = new StreamWriter(lstFs); lst.WriteLine("START"); GenerateListing(src, lst, ListingShape.longListing); lst.WriteLine("END"); src.Close(); lst.Close(); Console.WriteLine("resetModule ..."); Utils.Modules(Utils.ModuleAction.resetModule); Console.WriteLine("cleanupModule ..."); Utils.Modules(Utils.ModuleAction.cleanupModule); Console.WriteLine("END"); // Console.WriteLine("type [CR] to continue ..."); // Console.ReadLine(); } // Main #endif } // Errors // End of Errors.cs //=====================================|========================================
// -- FILE ------------------------------------------------------------------ // name : DateTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.08.24 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using Itenso.TimePeriod; using Xunit; namespace Itenso.TimePeriodTests { // ------------------------------------------------------------------------ public sealed class DateTest : TestUnitBase { // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void ConstructorTest() { Date date = new Date( 2009, 7, 22 ); Assert.Equal(2009, date.Year); Assert.Equal(7, date.Month); Assert.Equal(22, date.Day); } // ConstructorTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void ConstructorYearTest() { Date date = new Date( 2009 ); Assert.Equal(2009, date.Year); Assert.Equal(1, date.Month); Assert.Equal(1, date.Day); } // ConstructorYearTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void ConstructorMonthTest() { Date date = new Date( 2009, 7 ); Assert.Equal(2009, date.Year); Assert.Equal(7, date.Month); Assert.Equal(1, date.Day); } // ConstructorMonthTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void DefaultConstructorTest() { const int year = 2009; Date date = new Date( year ); Assert.Equal( date.Year, year ); Assert.Equal(1, date.Month); Assert.Equal(1, date.Day); } // DefaultConstructorTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void DateTimeConstructorTest() { DateTime dateTime = new DateTime( 2009, 7, 22, 18, 23, 56, 344 ); Date date = new Date( dateTime ); Assert.Equal( date.Year, dateTime.Year ); Assert.Equal( date.Month, dateTime.Month ); Assert.Equal( date.Day, dateTime.Day ); } // DateTimeConstructorTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void MinValueTest() { new Date( DateTime.MinValue ); } // MinValueTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void MaxValueTest() { new Date( DateTime.MaxValue ); } // MinValueTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void MinYearTest() { Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() => new Date( DateTime.MinValue.Year - 1 ))); } // MinYearTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void MaxYearTest() { Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() => new Date( DateTime.MaxValue.Year + 1 ))); } // MaxYearTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void MinMonthTest() { Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() => new Date( DateTime.MinValue.Year, 0 ))); } // MinMonthTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void MaxMonthTest() { Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() => new Date( DateTime.MaxValue.Year, TimeSpec.MonthsPerYear + 1 ))); } // MaxMonthTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void MinDayTest() { Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() => new Date( DateTime.MinValue.Year, 1, 0 ))); } // MinDayTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void MaxDayTest() { Assert.NotNull(Assert.Throws<ArgumentOutOfRangeException>(() => new Date( DateTime.MinValue.Year, 1, TimeSpec.MaxDaysPerMonth + 1 ))); } // MaxDayTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void DateTimeTest1() { DateTime dateTime1 = new DateTime( 2009, 7, 22 ); Date date1 = new Date( dateTime1 ); Assert.Equal( date1.DateTime, dateTime1.Date ); DateTime dateTime2 = new DateTime( 2009, 7, 22, 18, 23, 56, 344 ); Date date2 = new Date( dateTime2 ); Assert.Equal( date2.DateTime, dateTime2.Date ); } // DateTimeTest1 // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void ToDateTimeTest2() { DateTime dateTime = new DateTime( 2009, 7, 22 ); Date date = new Date( dateTime ); Assert.Equal( date.DateTime, dateTime ); Assert.Equal( date.ToDateTime( 1 ), new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, 1, 0, 0, 0 ) ); Assert.Equal( date.ToDateTime( 1, 1 ), new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, 1, 1, 0, 0 ) ); Assert.Equal( date.ToDateTime( 1, 1, 1 ), new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, 1, 1, 1, 0 ) ); Assert.Equal( date.ToDateTime( 1, 1, 1, 1 ), new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, 1, 1, 1, 1 ) ); } // ToDateTimeTest2 // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void GetDateTimeFromTimeTest() { DateTime dateTime = new DateTime( 2009, 7, 22 ); Date date = new Date( dateTime ); TimeSpan timeSpan = new TimeSpan( 0, 18, 23, 56, 344 ); Time time = new Time( timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds ); Assert.Equal( date.ToDateTime( time ), dateTime.Add( timeSpan ) ); } // GetDateTimeFromTimeTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void CompareToTest() { DateTime now = ClockProxy.Clock.Now.Date; Date date = new Date( now ); Date dateBefore = new Date( now.AddDays( -1 ) ); Date dateAfter = new Date( now.AddDays( 1 ) ); Assert.Equal( 0, date.CompareTo( date ) ); Assert.Equal( 1, date.CompareTo( dateBefore ) ); Assert.Equal( -1, date.CompareTo( dateAfter ) ); } // CompareToTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void EquatableTest() { DateTime now = ClockProxy.Clock.Now.Date; Date date = new Date( now ); Date dateBefore = new Date( now.AddDays( -1 ) ); Date dateAfter = new Date( now.AddDays( 1 ) ); Assert.True( date.Equals( date ) ); Assert.False( date.Equals( dateBefore ) ); Assert.False( date.Equals( dateAfter ) ); } // EquatableTest // ---------------------------------------------------------------------- [Trait("Category", "Date")] [Fact] public void OperatorTest() { DateTime now = ClockProxy.Clock.Now.Date; Date date = new Date( now ); Date dateBefore = new Date( now.AddDays( -1 ) ); Date dateAfter = new Date( now.AddDays( 1 ) ); TimeSpan oneDay = new TimeSpan( 1, 0, 0, 0, 0 ); TimeSpan halfDay = new TimeSpan( 0, 12, 30, 30, 500 ); Assert.Equal( dateBefore, date - oneDay ); Assert.Equal( dateBefore, date - halfDay ); Assert.Equal( dateBefore, date - oneDay ); Assert.Equal( oneDay, date - dateBefore ); // no operator +( Date, Date ) Assert.Equal( dateAfter, date + oneDay ); Assert.Equal( dateAfter, date + oneDay + halfDay ); Assert.True( dateBefore < date ); Assert.False( dateAfter <= date ); Assert.True( dateBefore <= date ); Assert.False( dateAfter <= date ); Assert.False( dateBefore == date ); Assert.False( dateAfter == date ); Assert.True( dateBefore != date ); Assert.True( dateAfter != date ); Assert.False( dateBefore >= date ); Assert.True( dateAfter >= date ); Assert.False( dateBefore > date ); Assert.True( dateAfter > date ); } // OperatorTest } // class DateTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using QuantConnect.Data.Market; using QuantConnect.Securities; namespace QuantConnect.Orders.Fills { /// <summary> /// Represents the default fill model used to simulate order fills /// </summary> public class ImmediateFillModel : IFillModel { /// <summary> /// Default market fill model for the base security class. Fills at the last traded price. /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="SecurityTransactionModel.StopMarketFill"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> public virtual OrderEvent MarketFill(Security asset, MarketOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; //Order [fill]price for a market order model is the current security price fill.FillPrice = GetPrices(asset, order.Direction).Current; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default stop fill model implementation in base class security. (Stop Market Order Type) /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="MarketFill(Security, MarketOrder)"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> public virtual OrderEvent StopMarketFill(Security asset, StopMarketOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: var prices = GetPrices(asset, order.Direction); //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Check if the Stop Order was filled: opposite to a limit order switch (order.Direction) { case OrderDirection.Sell: //-> 1.1 Sell Stop: If Price below setpoint, Sell: if (prices.Low < order.StopPrice) { fill.Status = OrderStatus.Filled; // Assuming worse case scenario fill - fill at lowest of the stop & asset price. fill.FillPrice = Math.Min(order.StopPrice, prices.Current - slip); } break; case OrderDirection.Buy: //-> 1.2 Buy Stop: If Price Above Setpoint, Buy: if (prices.High > order.StopPrice) { fill.Status = OrderStatus.Filled; // Assuming worse case scenario fill - fill at highest of the stop & asset price. fill.FillPrice = Math.Max(order.StopPrice, prices.Current + slip); } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default stop limit fill model implementation in base class security. (Stop Limit Order Type) /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/> /// <seealso cref="SecurityTransactionModel.LimitFill"/> /// <remarks> /// There is no good way to model limit orders with OHLC because we never know whether the market has /// gapped past our fill price. We have to make the assumption of a fluid, high volume market. /// /// Stop limit orders we also can't be sure of the order of the H - L values for the limit fill. The assumption /// was made the limit fill will be done with closing price of the bar after the stop has been triggered.. /// </remarks> public virtual OrderEvent StopLimitFill(Security asset, StopLimitOrder order) { //Default order event to return. var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: var prices = GetPrices(asset, order.Direction); //Check if the Stop Order was filled: opposite to a limit order switch (order.Direction) { case OrderDirection.Buy: //-> 1.2 Buy Stop: If Price Above Setpoint, Buy: if (prices.High > order.StopPrice || order.StopTriggered) { order.StopTriggered = true; // Fill the limit order, using closing price of bar: // Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered. if (asset.Price < order.LimitPrice) { fill.Status = OrderStatus.Filled; fill.FillPrice = order.LimitPrice; } } break; case OrderDirection.Sell: //-> 1.1 Sell Stop: If Price below setpoint, Sell: if (prices.Low < order.StopPrice || order.StopTriggered) { order.StopTriggered = true; // Fill the limit order, using minimum price of the bar // Note > Can't use minimum price, because no way to be sure minimum wasn't before the stop triggered. if (asset.Price > order.LimitPrice) { fill.Status = OrderStatus.Filled; fill.FillPrice = order.LimitPrice; // Fill at limit price not asset price. } } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Default limit order fill model in the base security class. /// </summary> /// <param name="asset">Security asset we're filling</param> /// <param name="order">Order packet to model</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> /// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/> /// <seealso cref="MarketFill(Security, MarketOrder)"/> public virtual OrderEvent LimitFill(Security asset, LimitOrder order) { //Initialise; var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); //If its cancelled don't need anymore checks: if (order.Status == OrderStatus.Canceled) return fill; //Get the range of prices in the last bar: var prices = GetPrices(asset, order.Direction); //-> Valid Live/Model Order: switch (order.Direction) { case OrderDirection.Buy: //Buy limit seeks lowest price if (prices.Low < order.LimitPrice) { //Set order fill: fill.Status = OrderStatus.Filled; // fill at the worse price this bar or the limit price, this allows far out of the money limits // to be executed properly fill.FillPrice = Math.Min(prices.High, order.LimitPrice); } break; case OrderDirection.Sell: //Sell limit seeks highest price possible if (prices.High > order.LimitPrice) { fill.Status = OrderStatus.Filled; // fill at the worse price this bar or the limit price, this allows far out of the money limits // to be executed properly fill.FillPrice = Math.Max(prices.Low, order.LimitPrice); } break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Market on Open Fill Model. Return an order event with the fill details /// </summary> /// <param name="asset">Asset we're trading with this order</param> /// <param name="order">Order to be filled</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> public OrderEvent MarketOnOpenFill(Security asset, MarketOnOpenOrder order) { var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; // MOO should never fill on the same bar or on stale data // Imagine the case where we have a thinly traded equity, ASUR, and another liquid // equity, say SPY, SPY gets data every minute but ASUR, if not on fill forward, maybe // have large gaps, in which case the currentBar.EndTime will be in the past // ASUR | | | [order] | | | | | | | // SPY | | | | | | | | | | | | | | | | | | | | var currentBar = asset.GetLastData(); var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone); if (currentBar == null || localOrderTime >= currentBar.EndTime) return fill; // if the MOO was submitted during market the previous day, wait for a day to turn over if (asset.Exchange.DateTimeIsOpen(localOrderTime) && localOrderTime.Date == asset.LocalTime.Date) { return fill; } // wait until market open // make sure the exchange is open before filling if (!IsExchangeOpen(asset)) return fill; fill.FillPrice = GetPrices(asset, order.Direction).Open; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Market on Close Fill Model. Return an order event with the fill details /// </summary> /// <param name="asset">Asset we're trading with this order</param> /// <param name="order">Order to be filled</param> /// <returns>Order fill information detailing the average price and quantity filled.</returns> public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order) { var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone); var fill = new OrderEvent(order, utcTime, 0); if (order.Status == OrderStatus.Canceled) return fill; var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone); var nextMarketClose = asset.Exchange.Hours.GetNextMarketClose(localOrderTime, false); // wait until market closes after the order time if (asset.LocalTime < nextMarketClose) { return fill; } fill.FillPrice = GetPrices(asset, order.Direction).Close; fill.Status = OrderStatus.Filled; //Calculate the model slippage: e.g. 0.01c var slip = asset.SlippageModel.GetSlippageApproximation(asset, order); //Apply slippage switch (order.Direction) { case OrderDirection.Buy: fill.FillPrice += slip; break; case OrderDirection.Sell: fill.FillPrice -= slip; break; } // assume the order completely filled if (fill.Status == OrderStatus.Filled) { fill.FillQuantity = order.Quantity; fill.OrderFee = asset.FeeModel.GetOrderFee(asset, order); } return fill; } /// <summary> /// Get the minimum and maximum price for this security in the last bar: /// </summary> /// <param name="asset">Security asset we're checking</param> /// <param name="direction">The order direction, decides whether to pick bid or ask</param> private Prices GetPrices(Security asset, OrderDirection direction) { var low = asset.Low; var high = asset.High; var open = asset.Open; var close = asset.Close; var current = asset.Price; if (direction == OrderDirection.Hold) { return new Prices(current, open, high, low, close); } var tick = asset.Cache.GetData<Tick>(); if (tick != null) { if (direction == OrderDirection.Sell && tick.BidPrice != 0) { current = tick.BidPrice; } else if (direction == OrderDirection.Buy && tick.AskPrice != 0) { current = tick.AskPrice; } } var quoteBar = asset.Cache.GetData<QuoteBar>(); if (quoteBar != null) { var bar = direction == OrderDirection.Sell ? quoteBar.Bid : quoteBar.Ask; if (bar != null) { return new Prices(bar); } } var tradeBar = asset.Cache.GetData<TradeBar>(); if (tradeBar != null) { return new Prices(tradeBar); } var lastData = asset.GetLastData(); var lastBar = lastData as IBar; if (lastBar != null) { return new Prices(lastBar); } return new Prices(current, open, high, low, close); } /// <summary> /// Determines if the exchange is open using the current time of the asset /// </summary> private static bool IsExchangeOpen(Security asset) { if (!asset.Exchange.DateTimeIsOpen(asset.LocalTime)) { // if we're not open at the current time exactly, check the bar size, this handle large sized bars (hours/days) var currentBar = asset.GetLastData(); if (asset.LocalTime.Date != currentBar.EndTime.Date || !asset.Exchange.IsOpenDuringBar(currentBar.Time, currentBar.EndTime, false)) { return false; } } return true; } private class Prices { public readonly decimal Current; public readonly decimal Open; public readonly decimal High; public readonly decimal Low; public readonly decimal Close; public Prices(IBar bar) : this(bar.Close, bar.Open, bar.High, bar.Low, bar.Close) { } public Prices(decimal current, decimal open, decimal high, decimal low, decimal close) { Current = current; Open = open == 0 ? current : open; High = high == 0 ? current : high; Low = low == 0 ? current : low; Close = close == 0 ? current : close; } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapAttributeSchema.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using SchemaParser = Novell.Directory.Ldap.Utilclass.SchemaParser; using AttributeQualifier = Novell.Directory.Ldap.Utilclass.AttributeQualifier; namespace Novell.Directory.Ldap { /// <summary> A specific a name form in the directory schema. /// /// The LdapNameFormSchema class represents the definition of a Name Form. It /// is used to discover or modify the allowed naming attributes for a particular /// object class. /// /// </summary> /// <seealso cref="LdapSchemaElement"> /// </seealso> /// <seealso cref="LdapSchema"> /// </seealso> public class LdapNameFormSchema:LdapSchemaElement { /// <summary> Returns the name of the object class which this name form applies to. /// /// </summary> /// <returns> The name of the object class. /// </returns> virtual public System.String ObjectClass { get { return objectClass; } } /// <summary> Returns the list of required naming attributes for an entry /// controlled by this name form. /// /// </summary> /// <returns> The list of required naming attributes. /// </returns> virtual public System.String[] RequiredNamingAttributes { get { return required; } } /// <summary> Returns the list of optional naming attributes for an entry /// controlled by this content rule. /// /// </summary> /// <returns> The list of the optional naming attributes. /// </returns> virtual public System.String[] OptionalNamingAttributes { get { return optional; } } private System.String objectClass; private System.String[] required; private System.String[] optional; /// <summary> Constructs a name form for adding to or deleting from the schema. /// /// </summary> /// <param name="names"> The name(s) of the name form. /// /// </param> /// <param name="oid"> The unique object identifier of the name form - in /// dotted numerical format. /// /// </param> /// <param name="description">An optional description of the name form. /// /// </param> /// <param name="obsolete"> True if the name form is obsolete. /// /// </param> /// <param name="objectClass">The object to which this name form applies. /// This may be specified by either name or /// numeric oid. /// /// </param> /// <param name="required"> A list of the attributes that must be present /// in the RDN of an entry that this name form /// controls. These attributes may be specified by /// either name or numeric oid. /// /// </param> /// <param name="optional"> A list of the attributes that may be present /// in the RDN of an entry that this name form /// controls. These attributes may be specified by /// either name or numeric oid. /// </param> public LdapNameFormSchema(System.String[] names, System.String oid, System.String description, bool obsolete, System.String objectClass, System.String[] required, System.String[] optional):base(LdapSchema.schemaTypeNames[LdapSchema.NAME_FORM]) { base.names = new System.String[names.Length]; names.CopyTo(base.names, 0); base.oid = oid; base.description = description; base.obsolete = obsolete; this.objectClass = objectClass; this.required = new System.String[required.Length]; required.CopyTo(this.required, 0); this.optional = new System.String[optional.Length]; optional.CopyTo(this.optional, 0); base.Value = formatString(); return ; } /* } /** * Constructs a Name Form from the raw string value returned on a * schema query for nameForms. * * @param raw The raw string value returned on a schema * query for nameForms. */ public LdapNameFormSchema(System.String raw):base(LdapSchema.schemaTypeNames[LdapSchema.NAME_FORM]) { base.obsolete = false; try { SchemaParser parser = new SchemaParser(raw); if (parser.Names != null) { base.names = new System.String[parser.Names.Length]; parser.Names.CopyTo(base.names, 0); } if ((System.Object) parser.ID != null) base.oid = new System.Text.StringBuilder(parser.ID).ToString(); if ((System.Object) parser.Description != null) base.description = new System.Text.StringBuilder(parser.Description).ToString(); if (parser.Required != null) { required = new System.String[parser.Required.Length]; parser.Required.CopyTo(required, 0); } if (parser.Optional != null) { optional = new System.String[parser.Optional.Length]; parser.Optional.CopyTo(optional, 0); } if ((System.Object) parser.ObjectClass != null) objectClass = parser.ObjectClass; base.obsolete = parser.Obsolete; System.Collections.IEnumerator qualifiers = parser.Qualifiers; AttributeQualifier attrQualifier; while (qualifiers.MoveNext()) { attrQualifier = (AttributeQualifier) qualifiers.Current; setQualifier(attrQualifier.Name, attrQualifier.Values); } base.Value = formatString(); } catch (System.IO.IOException e) { } return ; } /// <summary> Returns a string in a format suitable for directly adding to a /// directory, as a value of the particular schema element class. /// /// </summary> /// <returns> A string representation of the class' definition. /// </returns> protected internal override System.String formatString() { System.Text.StringBuilder valueBuffer = new System.Text.StringBuilder("( "); System.String token; System.String[] strArray; if ((System.Object) (token = ID) != null) { valueBuffer.Append(token); } strArray = Names; if (strArray != null) { valueBuffer.Append(" NAME "); if (strArray.Length == 1) { valueBuffer.Append("'" + strArray[0] + "'"); } else { valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { valueBuffer.Append(" '" + strArray[i] + "'"); } valueBuffer.Append(" )"); } } if ((System.Object) (token = Description) != null) { valueBuffer.Append(" DESC "); valueBuffer.Append("'" + token + "'"); } if (Obsolete) { valueBuffer.Append(" OBSOLETE"); } if ((System.Object) (token = ObjectClass) != null) { valueBuffer.Append(" OC "); valueBuffer.Append("'" + token + "'"); } if ((strArray = RequiredNamingAttributes) != null) { valueBuffer.Append(" MUST "); if (strArray.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { if (i > 0) valueBuffer.Append(" $ "); valueBuffer.Append(strArray[i]); } if (strArray.Length > 1) valueBuffer.Append(" )"); } if ((strArray = OptionalNamingAttributes) != null) { valueBuffer.Append(" MAY "); if (strArray.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < strArray.Length; i++) { if (i > 0) valueBuffer.Append(" $ "); valueBuffer.Append(strArray[i]); } if (strArray.Length > 1) valueBuffer.Append(" )"); } System.Collections.IEnumerator en; if ((en = QualifierNames) != null) { System.String qualName; System.String[] qualValue; while (en.MoveNext()) { qualName = ((System.String) en.Current); valueBuffer.Append(" " + qualName + " "); if ((qualValue = getQualifier(qualName)) != null) { if (qualValue.Length > 1) valueBuffer.Append("( "); for (int i = 0; i < qualValue.Length; i++) { if (i > 0) valueBuffer.Append(" "); valueBuffer.Append("'" + qualValue[i] + "'"); } if (qualValue.Length > 1) valueBuffer.Append(" )"); } } } valueBuffer.Append(" )"); return valueBuffer.ToString(); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion #if !PORTABLE40 using System; using System.Collections.Generic; using System.Globalization; using System.Xml; #if !(NET20 || PORTABLE40) using System.Xml.Linq; #endif using Arch.CMessaging.Client.Newtonsoft.Json.Utilities; #if NET20 using Arch.CMessaging.Client.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Arch.CMessaging.Client.Newtonsoft.Json.Converters { #region XmlNodeWrappers #if !NETFX_CORE && !PORTABLE && !PORTABLE40 internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument { private readonly XmlDocument _document; public XmlDocumentWrapper(XmlDocument document) : base(document) { _document = document; } public IXmlNode CreateComment(string data) { return new XmlNodeWrapper(_document.CreateComment(data)); } public IXmlNode CreateTextNode(string text) { return new XmlNodeWrapper(_document.CreateTextNode(text)); } public IXmlNode CreateCDataSection(string data) { return new XmlNodeWrapper(_document.CreateCDataSection(data)); } public IXmlNode CreateWhitespace(string text) { return new XmlNodeWrapper(_document.CreateWhitespace(text)); } public IXmlNode CreateSignificantWhitespace(string text) { return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text)); } public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XmlDeclarationWrapper(_document.CreateXmlDeclaration(version, encoding, standalone)); } public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XmlDocumentTypeWrapper(_document.CreateDocumentType(name, publicId, systemId, null)); } public IXmlNode CreateProcessingInstruction(string target, string data) { return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data)); } public IXmlElement CreateElement(string elementName) { return new XmlElementWrapper(_document.CreateElement(elementName)); } public IXmlElement CreateElement(string qualifiedName, string namespaceUri) { return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri)); } public IXmlNode CreateAttribute(string name, string value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name)); attribute.Value = value; return attribute; } public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri)); attribute.Value = value; return attribute; } public IXmlElement DocumentElement { get { if (_document.DocumentElement == null) return null; return new XmlElementWrapper(_document.DocumentElement); } } } internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement { private readonly XmlElement _element; public XmlElementWrapper(XmlElement element) : base(element) { _element = element; } public void SetAttributeNode(IXmlNode attribute) { XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute; _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode); } public string GetPrefixOfNamespace(string namespaceUri) { return _element.GetPrefixOfNamespace(namespaceUri); } public bool IsEmpty { get { return _element.IsEmpty; } } } internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration { private readonly XmlDeclaration _declaration; public XmlDeclarationWrapper(XmlDeclaration declaration) : base(declaration) { _declaration = declaration; } public string Version { get { return _declaration.Version; } } public string Encoding { get { return _declaration.Encoding; } set { _declaration.Encoding = value; } } public string Standalone { get { return _declaration.Standalone; } set { _declaration.Standalone = value; } } } internal class XmlDocumentTypeWrapper : XmlNodeWrapper, IXmlDocumentType { private readonly XmlDocumentType _documentType; public XmlDocumentTypeWrapper(XmlDocumentType documentType) : base(documentType) { _documentType = documentType; } public string Name { get { return _documentType.Name; } } public string System { get { return _documentType.SystemId; } } public string Public { get { return _documentType.PublicId; } } public string InternalSubset { get { return _documentType.InternalSubset; } } public override string LocalName { get { return "DOCTYPE"; } } } internal class XmlNodeWrapper : IXmlNode { private readonly XmlNode _node; private IList<IXmlNode> _childNodes; public XmlNodeWrapper(XmlNode node) { _node = node; } public object WrappedNode { get { return _node; } } public XmlNodeType NodeType { get { return _node.NodeType; } } public virtual string LocalName { get { return _node.LocalName; } } public IList<IXmlNode> ChildNodes { get { // childnodes is read multiple times // cache results to prevent multiple reads which kills perf in large documents if (_childNodes == null) _childNodes = _node.ChildNodes.Cast<XmlNode>().Select(WrapNode).ToList(); return _childNodes; } } internal static IXmlNode WrapNode(XmlNode node) { switch (node.NodeType) { case XmlNodeType.Element: return new XmlElementWrapper((XmlElement) node); case XmlNodeType.XmlDeclaration: return new XmlDeclarationWrapper((XmlDeclaration) node); case XmlNodeType.DocumentType: return new XmlDocumentTypeWrapper((XmlDocumentType) node); default: return new XmlNodeWrapper(node); } } public IList<IXmlNode> Attributes { get { if (_node.Attributes == null) return null; return _node.Attributes.Cast<XmlAttribute>().Select(WrapNode).ToList(); } } public IXmlNode ParentNode { get { XmlNode node = (_node is XmlAttribute) ? ((XmlAttribute) _node).OwnerElement : _node.ParentNode; if (node == null) return null; return WrapNode(node); } } public string Value { get { return _node.Value; } set { _node.Value = value; } } public IXmlNode AppendChild(IXmlNode newChild) { XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper) newChild; _node.AppendChild(xmlNodeWrapper._node); _childNodes = null; return newChild; } public string NamespaceUri { get { return _node.NamespaceURI; } } } #endif #endregion #region Interfaces internal interface IXmlDocument : IXmlNode { IXmlNode CreateComment(string text); IXmlNode CreateTextNode(string text); IXmlNode CreateCDataSection(string data); IXmlNode CreateWhitespace(string text); IXmlNode CreateSignificantWhitespace(string text); IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone); IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset); IXmlNode CreateProcessingInstruction(string target, string data); IXmlElement CreateElement(string elementName); IXmlElement CreateElement(string qualifiedName, string namespaceUri); IXmlNode CreateAttribute(string name, string value); IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); IXmlElement DocumentElement { get; } } internal interface IXmlDeclaration : IXmlNode { string Version { get; } string Encoding { get; set; } string Standalone { get; set; } } internal interface IXmlDocumentType : IXmlNode { string Name { get; } string System { get; } string Public { get; } string InternalSubset { get; } } internal interface IXmlElement : IXmlNode { void SetAttributeNode(IXmlNode attribute); string GetPrefixOfNamespace(string namespaceUri); bool IsEmpty { get; } } internal interface IXmlNode { XmlNodeType NodeType { get; } string LocalName { get; } IList<IXmlNode> ChildNodes { get; } IList<IXmlNode> Attributes { get; } IXmlNode ParentNode { get; } string Value { get; set; } IXmlNode AppendChild(IXmlNode newChild); string NamespaceUri { get; } object WrappedNode { get; } } #endregion #region XNodeWrappers #if !NET20 internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration { internal XDeclaration Declaration { get; private set; } public XDeclarationWrapper(XDeclaration declaration) : base(null) { Declaration = declaration; } public override XmlNodeType NodeType { get { return XmlNodeType.XmlDeclaration; } } public string Version { get { return Declaration.Version; } } public string Encoding { get { return Declaration.Encoding; } set { Declaration.Encoding = value; } } public string Standalone { get { return Declaration.Standalone; } set { Declaration.Standalone = value; } } } internal class XDocumentTypeWrapper : XObjectWrapper, IXmlDocumentType { private readonly XDocumentType _documentType; public XDocumentTypeWrapper(XDocumentType documentType) : base(documentType) { _documentType = documentType; } public string Name { get { return _documentType.Name; } } public string System { get { return _documentType.SystemId; } } public string Public { get { return _documentType.PublicId; } } public string InternalSubset { get { return _documentType.InternalSubset; } } public override string LocalName { get { return "DOCTYPE"; } } } internal class XDocumentWrapper : XContainerWrapper, IXmlDocument { private XDocument Document { get { return (XDocument)WrappedNode; } } public XDocumentWrapper(XDocument document) : base(document) { } public override IList<IXmlNode> ChildNodes { get { IList<IXmlNode> childNodes = base.ChildNodes; if (Document.Declaration != null && childNodes[0].NodeType != XmlNodeType.XmlDeclaration) childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration)); return childNodes; } } public IXmlNode CreateComment(string text) { return new XObjectWrapper(new XComment(text)); } public IXmlNode CreateTextNode(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateCDataSection(string data) { return new XObjectWrapper(new XCData(data)); } public IXmlNode CreateWhitespace(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateSignificantWhitespace(string text) { return new XObjectWrapper(new XText(text)); } public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) { return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); } public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XDocumentTypeWrapper(new XDocumentType(name, publicId, systemId, internalSubset)); } public IXmlNode CreateProcessingInstruction(string target, string data) { return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); } public IXmlElement CreateElement(string elementName) { return new XElementWrapper(new XElement(elementName)); } public IXmlElement CreateElement(string qualifiedName, string namespaceUri) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); } public IXmlNode CreateAttribute(string name, string value) { return new XAttributeWrapper(new XAttribute(name, value)); } public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); } public IXmlElement DocumentElement { get { if (Document.Root == null) return null; return new XElementWrapper(Document.Root); } } public override IXmlNode AppendChild(IXmlNode newChild) { XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper; if (declarationWrapper != null) { Document.Declaration = declarationWrapper.Declaration; return declarationWrapper; } else { return base.AppendChild(newChild); } } } internal class XTextWrapper : XObjectWrapper { private XText Text { get { return (XText)WrappedNode; } } public XTextWrapper(XText text) : base(text) { } public override string Value { get { return Text.Value; } set { Text.Value = value; } } public override IXmlNode ParentNode { get { if (Text.Parent == null) return null; return XContainerWrapper.WrapNode(Text.Parent); } } } internal class XCommentWrapper : XObjectWrapper { private XComment Text { get { return (XComment)WrappedNode; } } public XCommentWrapper(XComment text) : base(text) { } public override string Value { get { return Text.Value; } set { Text.Value = value; } } public override IXmlNode ParentNode { get { if (Text.Parent == null) return null; return XContainerWrapper.WrapNode(Text.Parent); } } } internal class XProcessingInstructionWrapper : XObjectWrapper { private XProcessingInstruction ProcessingInstruction { get { return (XProcessingInstruction)WrappedNode; } } public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction) : base(processingInstruction) { } public override string LocalName { get { return ProcessingInstruction.Target; } } public override string Value { get { return ProcessingInstruction.Data; } set { ProcessingInstruction.Data = value; } } } internal class XContainerWrapper : XObjectWrapper { private IList<IXmlNode> _childNodes; private XContainer Container { get { return (XContainer)WrappedNode; } } public XContainerWrapper(XContainer container) : base(container) { } public override IList<IXmlNode> ChildNodes { get { // childnodes is read multiple times // cache results to prevent multiple reads which kills perf in large documents if (_childNodes == null) _childNodes = Container.Nodes().Select(WrapNode).ToList(); return _childNodes; } } public override IXmlNode ParentNode { get { if (Container.Parent == null) return null; return WrapNode(Container.Parent); } } internal static IXmlNode WrapNode(XObject node) { if (node is XDocument) return new XDocumentWrapper((XDocument)node); else if (node is XElement) return new XElementWrapper((XElement)node); else if (node is XContainer) return new XContainerWrapper((XContainer)node); else if (node is XProcessingInstruction) return new XProcessingInstructionWrapper((XProcessingInstruction)node); else if (node is XText) return new XTextWrapper((XText)node); else if (node is XComment) return new XCommentWrapper((XComment)node); else if (node is XAttribute) return new XAttributeWrapper((XAttribute)node); else if (node is XDocumentType) return new XDocumentTypeWrapper((XDocumentType)node); else return new XObjectWrapper(node); } public override IXmlNode AppendChild(IXmlNode newChild) { Container.Add(newChild.WrappedNode); _childNodes = null; return newChild; } } internal class XObjectWrapper : IXmlNode { private readonly XObject _xmlObject; public XObjectWrapper(XObject xmlObject) { _xmlObject = xmlObject; } public object WrappedNode { get { return _xmlObject; } } public virtual XmlNodeType NodeType { get { return _xmlObject.NodeType; } } public virtual string LocalName { get { return null; } } public virtual IList<IXmlNode> ChildNodes { get { return new List<IXmlNode>(); } } public virtual IList<IXmlNode> Attributes { get { return null; } } public virtual IXmlNode ParentNode { get { return null; } } public virtual string Value { get { return null; } set { throw new InvalidOperationException(); } } public virtual IXmlNode AppendChild(IXmlNode newChild) { throw new InvalidOperationException(); } public virtual string NamespaceUri { get { return null; } } } internal class XAttributeWrapper : XObjectWrapper { private XAttribute Attribute { get { return (XAttribute)WrappedNode; } } public XAttributeWrapper(XAttribute attribute) : base(attribute) { } public override string Value { get { return Attribute.Value; } set { Attribute.Value = value; } } public override string LocalName { get { return Attribute.Name.LocalName; } } public override string NamespaceUri { get { return Attribute.Name.NamespaceName; } } public override IXmlNode ParentNode { get { if (Attribute.Parent == null) return null; return XContainerWrapper.WrapNode(Attribute.Parent); } } } internal class XElementWrapper : XContainerWrapper, IXmlElement { private XElement Element { get { return (XElement)WrappedNode; } } public XElementWrapper(XElement element) : base(element) { } public void SetAttributeNode(IXmlNode attribute) { XObjectWrapper wrapper = (XObjectWrapper)attribute; Element.Add(wrapper.WrappedNode); } public override IList<IXmlNode> Attributes { get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); } } public override string Value { get { return Element.Value; } set { Element.Value = value; } } public override string LocalName { get { return Element.Name.LocalName; } } public override string NamespaceUri { get { return Element.Name.NamespaceName; } } public string GetPrefixOfNamespace(string namespaceUri) { return Element.GetPrefixOfNamespace(namespaceUri); } public bool IsEmpty { get { return Element.IsEmpty; } } } #endif #endregion /// <summary> /// Converts XML to and from JSON. /// </summary> public class XmlNodeConverter : JsonConverter { private const string TextName = "#text"; private const string CommentName = "#comment"; private const string CDataName = "#cdata-section"; private const string WhitespaceName = "#whitespace"; private const string SignificantWhitespaceName = "#significant-whitespace"; private const string DeclarationName = "?xml"; private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json"; /// <summary> /// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements. /// </summary> /// <value>The name of the deserialize root element.</value> public string DeserializeRootElementName { get; set; } /// <summary> /// Gets or sets a flag to indicate whether to write the Json.NET array attribute. /// This attribute helps preserve arrays when converting the written XML back to JSON. /// </summary> /// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value> public bool WriteArrayAttribute { get; set; } /// <summary> /// Gets or sets a value indicating whether to write the root JSON object. /// </summary> /// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value> public bool OmitRootObject { get; set; } #region Writing /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="serializer">The calling serializer.</param> /// <param name="value">The value.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IXmlNode node = WrapXml(value); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); PushParentNamespaces(node, manager); if (!OmitRootObject) writer.WriteStartObject(); SerializeNode(writer, node, manager, !OmitRootObject); if (!OmitRootObject) writer.WriteEndObject(); } private IXmlNode WrapXml(object value) { #if !NET20 if (value is XObject) return XContainerWrapper.WrapNode((XObject)value); #endif #if !(NETFX_CORE || PORTABLE) if (value is XmlNode) return XmlNodeWrapper.WrapNode((XmlNode)value); #endif throw new ArgumentException("Value must be an XML object.", "value"); } private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { List<IXmlNode> parentElements = null; IXmlNode parent = node; while ((parent = parent.ParentNode) != null) { if (parent.NodeType == XmlNodeType.Element) { if (parentElements == null) parentElements = new List<IXmlNode>(); parentElements.Add(parent); } } if (parentElements != null) { parentElements.Reverse(); foreach (IXmlNode parentElement in parentElements) { manager.PushScope(); foreach (IXmlNode attribute in parentElement.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") manager.AddNamespace(attribute.LocalName, attribute.Value); } } } } private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) { string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) ? null : manager.LookupPrefix(node.NamespaceUri); if (!string.IsNullOrEmpty(prefix)) return prefix + ":" + node.LocalName; else return node.LocalName; } private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager) { switch (node.NodeType) { case XmlNodeType.Attribute: if (node.NamespaceUri == JsonNamespaceUri) return "$" + node.LocalName; else return "@" + ResolveFullName(node, manager); case XmlNodeType.CDATA: return CDataName; case XmlNodeType.Comment: return CommentName; case XmlNodeType.Element: return ResolveFullName(node, manager); case XmlNodeType.ProcessingInstruction: return "?" + ResolveFullName(node, manager); case XmlNodeType.DocumentType: return "!" + ResolveFullName(node, manager); case XmlNodeType.XmlDeclaration: return DeclarationName; case XmlNodeType.SignificantWhitespace: return SignificantWhitespaceName; case XmlNodeType.Text: return TextName; case XmlNodeType.Whitespace: return WhitespaceName; default: throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType); } } private bool IsArray(IXmlNode node) { IXmlNode jsonArrayAttribute = (node.Attributes != null) ? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri) : null; return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value)); } private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { // group nodes together by name Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>(); for (int i = 0; i < node.ChildNodes.Count; i++) { IXmlNode childNode = node.ChildNodes[i]; string nodeName = GetPropertyName(childNode, manager); List<IXmlNode> nodes; if (!nodesGroupedByName.TryGetValue(nodeName, out nodes)) { nodes = new List<IXmlNode>(); nodesGroupedByName.Add(nodeName, nodes); } nodes.Add(childNode); } // loop through grouped nodes. write single name instances as normal, // write multiple names together in an array foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName) { List<IXmlNode> groupedNodes = nodeNameGroup.Value; bool writeArray; if (groupedNodes.Count == 1) { writeArray = IsArray(groupedNodes[0]); } else { writeArray = true; } if (!writeArray) { SerializeNode(writer, groupedNodes[0], manager, writePropertyName); } else { string elementNames = nodeNameGroup.Key; if (writePropertyName) writer.WritePropertyName(elementNames); writer.WriteStartArray(); for (int i = 0; i < groupedNodes.Count; i++) { SerializeNode(writer, groupedNodes[i], manager, false); } writer.WriteEndArray(); } } } private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) { switch (node.NodeType) { case XmlNodeType.Document: case XmlNodeType.DocumentFragment: SerializeGroupedNodes(writer, node, manager, writePropertyName); break; case XmlNodeType.Element: if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0) { SerializeGroupedNodes(writer, node, manager, false); } else { manager.PushScope(); foreach (IXmlNode attribute in node.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string namespacePrefix = (attribute.LocalName != "xmlns") ? attribute.LocalName : string.Empty; string namespaceUri = attribute.Value; manager.AddNamespace(namespacePrefix, namespaceUri); } } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) { // write elements with a single text child as a name value pair writer.WriteValue(node.ChildNodes[0].Value); } else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes)) { IXmlElement element = (IXmlElement)node; // empty element if (element.IsEmpty) writer.WriteNull(); else writer.WriteValue(string.Empty); } else { writer.WriteStartObject(); for (int i = 0; i < node.Attributes.Count; i++) { SerializeNode(writer, node.Attributes[i], manager, true); } SerializeGroupedNodes(writer, node, manager, true); writer.WriteEndObject(); } manager.PopScope(); } break; case XmlNodeType.Comment: if (writePropertyName) writer.WriteComment(node.Value); break; case XmlNodeType.Attribute: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri) return; if (node.NamespaceUri == JsonNamespaceUri) { if (node.LocalName == "Array") return; } if (writePropertyName) writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteValue(node.Value); break; case XmlNodeType.XmlDeclaration: IXmlDeclaration declaration = (IXmlDeclaration)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(declaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(declaration.Version); } if (!string.IsNullOrEmpty(declaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(declaration.Encoding); } if (!string.IsNullOrEmpty(declaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(declaration.Standalone); } writer.WriteEndObject(); break; case XmlNodeType.DocumentType: IXmlDocumentType documentType = (IXmlDocumentType)node; writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); if (!string.IsNullOrEmpty(documentType.Name)) { writer.WritePropertyName("@name"); writer.WriteValue(documentType.Name); } if (!string.IsNullOrEmpty(documentType.Public)) { writer.WritePropertyName("@public"); writer.WriteValue(documentType.Public); } if (!string.IsNullOrEmpty(documentType.System)) { writer.WritePropertyName("@system"); writer.WriteValue(documentType.System); } if (!string.IsNullOrEmpty(documentType.InternalSubset)) { writer.WritePropertyName("@internalSubset"); writer.WriteValue(documentType.InternalSubset); } writer.WriteEndObject(); break; default: throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType); } } #endregion #region Reading /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); IXmlDocument document = null; IXmlNode rootNode = null; #if !NET20 if (typeof(XObject).IsAssignableFrom(objectType)) { if (objectType != typeof(XDocument) && objectType != typeof(XElement)) throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement."); XDocument d = new XDocument(); document = new XDocumentWrapper(d); rootNode = document; } #endif #if !(NETFX_CORE || PORTABLE) if (typeof(XmlNode).IsAssignableFrom(objectType)) { if (objectType != typeof(XmlDocument)) throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments"); XmlDocument d = new XmlDocument(); // prevent http request when resolving any DTD references d.XmlResolver = null; document = new XmlDocumentWrapper(d); rootNode = document; } #endif if (document == null || rootNode == null) throw new JsonSerializationException("Unexpected type when converting XML: " + objectType); if (reader.TokenType != JsonToken.StartObject) throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object."); if (!string.IsNullOrEmpty(DeserializeRootElementName)) { //rootNode = document.CreateElement(DeserializeRootElementName); //document.AppendChild(rootNode); ReadElement(reader, document, rootNode, DeserializeRootElementName, manager); } else { reader.Read(); DeserializeNode(reader, document, manager, rootNode); } #if !NET20 if (objectType == typeof(XElement)) { XElement element = (XElement)document.DocumentElement.WrappedNode; element.Remove(); return element; } #endif return document.WrappedNode; } private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode) { switch (propertyName) { case TextName: currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString())); break; case CDataName: currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString())); break; case WhitespaceName: currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString())); break; case SignificantWhitespaceName: currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString())); break; default: // processing instructions and the xml declaration start with ? if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?') { CreateInstruction(reader, document, currentNode, propertyName); } else if (string.Equals(propertyName, "!DOCTYPE", StringComparison.OrdinalIgnoreCase)) { CreateDocumentType(reader, document, currentNode); } else { if (reader.TokenType == JsonToken.StartArray) { // handle nested arrays ReadArrayElements(reader, document, propertyName, currentNode, manager); return; } // have to wait until attributes have been parsed before creating element // attributes may contain namespace info used by the element ReadElement(reader, document, currentNode, propertyName, manager); } break; } } private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML."); Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager); string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); if (propertyName.StartsWith('@')) { string attributeName = propertyName.Substring(1); string attributeValue = reader.Value.ToString(); string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(attributeName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); } else { IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(element); // add attributes to newly created element foreach (KeyValuePair<string, string> nameValue in attributeNameValues) { string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value) : document.CreateAttribute(nameValue.Key, nameValue.Value); element.SetAttributeNode(attribute); } if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Boolean || reader.TokenType == JsonToken.Date) { element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader))); } else if (reader.TokenType == JsonToken.Null) { // empty element. do nothing } else { // finished element will have no children to deserialize if (reader.TokenType != JsonToken.EndObject) { manager.PushScope(); DeserializeNode(reader, document, manager, element); manager.PopScope(); } manager.RemoveNamespace(string.Empty, manager.DefaultNamespace); } } } private string ConvertTokenToXmlValue(JsonReader reader) { if (reader.TokenType == JsonToken.String) { return reader.Value.ToString(); } else if (reader.TokenType == JsonToken.Integer) { return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Float) { if (reader.Value is decimal) return XmlConvert.ToString((decimal)reader.Value); if (reader.Value is float) return XmlConvert.ToString((float)reader.Value); return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Boolean) { return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Date) { #if !NET20 if (reader.Value is DateTimeOffset) return XmlConvert.ToString((DateTimeOffset)reader.Value); #endif DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture); #if !(NETFX_CORE || PORTABLE) return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind)); #else return XmlConvert.ToString(d); #endif } else if (reader.TokenType == JsonToken.Null) { return null; } else { throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager) { string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager); currentNode.AppendChild(nestedArrayElement); int count = 0; while (reader.Read() && reader.TokenType != JsonToken.EndArray) { DeserializeValue(reader, document, manager, propertyName, nestedArrayElement); count++; } if (WriteArrayAttribute) { AddJsonArrayAttribute(nestedArrayElement, document); } if (count == 1 && WriteArrayAttribute) { IXmlElement arrayElement = nestedArrayElement.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName); AddJsonArrayAttribute(arrayElement, document); } } private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document) { element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true")); #if !NET20 // linq to xml doesn't automatically include prefixes via the namespace manager if (element is XElementWrapper) { if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null) { element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri)); } } #endif } private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) { Dictionary<string, string> attributeNameValues = new Dictionary<string, string>(); bool finishedAttributes = false; bool finishedElement = false; // a string token means the element only has a single text child if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null && reader.TokenType != JsonToken.Boolean && reader.TokenType != JsonToken.Integer && reader.TokenType != JsonToken.Float && reader.TokenType != JsonToken.Date && reader.TokenType != JsonToken.StartConstructor) { // read properties until first non-attribute is encountered while (!finishedAttributes && !finishedElement && reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: string attributeName = reader.Value.ToString(); if (!string.IsNullOrEmpty(attributeName)) { char firstChar = attributeName[0]; string attributeValue; switch (firstChar) { case '@': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = ConvertTokenToXmlValue(reader); attributeNameValues.Add(attributeName, attributeValue); string namespacePrefix; if (IsNamespaceAttribute(attributeName, out namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } break; case '$': attributeName = attributeName.Substring(1); reader.Read(); attributeValue = reader.Value.ToString(); // check that JsonNamespaceUri is in scope // if it isn't then add it to document and namespace manager string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); if (jsonPrefix == null) { // ensure that the prefix used is free int? i = null; while (manager.LookupNamespace("json" + i) != null) { i = i.GetValueOrDefault() + 1; } jsonPrefix = "json" + i; attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri); manager.AddNamespace(jsonPrefix, JsonNamespaceUri); } attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue); break; default: finishedAttributes = true; break; } } else { finishedAttributes = true; } break; case JsonToken.EndObject: finishedElement = true; break; case JsonToken.Comment: finishedElement = true; break; default: throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType); } } } return attributeNameValues; } private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName) { if (propertyName == DeclarationName) { string version = null; string encoding = null; string standalone = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { switch (reader.Value.ToString()) { case "@version": reader.Read(); version = reader.Value.ToString(); break; case "@encoding": reader.Read(); encoding = reader.Value.ToString(); break; case "@standalone": reader.Read(); standalone = reader.Value.ToString(); break; default: throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); } } IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone); currentNode.AppendChild(declaration); } else { IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString()); currentNode.AppendChild(instruction); } } private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNode currentNode) { string name = null; string publicId = null; string systemId = null; string internalSubset = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { switch (reader.Value.ToString()) { case "@name": reader.Read(); name = reader.Value.ToString(); break; case "@public": reader.Read(); publicId = reader.Value.ToString(); break; case "@system": reader.Read(); systemId = reader.Value.ToString(); break; case "@internalSubset": reader.Read(); internalSubset = reader.Value.ToString(); break; default: throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); } } IXmlNode documentType = document.CreateXmlDocumentType(name, publicId, systemId, internalSubset); currentNode.AppendChild(documentType); } private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) { string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(elementName, ns) : document.CreateElement(elementName); return element; } private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode) { do { switch (reader.TokenType) { case JsonToken.PropertyName: if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null) throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); string propertyName = reader.Value.ToString(); reader.Read(); if (reader.TokenType == JsonToken.StartArray) { int count = 0; while (reader.Read() && reader.TokenType != JsonToken.EndArray) { DeserializeValue(reader, document, manager, propertyName, currentNode); count++; } if (count == 1 && WriteArrayAttribute) { IXmlElement arrayElement = currentNode.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName); AddJsonArrayAttribute(arrayElement, document); } } else { DeserializeValue(reader, document, manager, propertyName, currentNode); } break; case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { DeserializeValue(reader, document, manager, constructorName, currentNode); } break; case JsonToken.Comment: currentNode.AppendChild(document.CreateComment((string)reader.Value)); break; case JsonToken.EndObject: case JsonToken.EndArray: return; default: throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType); } } while (reader.TokenType == JsonToken.PropertyName || reader.Read()); // don't read if current token is a property. token was already read when parsing element attributes } /// <summary> /// Checks if the attributeName is a namespace attribute. /// </summary> /// <param name="attributeName">Attribute name to test.</param> /// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param> /// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns> private bool IsNamespaceAttribute(string attributeName, out string prefix) { if (attributeName.StartsWith("xmlns", StringComparison.Ordinal)) { if (attributeName.Length == 5) { prefix = string.Empty; return true; } else if (attributeName[5] == ':') { prefix = attributeName.Substring(6, attributeName.Length - 6); return true; } } prefix = null; return false; } private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c) { return c.Where(a => a.NamespaceUri != JsonNamespaceUri); } #endregion /// <summary> /// Determines whether this instance can convert the specified value type. /// </summary> /// <param name="valueType">Type of the value.</param> /// <returns> /// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type valueType) { #if !NET20 if (typeof(XObject).IsAssignableFrom(valueType)) return true; #endif #if !(NETFX_CORE || PORTABLE) if (typeof(XmlNode).IsAssignableFrom(valueType)) return true; #endif return false; } } } #endif
#region Copyright (c) Microsoft Corporation /// <copyright company='Microsoft Corporation'> /// Copyright (c) Microsoft Corporation. All Rights Reserved. /// Information Contained Herein is Proprietary and Confidential. /// </copyright> #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Web.Services.Description; using System.Xml; #if WEB_EXTENSIONS_CODE using System.Web.Resources; #else using Microsoft.VSDesigner.WCF.Resources; #endif #if WEB_EXTENSIONS_CODE namespace System.Web.Compilation.WCFModel #else namespace Microsoft.VSDesigner.WCFModel #endif { /// <summary> /// This class check whether there are duplicated wsdl files in the metadata collection, and report error messages, if any contract is /// defined differently in two wsdl files. /// </summary> internal class WsdlInspector { private IList<ProxyGenerationError> importErrors; private Dictionary<XmlQualifiedName, PortType> portTypes; private Dictionary<XmlQualifiedName, Message> messages; /// <summary> /// constructor /// </summary> /// <remarks></remarks> private WsdlInspector(IList<ProxyGenerationError> importErrors) { this.importErrors = importErrors; this.portTypes = new Dictionary<XmlQualifiedName, PortType>(); this.messages = new Dictionary<XmlQualifiedName, Message>(); } /// <summary> /// function to check duplicated items /// </summary> /// <param name="wsdlFiles"></param> /// <param name="importErrors"></param> /// <remarks></remarks> internal static void CheckDuplicatedWsdlItems(ICollection<ServiceDescription> wsdlFiles, IList<ProxyGenerationError> importErrors) { WsdlInspector inspector = new WsdlInspector(importErrors); inspector.CheckServiceDescriptions(wsdlFiles); } /// <summary> /// check all duplicated items in a collection of files /// </summary> /// <remarks></remarks> private void CheckServiceDescriptions(ICollection<ServiceDescription> wsdlFiles) { foreach (System.Web.Services.Description.ServiceDescription wsdl in wsdlFiles) { string targetNamespace = wsdl.TargetNamespace; if (String.IsNullOrEmpty(targetNamespace)) { targetNamespace = String.Empty; } // check all portTypes... foreach (PortType portType in wsdl.PortTypes) { XmlQualifiedName portTypeName = new XmlQualifiedName(portType.Name, targetNamespace); PortType definedPortType; if (portTypes.TryGetValue(portTypeName, out definedPortType)) { MatchPortTypes(definedPortType, portType); } else { portTypes.Add(portTypeName, portType); } } // check all messages... foreach (Message message in wsdl.Messages) { XmlQualifiedName messageName = new XmlQualifiedName(message.Name, targetNamespace); Message definedMessage; if (messages.TryGetValue(messageName, out definedMessage)) { MatchMessages(definedMessage, message); } else { messages.Add(messageName, message); } } } } /// <summary> /// Compare two port type (with same targetNamespace/name) /// </summary> /// <remarks></remarks> private void MatchPortTypes(PortType x, PortType y) { Operation[] operationsX = new Operation[x.Operations.Count]; x.Operations.CopyTo(operationsX, 0); Array.Sort(operationsX, new OperationComparer()); Operation[] operationsY = new Operation[y.Operations.Count]; y.Operations.CopyTo(operationsY, 0); Array.Sort(operationsY, new OperationComparer()); MatchCollections<Operation>(operationsX, operationsY, delegate(Operation operationX, Operation operationY) { if (operationX != null && operationY != null) { int nameDifferent = String.Compare(operationX.Name, operationY.Name, StringComparison.Ordinal); if (nameDifferent < 0) { ReportUniqueOperation(operationX, x, y); return false; } else if (nameDifferent > 0) { ReportUniqueOperation(operationY, y, x); return false; } else if (!MatchOperations(operationX, operationY)) { return false; } return true; } else if (operationX != null) { ReportUniqueOperation(operationX, x, y); return false; } else if (operationY != null) { ReportUniqueOperation(operationY, y, x); return false; } return true; } ); } /// <summary> /// Compare two operations (with same name) /// </summary> /// <remarks></remarks> private bool MatchOperations(Operation x, Operation y) { if (!MatchOperationMessages(x.Messages.Input, y.Messages.Input)) { ReportOperationDefinedDifferently(x, y); return false; } if (!MatchOperationMessages(x.Messages.Output, y.Messages.Output)) { ReportOperationDefinedDifferently(x, y); return false; } OperationFault[] faultsX = new OperationFault[x.Faults.Count]; x.Faults.CopyTo(faultsX, 0); Array.Sort(faultsX, new OperationFaultComparer()); OperationFault[] faultsY = new OperationFault[y.Faults.Count]; y.Faults.CopyTo(faultsY, 0); Array.Sort(faultsY, new OperationFaultComparer()); if (!MatchCollections<OperationFault>(faultsX, faultsY, delegate(OperationFault faultX, OperationFault faultY) { if (faultX != null && faultY != null) { return MatchXmlQualifiedNames(faultX.Message, faultY.Message); } else if (faultX != null || faultY != null) { return false; } return true; } )) { ReportOperationDefinedDifferently(x, y); return false; } return true; } /// <summary> /// Compare two messages in operations (with same name) /// </summary> /// <remarks></remarks> private bool MatchOperationMessages(OperationMessage x, OperationMessage y) { if (x == null && y == null) { return true; } else if (x == null || y == null) { return false; } return MatchXmlQualifiedNames(x.Message, y.Message); } /// <summary> /// Compare two messages defined in wsdl (with same name/targetNamespace) /// </summary> /// <remarks></remarks> private void MatchMessages(Message x, Message y) { MessagePart[] partsX = new MessagePart[x.Parts.Count]; x.Parts.CopyTo(partsX, 0); Array.Sort(partsX, new MessagePartComparer()); MessagePart[] partsY = new MessagePart[y.Parts.Count]; y.Parts.CopyTo(partsY, 0); Array.Sort(partsY, new MessagePartComparer()); MatchCollections<MessagePart>(partsX, partsY, delegate(MessagePart partX, MessagePart partY) { if (partX != null && partY != null) { int nameDifferent = String.Compare(partX.Name, partY.Name, StringComparison.Ordinal); if (nameDifferent < 0) { ReportUniqueMessagePart(partX, x, y); return false; } else if (nameDifferent > 0) { ReportUniqueMessagePart(partY, y, x); return false; } else if (!MatchMessageParts(partX, partY)) { return false; } return true; } else if (partX != null) { ReportUniqueMessagePart(partX, x, y); return false; } else if (partY != null) { ReportUniqueMessagePart(partY, y, x); return false; } return true; } ); } /// <summary> /// Compare two message parts (with same name) /// </summary> /// <remarks></remarks> private bool MatchMessageParts(MessagePart partX, MessagePart partY) { if (!MatchXmlQualifiedNames(partX.Type, partY.Type) || !MatchXmlQualifiedNames(partX.Element, partY.Element)) { ReportMessageDefinedDifferently(partX, partX.Message, partY.Message); return false; } return true; } /// <summary> /// compare two XmlQualifiedName /// </summary> /// <remarks></remarks> private bool MatchXmlQualifiedNames(XmlQualifiedName x, XmlQualifiedName y) { if (x != null && y != null) { return x == y; // XmlQualifiedName } return x == null && y == null; } /// <summary> /// Report an error when we find operation defined in one place but not another /// </summary> /// <remarks></remarks> private void ReportUniqueOperation(Operation operation, PortType portType1, PortType portType2) { importErrors.Add(new ProxyGenerationError( ProxyGenerationError.GeneratorState.MergeMetadata, String.Empty, new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_OperationDefinedInOneOfDuplicatedServiceContract, portType1.Name, portType1.ServiceDescription.RetrievalUrl, portType2.ServiceDescription.RetrievalUrl, operation.Name) ) ) ); } /// <summary> /// Report an error when we find operation defined in two places differently /// </summary> /// <remarks></remarks> private void ReportOperationDefinedDifferently(Operation x, Operation y) { importErrors.Add(new ProxyGenerationError( ProxyGenerationError.GeneratorState.MergeMetadata, String.Empty, new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_OperationDefinedDifferently, x.Name, x.PortType.Name, x.PortType.ServiceDescription.RetrievalUrl, y.PortType.ServiceDescription.RetrievalUrl) ) ) ); } /// <summary> /// Report an error when we find a part of message defined in one place but not another /// </summary> /// <remarks></remarks> private void ReportUniqueMessagePart(MessagePart part, Message message1, Message message2) { importErrors.Add(new ProxyGenerationError( ProxyGenerationError.GeneratorState.MergeMetadata, String.Empty, new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_FieldDefinedInOneOfDuplicatedMessage, message1.Name, message1.ServiceDescription.RetrievalUrl, message2.ServiceDescription.RetrievalUrl, part.Name) ) ) ); } /// <summary> /// Report an error when we find message defined in two places differently /// </summary> /// <remarks></remarks> private void ReportMessageDefinedDifferently(MessagePart part, Message x, Message y) { importErrors.Add(new ProxyGenerationError( ProxyGenerationError.GeneratorState.MergeMetadata, String.Empty, new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_FieldDefinedDifferentlyInDuplicatedMessage, part.Name, x.Name, x.ServiceDescription.RetrievalUrl, y.ServiceDescription.RetrievalUrl) ) ) ); } /// <summary> /// Helper class to sort Operations /// </summary> /// <remarks></remarks> private class OperationComparer : System.Collections.Generic.IComparer<Operation> { public int Compare(Operation x, Operation y) { return String.Compare(x.Name, y.Name, StringComparison.Ordinal); } } /// <summary> /// Helper class to sort OperationFaults /// </summary> /// <remarks></remarks> private class OperationFaultComparer : System.Collections.Generic.IComparer<OperationFault> { public int Compare(OperationFault x, OperationFault y) { int namespaceResult = String.Compare(x.Message.Namespace, y.Message.Namespace, StringComparison.Ordinal); if (namespaceResult != 0) { return namespaceResult; } return String.Compare(x.Message.Name, y.Message.Name, StringComparison.Ordinal); } } /// <summary> /// Helper class to sort MessageParts /// </summary> /// <remarks></remarks> private class MessagePartComparer : System.Collections.Generic.IComparer<MessagePart> { public int Compare(MessagePart x, MessagePart y) { return String.Compare(x.Name, y.Name, StringComparison.Ordinal); } } /// <summary> /// Helper function to compare two collections /// </summary> /// <remarks></remarks> private delegate bool MatchCollectionItemDelegate<T>(T x, T y); private bool MatchCollections<T>(T[] x, T[] y, MatchCollectionItemDelegate<T> compareItems) where T : class { System.Collections.IEnumerator enumeratorX = x.GetEnumerator(); System.Collections.IEnumerator enumeratorY = y.GetEnumerator(); T tX; T tY; do { tX = enumeratorX.MoveNext() ? (T)enumeratorX.Current : null; tY = enumeratorY.MoveNext() ? (T)enumeratorY.Current : null; if (tX != null && tY != null) { if (!compareItems(tX, tY)) { return false; } } } while (tX != null && tY != null); return compareItems(tX, tY); } } }
#region Using clause using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Runtime.Remoting.Messaging; using Android.App; using Android.Content; using Android.Views; using Android.Widget; using Microsoft.Xna.Framework; using System.Runtime.Serialization; using System.Threading.Tasks; #endregion Using clause namespace CocosSharp { /// <summary> /// IME keyboard implementaion for Android. This class uses an AlerDialog.Builder to create an AlertDialog to be /// presented for input. /// </summary> public class IMEKeyboardImpl : ICCIMEDelegate { private bool isVisible; private string contentText; private static IMEKeyboardImpl instance; public CCTextField TextFieldInFocus { get; set; } /// <summary> /// Returns a shared instance of the platform keyboard implemenation /// </summary> /// <value>The shared instance.</value> public static IMEKeyboardImpl SharedInstance { get { if (instance == null) instance = new IMEKeyboardImpl(); return instance; } } // Based on MonoGame's Guide implementation for Android AlertDialog alertDialog = null; public string ShowKeyboardInput(string defaultText) { var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); var kbi = new CCIMEKeyboardNotificationInfo(); OnKeyboardWillShow(); IsVisible = true; var context = Android.App.Application.Context; var alert = new AlertDialog.Builder(context); var input = new EditText(context) { Text = defaultText }; if (defaultText != null) { input.SetSelection(defaultText.Length); } alert.SetView(input); alert.SetPositiveButton("Ok", (dialog, whichButton) => { ContentText = input.Text; waitHandle.Set(); IsVisible = false; OnKeyboardWillHide(); }); alert.SetNegativeButton("Cancel", (dialog, whichButton) => { ContentText = null; waitHandle.Set(); IsVisible = false; OnKeyboardWillHide(); }); alert.SetCancelable(false); alertDialog = alert.Create(); alertDialog.Show(); OnKeyboardDidShow(); waitHandle.WaitOne(); if (alertDialog != null) { alertDialog.Dismiss(); alertDialog.Dispose(); alertDialog = null; } OnReplaceText(new CCIMEKeybardEventArgs(contentText, contentText.Length)); IsVisible = false; return contentText; } public async Task<string> ShowKeyboardAsync( string defaultText) { var tcs = new TaskCompletionSource<string>(defaultText); var task = Task.Run<string>( () => ShowKeyboardInput(defaultText) ); await task.ContinueWith(t => { // Copy the task result into the returned task. if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions); else if (t.IsCanceled) tcs.TrySetCanceled(); else tcs.TrySetResult(t.Result); }); IsVisible = false; OnKeyboardDidHide(); return task.Result; } #region Properties public bool IsVisible { get { return isVisible; } internal set { isVisible = value; } } #endregion #region IMEDelegate implementation public async Task AttachWithIMEAsync(string title, string defaultText, string text) { contentText = await ShowKeyboardAsync(ContentText); } public bool AttachWithIME() { AttachWithIMEAsync(string.Empty, string.Empty, string.Empty); return true; } public bool DetachWithIME() { if (CanDetachWithIME()) { if (alertDialog != null && alertDialog.IsShowing) { alertDialog.Dismiss(); alertDialog.Dispose(); alertDialog = null; } } return true; } public bool CanAttachWithIME() { if (!IsVisible) return true; return false; } public bool DidAttachWithIME() { return IsVisible; } public bool CanDetachWithIME() { if (IsVisible && alertDialog != null && alertDialog.IsShowing) return true; return false; } public bool DidDetachWithIME() { if (!IsVisible && alertDialog == null) return true; return false; } public event EventHandler<CCIMEKeybardEventArgs> InsertText; bool OnInsertText(CCIMEKeybardEventArgs eventArgs) { var handler = InsertText; if (handler != null) { return ProcessCancelableEvent(handler, eventArgs); } return false; } public event EventHandler<CCIMEKeybardEventArgs> ReplaceText; bool OnReplaceText(CCIMEKeybardEventArgs eventArgs) { var handler = ReplaceText; if (handler != null) { return ProcessCancelableEvent(handler, eventArgs); } return false; } public event EventHandler<CCIMEKeybardEventArgs> DeleteBackward; bool OnDeleteBackward() { var handler = DeleteBackward; if (handler != null) { return ProcessCancelableEvent(handler, new CCIMEKeybardEventArgs(string.Empty, 0)); } return false; } private bool ProcessCancelableEvent(EventHandler<CCIMEKeybardEventArgs> handler, CCIMEKeybardEventArgs eventArgs) { var canceled = false; Delegate inFocusDelegate = null; var sender = TextFieldInFocus; foreach (var instantHandler in handler.GetInvocationList()) { if (eventArgs.Cancel) { break; } // Make sure we process all event handlers except for our focused text field // We need to process it at the end to give the other event handlers a chance // to cancel the event from propogating to our focused text field. if (instantHandler.Target == sender) inFocusDelegate = instantHandler; else instantHandler.DynamicInvoke(sender, eventArgs); } canceled = eventArgs.Cancel; if (inFocusDelegate != null && !canceled) inFocusDelegate.DynamicInvoke(sender, eventArgs); return canceled; } public string ContentText { get { return contentText; } set { contentText = value; } } #region keyboard show/hide notification public event EventHandler<CCIMEKeyboardNotificationInfo> KeyboardWillShow; void OnKeyboardWillShow() { var handler = KeyboardWillShow; if (handler != null) handler(this, new CCIMEKeyboardNotificationInfo()); } public event EventHandler<CCIMEKeyboardNotificationInfo> KeyboardDidShow; void OnKeyboardDidShow() { var handler = KeyboardDidShow; if (handler != null) handler(this, new CCIMEKeyboardNotificationInfo()); } public event EventHandler<CCIMEKeyboardNotificationInfo> KeyboardWillHide; void OnKeyboardWillHide() { var handler = KeyboardWillHide; if (handler != null) handler(this, new CCIMEKeyboardNotificationInfo()); } public event EventHandler<CCIMEKeyboardNotificationInfo> KeyboardDidHide; void OnKeyboardDidHide() { var handler = KeyboardDidHide; if (handler != null) handler(this, new CCIMEKeyboardNotificationInfo()); } #endregion } #endregion }
namespace ClosedXML.Excel { using System; using System.Linq; internal class XLRangeColumn : XLRangeBase, IXLRangeColumn { #region Constructor public XLRangeColumn(XLRangeParameters rangeParameters, bool quickLoad) : base(rangeParameters.RangeAddress) { if (quickLoad) return; SubscribeToShiftedRows((range, rowsShifted) => this.WorksheetRangeShiftedRows(range, rowsShifted)); SubscribeToShiftedColumns((range, columnsShifted) => this.WorksheetRangeShiftedColumns(range, columnsShifted)); SetStyle(rangeParameters.DefaultStyle); } #endregion #region IXLRangeColumn Members IXLCell IXLRangeColumn.Cell(int row) { return Cell(row); } public new IXLCells Cells(string cellsInColumn) { var retVal = new XLCells(false, false); var rangePairs = cellsInColumn.Split(','); foreach (string pair in rangePairs) retVal.Add(Range(pair.Trim()).RangeAddress); return retVal; } public IXLCells Cells(int firstRow, int lastRow) { return Cells(firstRow + ":" + lastRow); } public void Delete() { Delete(XLShiftDeletedCells.ShiftCellsLeft); } public IXLCells InsertCellsAbove(int numberOfRows) { return InsertCellsAbove(numberOfRows, false); } public IXLCells InsertCellsAbove(int numberOfRows, bool expandRange) { return InsertRowsAbove(numberOfRows, expandRange).Cells(); } public IXLCells InsertCellsBelow(int numberOfRows) { return InsertCellsBelow(numberOfRows, true); } public IXLCells InsertCellsBelow(int numberOfRows, bool expandRange) { return InsertRowsBelow(numberOfRows, expandRange).Cells(); } public int CellCount() { return RangeAddress.LastAddress.RowNumber - RangeAddress.FirstAddress.RowNumber + 1; } public IXLRangeColumn Sort(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { base.Sort(1, sortOrder, matchCase, ignoreBlanks); return this; } public new IXLRangeColumn CopyTo(IXLCell target) { base.CopyTo(target); int lastRowNumber = target.Address.RowNumber + RowCount() - 1; if (lastRowNumber > XLHelper.MaxRowNumber) lastRowNumber = XLHelper.MaxRowNumber; int lastColumnNumber = target.Address.ColumnNumber + ColumnCount() - 1; if (lastColumnNumber > XLHelper.MaxColumnNumber) lastColumnNumber = XLHelper.MaxColumnNumber; return target.Worksheet.Range( target.Address.RowNumber, target.Address.ColumnNumber, lastRowNumber, lastColumnNumber) .Column(1); } public new IXLRangeColumn CopyTo(IXLRangeBase target) { base.CopyTo(target); int lastRowNumber = target.RangeAddress.FirstAddress.RowNumber + RowCount() - 1; if (lastRowNumber > XLHelper.MaxRowNumber) lastRowNumber = XLHelper.MaxRowNumber; int lastColumnNumber = target.RangeAddress.FirstAddress.ColumnNumber + ColumnCount() - 1; if (lastColumnNumber > XLHelper.MaxColumnNumber) lastColumnNumber = XLHelper.MaxColumnNumber; return target.Worksheet.Range( target.RangeAddress.FirstAddress.RowNumber, target.RangeAddress.FirstAddress.ColumnNumber, lastRowNumber, lastColumnNumber) .Column(1); } public IXLRangeColumn Column(int start, int end) { return Range(start, end).FirstColumn(); } public IXLRangeColumn Column(IXLCell start, IXLCell end) { return Column(start.Address.RowNumber, end.Address.RowNumber); } public IXLRangeColumns Columns(string columns) { var retVal = new XLRangeColumns(); var rowPairs = columns.Split(','); foreach (string trimmedPair in rowPairs.Select(pair => pair.Trim())) { string firstRow; string lastRow; if (trimmedPair.Contains(':') || trimmedPair.Contains('-')) { var rowRange = trimmedPair.Contains('-') ? trimmedPair.Replace('-', ':').Split(':') : trimmedPair.Split(':'); firstRow = rowRange[0]; lastRow = rowRange[1]; } else { firstRow = trimmedPair; lastRow = trimmedPair; } retVal.Add(Range(firstRow, lastRow).FirstColumn()); } return retVal; } public IXLRangeColumn SetDataType(XLCellValues dataType) { DataType = dataType; return this; } public IXLColumn WorksheetColumn() { return Worksheet.Column(RangeAddress.FirstAddress.ColumnNumber); } #endregion public XLCell Cell(int row) { return Cell(row, 1); } private void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted) { ShiftColumns(RangeAddress, range, columnsShifted); } private void WorksheetRangeShiftedRows(XLRange range, int rowsShifted) { ShiftRows(RangeAddress, range, rowsShifted); } public XLRange Range(int firstRow, int lastRow) { return Range(firstRow, 1, lastRow, 1); } public override XLRange Range(string rangeAddressStr) { string rangeAddressToUse; if (rangeAddressStr.Contains(':') || rangeAddressStr.Contains('-')) { if (rangeAddressStr.Contains('-')) rangeAddressStr = rangeAddressStr.Replace('-', ':'); var arrRange = rangeAddressStr.Split(':'); string firstPart = arrRange[0]; string secondPart = arrRange[1]; rangeAddressToUse = FixColumnAddress(firstPart) + ":" + FixColumnAddress(secondPart); } else rangeAddressToUse = FixColumnAddress(rangeAddressStr); var rangeAddress = new XLRangeAddress(Worksheet, rangeAddressToUse); return Range(rangeAddress); } public int CompareTo(XLRangeColumn otherColumn, IXLSortElements rowsToSort) { foreach (IXLSortElement e in rowsToSort) { var thisCell = Cell(e.ElementNumber); var otherCell = otherColumn.Cell(e.ElementNumber); int comparison; bool thisCellIsBlank = thisCell.IsEmpty(); bool otherCellIsBlank = otherCell.IsEmpty(); if (e.IgnoreBlanks && (thisCellIsBlank || otherCellIsBlank)) { if (thisCellIsBlank && otherCellIsBlank) comparison = 0; else { if (thisCellIsBlank) comparison = e.SortOrder == XLSortOrder.Ascending ? 1 : -1; else comparison = e.SortOrder == XLSortOrder.Ascending ? -1 : 1; } } else { if (thisCell.DataType == otherCell.DataType) { if (thisCell.DataType == XLCellValues.Text) { comparison = e.MatchCase ? thisCell.InnerText.CompareTo(otherCell.InnerText) : String.Compare(thisCell.InnerText, otherCell.InnerText, true); } else if (thisCell.DataType == XLCellValues.TimeSpan) comparison = thisCell.GetTimeSpan().CompareTo(otherCell.GetTimeSpan()); else comparison = Double.Parse(thisCell.InnerText, XLHelper.NumberStyle, XLHelper.ParseCulture).CompareTo(Double.Parse(otherCell.InnerText, XLHelper.NumberStyle, XLHelper.ParseCulture)); } else if (e.MatchCase) comparison = String.Compare(thisCell.GetString(), otherCell.GetString(), true); else comparison = thisCell.GetString().CompareTo(otherCell.GetString()); } if (comparison != 0) return e.SortOrder == XLSortOrder.Ascending ? comparison : comparison * -1; } return 0; } private XLRangeColumn ColumnShift(Int32 columnsToShift) { Int32 columnNumber = ColumnNumber() + columnsToShift; return Worksheet.Range( RangeAddress.FirstAddress.RowNumber, columnNumber, RangeAddress.LastAddress.RowNumber, columnNumber).FirstColumn(); } #region XLRangeColumn Left IXLRangeColumn IXLRangeColumn.ColumnLeft() { return ColumnLeft(); } IXLRangeColumn IXLRangeColumn.ColumnLeft(Int32 step) { return ColumnLeft(step); } public XLRangeColumn ColumnLeft() { return ColumnLeft(1); } public XLRangeColumn ColumnLeft(Int32 step) { return ColumnShift(step * -1); } #endregion #region XLRangeColumn Right IXLRangeColumn IXLRangeColumn.ColumnRight() { return ColumnRight(); } IXLRangeColumn IXLRangeColumn.ColumnRight(Int32 step) { return ColumnRight(step); } public XLRangeColumn ColumnRight() { return ColumnRight(1); } public XLRangeColumn ColumnRight(Int32 step) { return ColumnShift(step); } #endregion public IXLTable AsTable() { using (var asRange = AsRange()) return asRange.AsTable(); } public IXLTable AsTable(string name) { using (var asRange = AsRange()) return asRange.AsTable(name); } public IXLTable CreateTable() { using (var asRange = AsRange()) return asRange.CreateTable(); } public IXLTable CreateTable(string name) { using (var asRange = AsRange()) return asRange.CreateTable(name); } public new IXLRangeColumn Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats) { base.Clear(clearOptions); return this; } public IXLRangeColumn ColumnUsed(Boolean includeFormats = false) { return Column(FirstCellUsed(includeFormats), LastCellUsed(includeFormats)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsRequiredOptional { using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ExplicitModel. /// </summary> public static partial class ExplicitModelExtensions { /// <summary> /// Test explicitly required integer. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredIntegerParameter(this IExplicitModel operations, int bodyParameter) { return operations.PostRequiredIntegerParameterAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredIntegerParameterAsync(this IExplicitModel operations, int bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredIntegerParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalIntegerParameter(this IExplicitModel operations, int? bodyParameter = default(int?)) { operations.PostOptionalIntegerParameterAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalIntegerParameterAsync(this IExplicitModel operations, int? bodyParameter = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalIntegerParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required integer. Please put a valid int-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredIntegerProperty(this IExplicitModel operations, int value) { return operations.PostRequiredIntegerPropertyAsync(value).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put a valid int-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredIntegerPropertyAsync(this IExplicitModel operations, int value, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredIntegerPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put a valid int-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalIntegerProperty(this IExplicitModel operations, int? value = default(int?)) { operations.PostOptionalIntegerPropertyAsync(value).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a valid int-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalIntegerPropertyAsync(this IExplicitModel operations, int? value = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalIntegerPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required integer. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredIntegerHeader(this IExplicitModel operations, int headerParameter) { return operations.PostRequiredIntegerHeaderAsync(headerParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredIntegerHeaderAsync(this IExplicitModel operations, int headerParameter, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredIntegerHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static void PostOptionalIntegerHeader(this IExplicitModel operations, int? headerParameter = default(int?)) { operations.PostOptionalIntegerHeaderAsync(headerParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalIntegerHeaderAsync(this IExplicitModel operations, int? headerParameter = default(int?), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalIntegerHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required string. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredStringParameter(this IExplicitModel operations, string bodyParameter) { return operations.PostRequiredStringParameterAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredStringParameterAsync(this IExplicitModel operations, string bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredStringParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional string. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalStringParameter(this IExplicitModel operations, string bodyParameter = default(string)) { operations.PostOptionalStringParameterAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional string. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalStringParameterAsync(this IExplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalStringParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required string. Please put a valid string-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredStringProperty(this IExplicitModel operations, string value) { return operations.PostRequiredStringPropertyAsync(value).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put a valid string-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredStringPropertyAsync(this IExplicitModel operations, string value, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredStringPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put a valid string-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalStringProperty(this IExplicitModel operations, string value = default(string)) { operations.PostOptionalStringPropertyAsync(value).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a valid string-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalStringPropertyAsync(this IExplicitModel operations, string value = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalStringPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required string. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredStringHeader(this IExplicitModel operations, string headerParameter) { return operations.PostRequiredStringHeaderAsync(headerParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredStringHeaderAsync(this IExplicitModel operations, string headerParameter, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredStringHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional string. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalStringHeader(this IExplicitModel operations, string bodyParameter = default(string)) { operations.PostOptionalStringHeaderAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional string. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalStringHeaderAsync(this IExplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalStringHeaderWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required complex object. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredClassParameter(this IExplicitModel operations, Product bodyParameter) { return operations.PostRequiredClassParameterAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required complex object. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredClassParameterAsync(this IExplicitModel operations, Product bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional complex object. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalClassParameter(this IExplicitModel operations, Product bodyParameter = default(Product)) { operations.PostOptionalClassParameterAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional complex object. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalClassParameterAsync(this IExplicitModel operations, Product bodyParameter = default(Product), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required complex object. Please put a valid class-wrapper /// with 'value' = null and the client library should throw before the request /// is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredClassProperty(this IExplicitModel operations, Product value) { return operations.PostRequiredClassPropertyAsync(value).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required complex object. Please put a valid class-wrapper /// with 'value' = null and the client library should throw before the request /// is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredClassPropertyAsync(this IExplicitModel operations, Product value, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredClassPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional complex object. Please put a valid class-wrapper /// with 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalClassProperty(this IExplicitModel operations, Product value = default(Product)) { operations.PostOptionalClassPropertyAsync(value).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional complex object. Please put a valid class-wrapper /// with 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalClassPropertyAsync(this IExplicitModel operations, Product value = default(Product), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalClassPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required array. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredArrayParameter(this IExplicitModel operations, IList<string> bodyParameter) { return operations.PostRequiredArrayParameterAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredArrayParameterAsync(this IExplicitModel operations, IList<string> bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredArrayParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional array. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalArrayParameter(this IExplicitModel operations, IList<string> bodyParameter = default(IList<string>)) { operations.PostOptionalArrayParameterAsync(bodyParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional array. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalArrayParameterAsync(this IExplicitModel operations, IList<string> bodyParameter = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalArrayParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required array. Please put a valid array-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredArrayProperty(this IExplicitModel operations, IList<string> value) { return operations.PostRequiredArrayPropertyAsync(value).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put a valid array-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredArrayPropertyAsync(this IExplicitModel operations, IList<string> value, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredArrayPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional array. Please put a valid array-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalArrayProperty(this IExplicitModel operations, IList<string> value = default(IList<string>)) { operations.PostOptionalArrayPropertyAsync(value).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional array. Please put a valid array-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalArrayPropertyAsync(this IExplicitModel operations, IList<string> value = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalArrayPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Test explicitly required array. Please put a header 'headerParameter' =&gt; /// null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredArrayHeader(this IExplicitModel operations, IList<string> headerParameter) { return operations.PostRequiredArrayHeaderAsync(headerParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put a header 'headerParameter' =&gt; /// null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredArrayHeaderAsync(this IExplicitModel operations, IList<string> headerParameter, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostRequiredArrayHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static void PostOptionalArrayHeader(this IExplicitModel operations, IList<string> headerParameter = default(IList<string>)) { operations.PostOptionalArrayHeaderAsync(headerParameter).GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostOptionalArrayHeaderAsync(this IExplicitModel operations, IList<string> headerParameter = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.PostOptionalArrayHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
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 Crossroads.Gateway2.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using ModestTree; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Zenject { public static class TypeAnalyzer { static Dictionary<Type, ZenjectTypeInfo> _typeInfo = new Dictionary<Type, ZenjectTypeInfo>(); #if UNITY_EDITOR // We store this separately from ZenjectTypeInfo because this flag is needed for contract // types whereas ZenjectTypeInfo is only needed for types that are instantiated, and // we want to minimize the types that generate ZenjectTypeInfo for static Dictionary<Type, bool> _allowDuringValidation = new Dictionary<Type, bool>(); #endif public static ZenjectTypeInfo GetInfo<T>() { return GetInfo(typeof(T)); } public static bool ShouldAllowDuringValidation<T>() { return ShouldAllowDuringValidation(typeof(T)); } #if !UNITY_EDITOR public static bool ShouldAllowDuringValidation(Type type) { return false; } #else public static bool ShouldAllowDuringValidation(Type type) { bool shouldAllow; if (!_allowDuringValidation.TryGetValue(type, out shouldAllow)) { shouldAllow = ShouldAllowDuringValidationInternal(type); _allowDuringValidation.Add(type, shouldAllow); } return shouldAllow; } static bool ShouldAllowDuringValidationInternal(Type type) { // During validation, do not instantiate or inject anything except for // Installers, IValidatable's, or types marked with attribute ZenjectAllowDuringValidation // You would typically use ZenjectAllowDuringValidation attribute for data that you // inject into factories if (type.DerivesFrom<IInstaller>() || type.DerivesFrom<IValidatable>()) { return true; } #if !NOT_UNITY3D if (type.DerivesFrom<Context>()) { return true; } #endif return type.HasAttribute<ZenjectAllowDuringValidationAttribute>(); } #endif public static ZenjectTypeInfo GetInfo(Type type) { #if UNITY_EDITOR using (ProfileBlock.Start("Zenject Reflection")) #endif { Assert.That(!type.IsAbstract(), "Tried to analyze abstract type '{0}'. This is not currently allowed.", type); ZenjectTypeInfo info; #if ZEN_MULTITHREADING lock (_typeInfo) #endif { if (!_typeInfo.TryGetValue(type, out info)) { info = CreateTypeInfo(type); _typeInfo.Add(type, info); } } return info; } } static ZenjectTypeInfo CreateTypeInfo(Type type) { var constructor = GetInjectConstructor(type); return new ZenjectTypeInfo( type, GetPostInjectMethods(type), constructor, GetFieldInjectables(type).ToList(), GetPropertyInjectables(type).ToList(), GetConstructorInjectables(type, constructor).ToList()); } static IEnumerable<InjectableInfo> GetConstructorInjectables(Type parentType, ConstructorInfo constructorInfo) { if (constructorInfo == null) { return Enumerable.Empty<InjectableInfo>(); } return constructorInfo.GetParameters().Select( paramInfo => CreateInjectableInfoForParam(parentType, paramInfo)); } static InjectableInfo CreateInjectableInfoForParam( Type parentType, ParameterInfo paramInfo) { var injectAttributes = paramInfo.AllAttributes<InjectAttributeBase>().ToList(); Assert.That(injectAttributes.Count <= 1, "Found multiple 'Inject' attributes on type parameter '{0}' of type '{1}'. Parameter should only have one", paramInfo.Name, parentType); var injectAttr = injectAttributes.SingleOrDefault(); object identifier = null; bool isOptional = false; InjectSources sourceType = InjectSources.Any; if (injectAttr != null) { identifier = injectAttr.Id; isOptional = injectAttr.Optional; sourceType = injectAttr.Source; } bool isOptionalWithADefaultValue = (paramInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault; return new InjectableInfo( isOptionalWithADefaultValue || isOptional, identifier, paramInfo.Name, paramInfo.ParameterType, parentType, null, isOptionalWithADefaultValue ? paramInfo.DefaultValue : null, sourceType); } static List<PostInjectableInfo> GetPostInjectMethods(Type type) { // Note that unlike with fields and properties we use GetCustomAttributes // This is so that we can ignore inherited attributes, which is necessary // otherwise a base class method marked with [Inject] would cause all overridden // derived methods to be added as well var methods = type.GetAllInstanceMethods() .Where(x => x.GetCustomAttributes(typeof(InjectAttribute), false).Any()).ToList(); var heirarchyList = type.Yield().Concat(type.GetParentTypes()).Reverse().ToList(); // Order by base classes first // This is how constructors work so it makes more sense var values = methods.OrderBy(x => heirarchyList.IndexOf(x.DeclaringType)); var postInjectInfos = new List<PostInjectableInfo>(); foreach (var methodInfo in values) { var paramsInfo = methodInfo.GetParameters(); var injectAttr = methodInfo.AllAttributes<InjectAttribute>().Single(); Assert.That(!injectAttr.Optional && injectAttr.Id == null && injectAttr.Source == InjectSources.Any, "Parameters of InjectAttribute do not apply to constructors and methods"); postInjectInfos.Add( new PostInjectableInfo( methodInfo, paramsInfo.Select(paramInfo => CreateInjectableInfoForParam(type, paramInfo)).ToList())); } return postInjectInfos; } static IEnumerable<InjectableInfo> GetPropertyInjectables(Type type) { var propInfos = type.GetAllInstanceProperties() .Where(x => x.HasAttribute(typeof(InjectAttributeBase))); foreach (var propInfo in propInfos) { yield return CreateForMember(propInfo, type); } } static IEnumerable<InjectableInfo> GetFieldInjectables(Type type) { var fieldInfos = type.GetAllInstanceFields() .Where(x => x.HasAttribute(typeof(InjectAttributeBase))); foreach (var fieldInfo in fieldInfos) { yield return CreateForMember(fieldInfo, type); } } #if !(UNITY_WSA && ENABLE_DOTNET) || UNITY_EDITOR private static IEnumerable<FieldInfo> GetAllFields(Type t, BindingFlags flags) { if (t == null) { return Enumerable.Empty<FieldInfo>(); } return t.GetFields(flags).Concat(GetAllFields(t.BaseType, flags)).Distinct(); } private static Action<object, object> GetOnlyPropertySetter( Type parentType, string propertyName) { Assert.That(parentType != null); Assert.That(!string.IsNullOrEmpty(propertyName)); var allFields = GetAllFields( parentType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).ToList(); var writeableFields = allFields.Where(f => f.Name == string.Format("<{0}>k__BackingField", propertyName)).ToList(); if (!writeableFields.Any()) { throw new ZenjectException(string.Format( "Can't find backing field for get only property {0} on {1}.\r\n{2}", propertyName, parentType.FullName, string.Join(";", allFields.Select(f => f.Name).ToArray()))); } return (injectable, value) => writeableFields.ForEach(f => f.SetValue(injectable, value)); } #endif static InjectableInfo CreateForMember(MemberInfo memInfo, Type parentType) { var injectAttributes = memInfo.AllAttributes<InjectAttributeBase>().ToList(); Assert.That(injectAttributes.Count <= 1, "Found multiple 'Inject' attributes on type field '{0}' of type '{1}'. Field should only container one Inject attribute", memInfo.Name, parentType); var injectAttr = injectAttributes.SingleOrDefault(); object identifier = null; bool isOptional = false; InjectSources sourceType = InjectSources.Any; if (injectAttr != null) { identifier = injectAttr.Id; isOptional = injectAttr.Optional; sourceType = injectAttr.Source; } Type memberType; Action<object, object> setter; if (memInfo is FieldInfo) { var fieldInfo = (FieldInfo)memInfo; setter = ((object injectable, object value) => fieldInfo.SetValue(injectable, value)); memberType = fieldInfo.FieldType; } else { Assert.That(memInfo is PropertyInfo); var propInfo = (PropertyInfo)memInfo; memberType = propInfo.PropertyType; #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null)); #else if (propInfo.CanWrite) { setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null)); } else { setter = GetOnlyPropertySetter(parentType, propInfo.Name); } #endif } return new InjectableInfo( isOptional, identifier, memInfo.Name, memberType, parentType, setter, null, sourceType); } static ConstructorInfo GetInjectConstructor(Type parentType) { var constructors = parentType.Constructors(); #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR // WP8 generates a dummy constructor with signature (internal Classname(UIntPtr dummy)) // So just ignore that constructors = constructors.Where(c => !IsWp8GeneratedConstructor(c)).ToArray(); #endif if (constructors.IsEmpty()) { return null; } if (constructors.HasMoreThan(1)) { var explicitConstructor = (from c in constructors where c.HasAttribute<InjectAttribute>() select c).SingleOrDefault(); if (explicitConstructor != null) { return explicitConstructor; } // If there is only one public constructor then use that // This makes decent sense but is also necessary on WSA sometimes since the WSA generated // constructor can sometimes be private with zero parameters var singlePublicConstructor = constructors.Where(x => !x.IsPrivate).OnlyOrDefault(); if (singlePublicConstructor != null) { return singlePublicConstructor; } // Choose the one with the least amount of arguments // This might result in some non obvious errors like null reference exceptions // but is probably the best trade-off since it allows zenject to be more compatible // with libraries that don't depend on zenject at all // Discussion here - https://github.com/modesttree/Zenject/issues/416 return constructors.OrderBy(x => x.GetParameters().Count()).First(); } return constructors[0]; } #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR static bool IsWp8GeneratedConstructor(ConstructorInfo c) { ParameterInfo[] args = c.GetParameters(); if (args.Length == 1) { return args[0].ParameterType == typeof(UIntPtr) && (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy"); } if (args.Length == 2) { return args[0].ParameterType == typeof(UIntPtr) && args[1].ParameterType == typeof(Int64*) && (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy") && (string.IsNullOrEmpty(args[1].Name) || args[1].Name == "dummy"); } return false; } #endif } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Examples.SimpleModule { public class MyNpcCharacter : IClientAPI { private uint movementFlag = 0; private short flyState = 0; private Quaternion bodyDirection = Quaternion.Identity; private short count = 0; private short frame = 0; private Scene m_scene; // disable warning: public events, part of the public API #pragma warning disable 67 public event Action<IClientAPI> OnLogout; public event ObjectPermissions OnObjectPermissions; public event MoneyTransferRequest OnMoneyTransferRequest; public event ParcelBuy OnParcelBuy; public event Action<IClientAPI> OnConnectionClosed; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event SetAlwaysRun OnSetAlwaysRun; public event DeRezObject OnDeRezObject; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall2 OnRequestWearables; public event GenericCall2 OnCompleteMovementToRegion; public event UpdateAgent OnAgentUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event ViewerEffectEventHandler OnViewerEffect; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event ObjectRequest OnObjectRequest; public event ObjectSelect OnObjectSelect; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<UUID> OnRemoveAvatar; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event GenericMessage OnGenericMessage; public event UUIDNameRequest OnNameFromUUIDRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event ObjectDeselect OnObjectDeselect; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event EstateChangeInfo OnEstateChangeInfo; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event AgentSit OnUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event UpdateVector OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event ActivateGesture OnActivateGesture; public event DeactivateGesture OnDeactivateGesture; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event AvatarInterestUpdate OnAvatarInterestUpdate; public event PlacesQuery OnPlacesQuery; #pragma warning restore 67 private UUID myID = UUID.Random(); public MyNpcCharacter(Scene scene) { // startPos = new Vector3(128, (float)(Util.RandomClass.NextDouble()*100), 2); m_scene = scene; m_scene.EventManager.OnFrame += Update; } private Vector3 startPos = new Vector3(128, 128, 30); public virtual Vector3 StartPos { get { return startPos; } set { } } public virtual UUID AgentId { get { return myID; } } public UUID SessionId { get { return UUID.Zero; } } public UUID SecureSessionId { get { return UUID.Zero; } } public virtual string FirstName { get { return "Only"; } } private string lastName = "Today" + Util.RandomClass.Next(1, 1000); public virtual string LastName { get { return lastName; } } public virtual String Name { get { return FirstName + LastName; } } public bool IsActive { get { return true; } set { } } public UUID ActiveGroupId { get { return UUID.Zero; } } public string ActiveGroupName { get { return String.Empty; } } public ulong ActiveGroupPowers { get { return 0; } } public bool IsGroupMember(UUID groupID) { return false; } public ulong GetGroupPowers(UUID groupID) { return 0; } public virtual int NextAnimationSequenceNumber { get { return 1; } } public IScene Scene { get { return m_scene; } } public bool SendLogoutPacketWhenClosing { set { } } public virtual void ActivateGesture(UUID assetId, UUID gestureId) { } public virtual void SendWearables(AvatarWearable[] wearables, int serial) { } public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { } public virtual void Kick(string message) { } public virtual void SendStartPingCheck(byte seq) { } public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public virtual void SendKillObject(ulong regionHandle, uint localID) { } public virtual void SetChildAgentThrottle(byte[] throttle) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } public virtual void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { } public virtual void SendChatMessage(byte[] message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { } public void SendInstantMessage(GridInstantMessage im) { } public void SendGenericMessage(string method, List<string> message) { } public virtual void SendLayerData(float[] map) { } public virtual void SendLayerData(int px, int py, float[] map) { } public virtual void SendLayerData(int px, int py, float[] map, bool track) { } public virtual void SendWindData(Vector2[] windSpeeds) { } public virtual void SendCloudData(float[] cloudCover) { } public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { } public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { } public virtual AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { } public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { } public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { } public virtual void SendTeleportFailed(string reason) { } public virtual void SendTeleportLocationStart() { } public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) { } public virtual void SendPayPrice(UUID objectID, int[] payPrice) { } public virtual void SendAvatarData(ulong regionHandle, string firstName, string lastName, string grouptitle, UUID avatarID, uint avatarLocalID, Vector3 Pos, byte[] textureEntry, uint parentID, Quaternion rotation) { } public virtual void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position, Vector3 velocity, Quaternion rotation, UUID agentid) { } public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { } public virtual void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID) { } public virtual void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { } public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, Vector3 pos, Vector3 vel, Vector3 acc, Quaternion rotation, Vector3 rvel, uint flags, UUID objectID, UUID ownerID, string text, byte[] color, uint parentID, byte[] particleSystem, byte clickAction, byte material) { } public virtual void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, Vector3 pos, Vector3 vel, Vector3 acc, Quaternion rotation, Vector3 rvel, uint flags, UUID objectID, UUID ownerID, string text, byte[] color, uint parentID, byte[] particleSystem, byte clickAction, byte material, byte[] textureanimation, bool attachment, uint AttachmentPoint, UUID AssetId, UUID SoundId, double SoundVolume, byte SoundFlags, double SoundRadius) { } public virtual void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position, Quaternion rotation, Vector3 velocity, Vector3 rotationalvelocity, byte state, UUID AssetId, UUID ownerID, int attachPoint) { } public void FlushPrimUpdates() { } public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems) { } public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { } public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID) { } public virtual void SendRemoveInventoryItem(UUID itemID) { } public virtual void SendBulkUpdateInventory(InventoryNodeBase node) { } public UUID GetDefaultAnimation(string name) { return UUID.Zero; } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { } public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { } public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data) { } public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public virtual void SendNameReply(UUID profileId, string firstname, string lastname) { } public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { } public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { } public void SendAttachedSoundGainChange(UUID objectID, float gain) { } public void SendAlertMessage(string message) { } public void SendAgentAlertMessage(string message, bool modal) { } public void SendSystemAlertMessage(string message) { } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { } public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { if (OnRegionHandShakeReply != null) { OnRegionHandShakeReply(this); } if (OnCompleteMovementToRegion != null) { OnCompleteMovementToRegion(); } } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { } public void SendImageNotFound(UUID imageid) { } public void SendShutdownConnectionNotice() { } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType,int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) { } public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) { } public void SendAgentOffline(UUID[] agentIDs) { } public void SendAgentOnline(UUID[] agentIDs) { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } private void Update() { frame++; if (frame > 20) { frame = 0; if (OnAgentUpdate != null) { AgentUpdateArgs pack = new AgentUpdateArgs(); pack.ControlFlags = movementFlag; pack.BodyRotation = bodyDirection; OnAgentUpdate(this, pack); } if (flyState == 0) { movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY | (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG; flyState = 1; } else if (flyState == 1) { movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY | (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS; flyState = 2; } else { movementFlag = (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY; flyState = 0; } if (count >= 10) { if (OnChatFromClient != null) { OSChatMessage args = new OSChatMessage(); args.Message = "Hey You! Get out of my Home. This is my Region"; args.Channel = 0; args.From = FirstName + " " + LastName; args.Scene = m_scene; args.Position = new Vector3(128, 128, 26); args.Sender = this; args.Type = ChatTypeEnum.Shout; OnChatFromClient(this, args); } count = -1; } count++; } } public bool AddMoney(int debit) { return false; } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase) { } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { } public void SetDebugPacketLevel(int newDebug) { } public void InPacket(object NewPack) { } public void ProcessInPacket(Packet NewPack) { } public void Close(bool ShutdownCircuit) { } public void Start() { } public void Stop() { } private uint m_circuitCode; public uint CircuitCode { get { return m_circuitCode; } set { m_circuitCode = value; } } public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message) { } public void SendLogoutPacket() { } public void Terminate() { } public EndPoint GetClientEP() { return null; } public ClientInfo GetClientInfo() { return null; } public void SetClientInfo(ClientInfo info) { } public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateManagersList(UUID invoice, UUID[] EstateManagers, uint estateID) { } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(UUID covenant) { } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { } public void SendAsset(AssetRequestToClient req) { } public void SendTexture(AssetBase TextureAsset) { } public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters) { } public void SendClearFollowCamProperties (UUID objectID) { } public void SendRegionHandle (UUID regoinID, ulong handle) { } public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return string.Empty; } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void KillEndDone() { } public void SendEventInfoReply (EventData info) { } public void SendOfferCallingCard (UUID destID, UUID transactionID) { } public void SendAcceptCallingCard (UUID transactionID) { } public void SendDeclineCallingCard (UUID transactionID) { } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { } public void SendJoinGroupReply(UUID groupID, bool success) { } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss) { } public void SendLeaveGroupReply(UUID groupID, bool success) { } public void SendTerminateFriend(UUID exFriendID) { } #region IClientAPI Members public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { return true; } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(UUID groupID) { } public void SendAvatarNotesReply(UUID targetID, string text) { } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendCreateGroupReply(UUID groupID, bool success, string message) { } public void RefreshGroupMembership() { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal class AttributeNamedParameterCompletionProvider : AbstractCompletionProvider { private const string EqualsString = "="; private const string SpaceEqualsString = " ="; private const string ColonString = ":"; public override bool IsCommitCharacter(CompletionItem completionItem, char ch, string textTypedSoFar) { return CompletionUtilities.IsCommitCharacter(completionItem, ch, textTypedSoFar); } public override bool SendEnterThroughToEditor(CompletionItem completionItem, string textTypedSoFar) { return CompletionUtilities.SendEnterThroughToEditor(completionItem, textTypedSoFar); } public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options) { return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); } public override TextChange GetTextChange(CompletionItem selectedItem, char? ch = null, string textTypedSoFar = null) { var displayText = selectedItem.DisplayText; if (ch != null) { // If user types a space, do not complete the " =" (space and equals) at the end of a named parameter. The // typed space character will be passed through to the editor, and they can then type the '='. if (ch == ' ' && displayText.EndsWith(SpaceEqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.FilterSpan, displayText.Remove(displayText.Length - SpaceEqualsString.Length)); } // If the user types '=', do not complete the '=' at the end of the named parameter because the typed '=' // will be passed through to the editor. if (ch == '=' && displayText.EndsWith(EqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.FilterSpan, displayText.Remove(displayText.Length - EqualsString.Length)); } // If the user types ':', do not complete the ':' at the end of the named parameter because the typed ':' // will be passed through to the editor. if (ch == ':' && displayText.EndsWith(ColonString, StringComparison.Ordinal)) { return new TextChange(selectedItem.FilterSpan, displayText.Remove(displayText.Length - ColonString.Length)); } } return new TextChange(selectedItem.FilterSpan, displayText); } protected override async Task<bool> IsExclusiveAsync(Document document, int caretPosition, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { var syntaxTree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTree.FindTokenOnLeftOfPosition(caretPosition, cancellationToken) .GetPreviousTokenIfTouchingWord(caretPosition); return IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token); } private bool IsAfterNameColonArgument(SyntaxToken token) { var argumentList = token.Parent as AttributeArgumentListSyntax; if (token.Kind() == SyntaxKind.CommaToken && argumentList != null) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameColon != null) { return true; } } } } return false; } private bool IsAfterNameEqualsArgument(SyntaxToken token) { var argumentList = token.Parent as AttributeArgumentListSyntax; if (token.Kind() == SyntaxKind.CommaToken && argumentList != null) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameEquals != null) { return true; } } } } return false; } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync( Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { var syntaxTree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return null; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() != SyntaxKind.OpenParenToken && token.Kind() != SyntaxKind.CommaToken) { return null; } var attributeArgumentList = token.Parent as AttributeArgumentListSyntax; var attributeSyntax = token.Parent.Parent as AttributeSyntax; if (attributeSyntax == null || attributeArgumentList == null) { return null; } // We actually want to collect two sets of named parameters to present the user. The // normal named parameters that come from the attribute constructors. These will be // presented like "foo:". And also the named parameters that come from the writable // fields/properties in the attribute. These will be presented like "bar =". var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position); var workspace = document.Project.Solution.Workspace; var semanticModel = await document.GetCSharpSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false); var nameColonItems = await GetNameColonItemsAsync(workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false); var nameEqualsItems = await GetNameEqualsItemsAsync(workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false); // If we're after a name= parameter, then we only want to show name= parameters. if (IsAfterNameEqualsArgument(token)) { return nameEqualsItems; } return nameColonItems.Concat(nameEqualsItems); } private async Task<IEnumerable<CompletionItem>> GetNameEqualsItemsAsync(Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters, CancellationToken cancellationToken) { var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, position, attributeSyntax, cancellationToken); var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name)); var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); return from p in attributeNamedParameters where !existingNamedParameters.Contains(p.Name) select new CSharpCompletionItem( workspace, this, p.Name.ToIdentifierToken().ToString() + SpaceEqualsString, CompletionUtilities.GetTextChangeSpan(text, position), CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p), p.GetGlyph(), sortText: p.Name); } private async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync( Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters, CancellationToken cancellationToken) { var parameterLists = GetParameterLists(semanticModel, position, attributeSyntax, cancellationToken); parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters)); var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); return from pl in parameterLists from p in pl where !existingNamedParameters.Contains(p.Name) select new CSharpCompletionItem( workspace, this, p.Name.ToIdentifierToken().ToString() + ColonString, CompletionUtilities.GetTextChangeSpan(text, position), CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p), p.GetGlyph(), sortText: p.Name); } private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters) { return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty(); } private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position) { var existingArguments1 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameColon != null) .Select(a => a.NameColon.Name.Identifier.ValueText); var existingArguments2 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameEquals != null) .Select(a => a.NameEquals.Name.Identifier.ValueText); return existingArguments1.Concat(existingArguments2).ToSet(); } private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; if (within != null && attributeType != null) { return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within)) .Select(c => c.Parameters); } return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>(); } private IEnumerable<ISymbol> GetAttributeNamedParameters( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within); } } }
//----------------------------------------------------------------------------- // // <copyright file="SecureEnvironment.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: Secure Environment class is a starting point for Managed RM APIs // It provides basic services of enumerating User Certificates, Initializing Environment // // History: // 06/01/2005: IgorBel : Initial Implementation // //----------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Windows; using MS.Internal.Security.RightsManagement; using SecurityHelper=MS.Internal.WindowsBase.SecurityHelper; using MS.Internal; using System.Security.Permissions; using SR=MS.Internal.WindowsBase.SR; using SRID=MS.Internal.WindowsBase.SRID; namespace System.Security.RightsManagement { /// <summary> /// This class represent a client session, which used in activation, binding and other function calls. /// </summary> /// <SecurityNote> /// Critical: This class expose access to methods that eventually do one or more of the the following /// 1. call into unmanaged code /// 2. affects state/data that will eventually cross over unmanaged code boundary /// 3. Return some RM related information which is considered private /// /// TreatAsSafe: This attrbiute automatically applied to all public entry points. All the public entry points have /// Demands for RightsManagementPermission at entry to counter the possible attacks that do /// not lead to the unamanged code directly(which is protected by another Demand there) but rather leave /// some status/data behind which eventually might cross the unamanaged boundary. /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] public class SecureEnvironment : IDisposable { /// <summary> /// This static Method builds a new instance of a SecureEnvironment for a given user that is already /// activated. If this method called with a user that isn't activated, and exception will be thrown. /// The user that is passed into the function must have a well defined authentication type /// AuthenticationType.Windows or AuthenticationType.Passport, all other Authentication /// types(AuthenticationType.WindowsPassport or AuthenticationType.Internal) are not allowed. /// </summary> public static SecureEnvironment Create(string applicationManifest, ContentUser user) { SecurityHelper.DemandRightsManagementPermission(); return CriticalCreate(applicationManifest, user); } /// <summary> /// This static method activates a user and creates a new instance of SecureEnvironment. /// The authentication type determines the type of user identity that will be activated. /// If Permanent Windows activation is requested then the default currently logged on /// Windows Account identity will be activated. If Temporary Windows activation requested /// then user will be prompted for Windows Domain credentials through a dialog, and the /// user identified through those credentials will be activated. /// In case of Passport authentication, a Passport authentication dialog will always /// appear regardless of temporary or permanent activation mode. The user that authenticatd /// through that Passport Authentication dialog will be activated. /// Regardless of Windows or Passport Authentication, all Temporary created activation will be /// destroyed when SecureEnvironment instance is Disposed or Finalized. /// </summary> public static SecureEnvironment Create(string applicationManifest, AuthenticationType authentication, UserActivationMode userActivationMode) { SecurityHelper.DemandRightsManagementPermission(); return CriticalCreate(applicationManifest, authentication, userActivationMode); } /// <summary> /// This property verifies whether the current machine was prepared for consuming and producing RM protected content. /// If property returns true it could be used as an indication that Init function call will not result in a network transaction. /// </summary> public static bool IsUserActivated(ContentUser user) { SecurityHelper.DemandRightsManagementPermission(); if (user == null) { throw new ArgumentNullException("user"); } // we only let specifically identified users to be used here if ((user.AuthenticationType != AuthenticationType.Windows) && (user.AuthenticationType != AuthenticationType.Passport)) { throw new ArgumentOutOfRangeException("user", SR.Get(SRID.OnlyPassportOrWindowsAuthenticatedUsersAreAllowed)); } using (ClientSession userClientSession = new ClientSession(user)) { // if machine activation is not present we can return false right away return (userClientSession.IsMachineActivated() && userClientSession.IsUserActivated()); } } /// <summary> /// Removes activation for a given user. User must have Windows or Passport authnetication /// </summary> public static void RemoveActivatedUser(ContentUser user) { SecurityHelper.DemandRightsManagementPermission(); if (user == null) { throw new ArgumentNullException("user"); } // we only let specifically identifyed users to be used here if ((user.AuthenticationType != AuthenticationType.Windows) && (user.AuthenticationType != AuthenticationType.Passport)) { throw new ArgumentOutOfRangeException("user", SR.Get(SRID.OnlyPassportOrWindowsAuthenticatedUsersAreAllowed)); } // Generic client session to enumerate user certificates using (ClientSession userClientSession = new ClientSession(user)) { // Remove Licensor certificastes first List<string> userClientLicensorCertificateIds = userClientSession.EnumerateUsersCertificateIds(user, EnumerateLicenseFlags.ClientLicensor); // and now we can remove certificates that have been enumerated foreach(string licenseId in userClientLicensorCertificateIds) { userClientSession.DeleteLicense(licenseId); } // Remove User's identity certificastes second List<string> userGroupIdentityCertificateIds = userClientSession.EnumerateUsersCertificateIds(user, EnumerateLicenseFlags.GroupIdentity); // and now we can remove certificates that have been enumerated foreach(string licenseId in userGroupIdentityCertificateIds) { userClientSession.DeleteLicense(licenseId); } } } /// <summary> /// This function returns a read only collection of the activated users. /// </summary> static public ReadOnlyCollection<ContentUser> GetActivatedUsers() { SecurityHelper.DemandRightsManagementPermission(); //build user with the default authentication type and a default name // neither name not authentication type is important in this case //ContentUser tempUser = new ContentUser(_defaultUserName, AuthenticationType.Windows); // Generic client session to enumerate user certificates using(ClientSession genericClientSession = ClientSession.DefaultUserClientSession(AuthenticationType.Windows)) { List<ContentUser> userList = new List<ContentUser>(); // if machine activation is not present we can return empty list right away if (genericClientSession.IsMachineActivated()) { int index =0; while(true) { // we get a string which can be parsed to get the ID and type string userCertificate = genericClientSession.EnumerateLicense(EnumerateLicenseFlags.GroupIdentity, index); if (userCertificate == null) break; // we need to parse the information out of the string ContentUser user = ClientSession.ExtractUserFromCertificateChain(userCertificate); // User specific client session to check it's status using(ClientSession userClientSession = new ClientSession(user)) { if (userClientSession.IsUserActivated()) { userList.Add(user); } } index ++; } } return new ReadOnlyCollection<ContentUser>(userList); } } /// <summary> /// This method is responsible for tearing down secure environment that was built as a result of Init call. /// </summary> public void Dispose() { SecurityHelper.DemandRightsManagementPermission(); Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Read only property which returns the User provided in the constructor. /// </summary> public ContentUser User { get { SecurityHelper.DemandRightsManagementPermission(); CheckDisposed(); return _user; } } /// <summary> /// Read only property which returns the Application Manifest provided in the constructor. /// </summary> public string ApplicationManifest { get { SecurityHelper.DemandRightsManagementPermission(); CheckDisposed(); return _applicationManifest; } } /// <summary> /// Dispose(bool) /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { try { if (disposing && (_clientSession != null)) { _clientSession.Dispose(); } } finally { _clientSession = null; } } internal ClientSession ClientSession { get { Invariant.Assert(_clientSession != null); return _clientSession; } } /// <summary> /// This static Method builds a new instance of a secure environment for a given user that is assumed to be already activated. /// client Application can use GetActivatedUsers property to enumerate Activated users. /// </summary> private static SecureEnvironment CriticalCreate(string applicationManifest, ContentUser user) { if (applicationManifest == null) { throw new ArgumentNullException("applicationManifest"); } if (user == null) { throw new ArgumentNullException("user"); } // we only let specifically identifyed users to be used here if ((user.AuthenticationType != AuthenticationType.Windows) && (user.AuthenticationType != AuthenticationType.Passport)) { throw new ArgumentOutOfRangeException("user"); } if (!IsUserActivated(user)) { throw new RightsManagementException(RightsManagementFailureCode.NeedsGroupIdentityActivation); } ClientSession clientSession = new ClientSession(user); try { clientSession.BuildSecureEnvironment(applicationManifest); return new SecureEnvironment(applicationManifest, user, clientSession); } catch { clientSession.Dispose(); throw; } } private static SecureEnvironment CriticalCreate( string applicationManifest, AuthenticationType authentication, UserActivationMode userActivationMode) { if (applicationManifest == null) { throw new ArgumentNullException("applicationManifest"); } if ((authentication != AuthenticationType.Windows) && (authentication != AuthenticationType.Passport)) { throw new ArgumentOutOfRangeException("authentication"); } if ((userActivationMode != UserActivationMode.Permanent) && (userActivationMode != UserActivationMode.Temporary)) { throw new ArgumentOutOfRangeException("userActivationMode"); } //build user with the given authnetication type and a default name // only authentication type is critical in this case ContentUser user; using (ClientSession tempClientSession = ClientSession.DefaultUserClientSession(authentication)) { //Activate Machine if neccessary if (!tempClientSession.IsMachineActivated()) { // activate Machine tempClientSession.ActivateMachine(authentication); } //Activate User (we will force start activation at this point) // at this point we should have a real user name user = tempClientSession.ActivateUser(authentication, userActivationMode); } Debug.Assert(IsUserActivated(user)); ClientSession clientSession = new ClientSession(user, userActivationMode); try { try { // make sure we have a Client Licensor Certificate clientSession.AcquireClientLicensorCertificate(); } catch (RightsManagementException) { // In case of the RightsMnaagement exception we are willing to proceed // as ClientLicensorCertificate only required for publishing not for consumption // and therefore it is optional to have one. } clientSession.BuildSecureEnvironment(applicationManifest); return new SecureEnvironment(applicationManifest, user, clientSession); } catch { clientSession.Dispose(); throw; } } /// <summary> /// Private Constructor for the SecureEnvironment. /// </summary> private SecureEnvironment(string applicationManifest, ContentUser user, ClientSession clientSession) { Invariant.Assert(applicationManifest != null); Invariant.Assert(user != null); Invariant.Assert(clientSession != null); _user = user; _applicationManifest = applicationManifest; _clientSession = clientSession; } /// <summary> /// Call this before accepting any API call /// </summary> private void CheckDisposed() { if (_clientSession == null) throw new ObjectDisposedException("SecureEnvironment"); } private ContentUser _user; private string _applicationManifest; private ClientSession _clientSession; // if null we are disposed } }
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors using System; using System.Linq; using Generator.Documentation.CSharp; using Generator.Enums; using Generator.Enums.Encoder; using Generator.IO; namespace Generator.Encoder.CSharp { [Generator(TargetLanguage.CSharp)] sealed class CSharpInstrCreateGen : InstrCreateGen { readonly IdentifierConverter idConverter; readonly CSharpDocCommentWriter docWriter; readonly CSharpDeprecatedWriter deprecatedWriter; public CSharpInstrCreateGen(GeneratorContext generatorContext) : base(generatorContext.Types) { idConverter = CSharpIdentifierConverter.Create(); docWriter = new CSharpDocCommentWriter(idConverter); deprecatedWriter = new CSharpDeprecatedWriter(idConverter); } protected override (TargetLanguage language, string id, string filename) GetFileInfo() => (TargetLanguage.CSharp, "Create", CSharpConstants.GetFilename(genTypes, CSharpConstants.IcedNamespace, "Instruction.Create.cs")); void WriteDocs(FileWriter writer, CreateMethod method) { const string typeName = "Instruction"; docWriter.BeginWrite(writer); docWriter.WriteLine(writer, "<summary>"); foreach (var doc in method.Docs) docWriter.WriteDocLine(writer, doc, typeName); docWriter.WriteLine(writer, "</summary>"); for (int i = 0; i < method.Args.Count; i++) { var arg = method.Args[i]; docWriter.Write($"<param name=\"{idConverter.Argument(arg.Name)}\">"); docWriter.WriteDoc(writer, arg.Doc, typeName); docWriter.WriteLine(writer, "</param>"); } docWriter.EndWrite(writer); } void WriteMethodDeclArgs(FileWriter writer, CreateMethod method) { bool comma = false; foreach (var arg in method.Args) { if (comma) writer.Write(", "); comma = true; switch (arg.Type) { case MethodArgType.Code: writer.Write(codeType.Name(idConverter)); break; case MethodArgType.Register: writer.Write(genTypes[TypeIds.Register].Name(idConverter)); break; case MethodArgType.RepPrefixKind: writer.Write(genTypes[TypeIds.RepPrefixKind].Name(idConverter)); break; case MethodArgType.Memory: writer.Write("in MemoryOperand"); break; case MethodArgType.UInt8: writer.Write("byte"); break; case MethodArgType.UInt16: writer.Write("ushort"); break; case MethodArgType.PreferedInt32: case MethodArgType.Int32: case MethodArgType.ArrayIndex: case MethodArgType.ArrayLength: writer.Write("int"); break; case MethodArgType.UInt32: writer.Write("uint"); break; case MethodArgType.Int64: writer.Write("long"); break; case MethodArgType.UInt64: writer.Write("ulong"); break; case MethodArgType.ByteArray: writer.Write("byte[]"); break; case MethodArgType.WordArray: writer.Write("ushort[]"); break; case MethodArgType.DwordArray: writer.Write("uint[]"); break; case MethodArgType.QwordArray: writer.Write("ulong[]"); break; case MethodArgType.ByteSlice: writer.Write("ReadOnlySpan<byte>"); break; case MethodArgType.WordSlice: writer.Write("ReadOnlySpan<ushort>"); break; case MethodArgType.DwordSlice: writer.Write("ReadOnlySpan<uint>"); break; case MethodArgType.QwordSlice: writer.Write("ReadOnlySpan<ulong>"); break; case MethodArgType.BytePtr: writer.Write("byte*"); break; case MethodArgType.WordPtr: writer.Write("ushort*"); break; case MethodArgType.DwordPtr: writer.Write("uint*"); break; case MethodArgType.QwordPtr: writer.Write("ulong*"); break; default: throw new InvalidOperationException(); } writer.Write(" "); writer.Write(idConverter.Argument(arg.Name)); switch (arg.DefaultValue) { case EnumValue enumValue: writer.Write($" = {enumValue.DeclaringType.Name(idConverter)}.{enumValue.Name(idConverter)}"); break; case null: break; default: throw new InvalidOperationException(); } } } void WriteInitializeInstruction(FileWriter writer, CreateMethod method) { writer.WriteLine("Instruction instruction = default;"); var args = method.Args; if (args.Count == 0 || args[0].Type != MethodArgType.Code) throw new InvalidOperationException(); var codeName = idConverter.Argument(args[0].Name); writer.WriteLine($"instruction.InternalCode = {codeName};"); } void WriteInitializeInstruction(FileWriter writer, EnumValue code) { writer.WriteLine("Instruction instruction = default;"); writer.WriteLine($"instruction.InternalCode = {code.DeclaringType.Name(idConverter)}.{code.Name(idConverter)};"); } static void WriteMethodFooter(FileWriter writer, int args) { writer.WriteLine(); writer.WriteLine($"Debug.Assert(instruction.OpCount == {args});"); writer.WriteLine("return instruction;"); } protected override void GenCreate(FileWriter writer, CreateMethod method, InstructionGroup group) { WriteDocs(writer, method); writer.Write("public static Instruction Create("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { WriteInitializeInstruction(writer, method); var args = method.Args; var codeName = idConverter.Argument(args[0].Name); var opKindStr = genTypes[TypeIds.OpKind].Name(idConverter); var registerStr = genTypes[TypeIds.OpKind][nameof(OpKind.Register)].Name(idConverter); var memoryStr = genTypes[TypeIds.OpKind][nameof(OpKind.Memory)].Name(idConverter); var immediate64Str = genTypes[TypeIds.OpKind][nameof(OpKind.Immediate64)].Name(idConverter); var immediate8_2ndStr = genTypes[TypeIds.OpKind][nameof(OpKind.Immediate8_2nd)].Name(idConverter); bool multipleInts = args.Where(a => a.Type == MethodArgType.Int32 || a.Type == MethodArgType.UInt32).Count() > 1; for (int i = 1; i < args.Count; i++) { int op = i - 1; var arg = args[i]; writer.WriteLine(); switch (arg.Type) { case MethodArgType.Register: writer.WriteLine($"Static.Assert({opKindStr}.{registerStr} == 0 ? 0 : -1);"); writer.WriteLine($"//instruction.InternalOp{op}Kind = {opKindStr}.{registerStr};"); writer.WriteLine($"instruction.InternalOp{op}Register = {idConverter.Argument(arg.Name)};"); break; case MethodArgType.Memory: writer.WriteLine($"instruction.InternalOp{op}Kind = {opKindStr}.{memoryStr};"); writer.WriteLine($"InitMemoryOperand(ref instruction, {idConverter.Argument(arg.Name)});"); break; case MethodArgType.Int32: case MethodArgType.UInt32: case MethodArgType.Int64: case MethodArgType.UInt64: var methodName = arg.Type == MethodArgType.Int32 || arg.Type == MethodArgType.Int64 ? "InitializeSignedImmediate" : "InitializeUnsignedImmediate"; writer.WriteLine($"{methodName}(ref instruction, {op}, {idConverter.Argument(arg.Name)});"); break; case MethodArgType.Code: case MethodArgType.RepPrefixKind: case MethodArgType.UInt8: case MethodArgType.UInt16: case MethodArgType.PreferedInt32: case MethodArgType.ArrayIndex: case MethodArgType.ArrayLength: case MethodArgType.ByteArray: case MethodArgType.WordArray: case MethodArgType.DwordArray: case MethodArgType.QwordArray: case MethodArgType.ByteSlice: case MethodArgType.WordSlice: case MethodArgType.DwordSlice: case MethodArgType.QwordSlice: case MethodArgType.BytePtr: case MethodArgType.WordPtr: case MethodArgType.DwordPtr: case MethodArgType.QwordPtr: default: throw new InvalidOperationException(); } } WriteMethodFooter(writer, args.Count - 1); } writer.WriteLine("}"); } protected override void GenCreateBranch(FileWriter writer, CreateMethod method) { if (method.Args.Count != 2) throw new InvalidOperationException(); WriteDocs(writer, method); writer.Write("public static Instruction CreateBranch("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { WriteInitializeInstruction(writer, method); writer.WriteLine(); writer.WriteLine($"instruction.InternalOp0Kind = GetNearBranchOpKind({idConverter.Argument(method.Args[0].Name)}, 0);"); writer.WriteLine($"instruction.NearBranch64 = {idConverter.Argument(method.Args[1].Name)};"); WriteMethodFooter(writer, 1); } writer.WriteLine("}"); } protected override void GenCreateFarBranch(FileWriter writer, CreateMethod method) { if (method.Args.Count != 3) throw new InvalidOperationException(); WriteDocs(writer, method); writer.Write("public static Instruction CreateBranch("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { WriteInitializeInstruction(writer, method); writer.WriteLine(); writer.WriteLine($"instruction.InternalOp0Kind = GetFarBranchOpKind({idConverter.Argument(method.Args[0].Name)}, 0);"); writer.WriteLine($"instruction.FarBranchSelector = {idConverter.Argument(method.Args[1].Name)};"); writer.WriteLine($"instruction.FarBranch32 = {idConverter.Argument(method.Args[2].Name)};"); WriteMethodFooter(writer, 1); } writer.WriteLine("}"); } protected override void GenCreateXbegin(FileWriter writer, CreateMethod method) { if (method.Args.Count != 2) throw new InvalidOperationException(); WriteDocs(writer, method); writer.Write("public static Instruction CreateXbegin("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { writer.WriteLine("Instruction instruction = default;"); var bitnessName = idConverter.Argument(method.Args[0].Name); var opKindName = genTypes[TypeIds.OpKind].Name(idConverter); var codeName = codeType.Name(idConverter); writer.WriteLine($"switch ({bitnessName}) {{"); writer.WriteLine($"case 16:"); using (writer.Indent()) { writer.WriteLine($"instruction.InternalCode = {codeName}.{codeType[nameof(Code.Xbegin_rel16)].Name(idConverter)};"); writer.WriteLine($"instruction.InternalOp0Kind = {opKindName}.{genTypes[TypeIds.OpKind][nameof(OpKind.NearBranch32)].Name(idConverter)};"); writer.WriteLine($"instruction.NearBranch32 = (uint){idConverter.Argument(method.Args[1].Name)};"); writer.WriteLine($"break;"); } writer.WriteLine(); writer.WriteLine($"case 32:"); using (writer.Indent()) { writer.WriteLine($"instruction.InternalCode = {codeName}.{codeType[nameof(Code.Xbegin_rel32)].Name(idConverter)};"); writer.WriteLine($"instruction.InternalOp0Kind = {opKindName}.{genTypes[TypeIds.OpKind][nameof(OpKind.NearBranch32)].Name(idConverter)};"); writer.WriteLine($"instruction.NearBranch32 = (uint){idConverter.Argument(method.Args[1].Name)};"); writer.WriteLine($"break;"); } writer.WriteLine(); writer.WriteLine($"case 64:"); using (writer.Indent()) { writer.WriteLine($"instruction.InternalCode = {codeName}.{codeType[nameof(Code.Xbegin_rel32)].Name(idConverter)};"); writer.WriteLine($"instruction.InternalOp0Kind = {opKindName}.{genTypes[TypeIds.OpKind][nameof(OpKind.NearBranch64)].Name(idConverter)};"); writer.WriteLine($"instruction.NearBranch64 = {idConverter.Argument(method.Args[1].Name)};"); writer.WriteLine($"break;"); } writer.WriteLine(); writer.WriteLine($"default:"); using (writer.Indent()) writer.WriteLine($"throw new ArgumentOutOfRangeException(nameof({bitnessName}));"); writer.WriteLine($"}}"); WriteMethodFooter(writer, 1); } writer.WriteLine("}"); } protected override bool CallGenCreateMemory64 => true; protected override void GenCreateMemory64(FileWriter writer, CreateMethod method) { if (method.Args.Count != 4) throw new InvalidOperationException(); int memOp, regOp; if (method.Args[1].Type == MethodArgType.UInt64) { memOp = 0; regOp = 1; } else { memOp = 1; regOp = 0; } WriteDocs(writer, method); deprecatedWriter.WriteDeprecated(writer, "Create() with a MemoryOperand arg", null, false, false); writer.Write("public static Instruction CreateMemory64("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { var regNone = genTypes[TypeIds.Register][nameof(Register.None)]; var regStr = $"{regNone.DeclaringType.Name(idConverter)}.{regNone.Name(idConverter)}"; var addrStr = idConverter.Argument(method.Args[1 + memOp].Name); var segPrefStr = idConverter.Argument(method.Args[3].Name); var memOpStr = $"new MemoryOperand({regStr}, (long){addrStr}, 8, false, {segPrefStr})"; var regOpStr = idConverter.Argument(method.Args[1 + regOp].Name); var codeStr = idConverter.Argument(method.Args[0].Name); if (memOp == 0) writer.WriteLine($"return Create({codeStr}, {memOpStr}, {regOpStr});"); else writer.WriteLine($"return Create({codeStr}, {regOpStr}, {memOpStr});"); } writer.WriteLine("}"); } static void WriteComma(FileWriter writer) => writer.Write(", "); void Write(FileWriter writer, EnumValue value) => writer.Write($"{value.DeclaringType.Name(idConverter)}.{value.Name(idConverter)}"); void Write(FileWriter writer, MethodArg arg) => writer.Write(idConverter.Argument(arg.Name)); protected override void GenCreateString_Reg_SegRSI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) { WriteDocs(writer, method); var methodName = idConverter.Method("Create" + methodBaseName); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") =>"); using (writer.Indent()) { writer.Write("CreateString_Reg_SegRSI("); switch (kind) { case StringMethodKind.Full: if (method.Args.Count != 3) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, register); WriteComma(writer); Write(writer, method.Args[1]); WriteComma(writer); Write(writer, method.Args[2]); break; case StringMethodKind.Rep: if (method.Args.Count != 1) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, register); WriteComma(writer); Write(writer, genTypes[TypeIds.Register][nameof(Register.None)]); WriteComma(writer); Write(writer, genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)]); break; case StringMethodKind.Repe: case StringMethodKind.Repne: default: throw new InvalidOperationException(); } writer.WriteLine(");"); } } protected override void GenCreateString_Reg_ESRDI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) { WriteDocs(writer, method); var methodName = idConverter.Method("Create" + methodBaseName); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") =>"); using (writer.Indent()) { writer.Write("CreateString_Reg_ESRDI("); switch (kind) { case StringMethodKind.Full: if (method.Args.Count != 2) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, register); WriteComma(writer); Write(writer, method.Args[1]); break; case StringMethodKind.Repe: case StringMethodKind.Repne: if (method.Args.Count != 1) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, register); WriteComma(writer); Write(writer, kind == StringMethodKind.Repe ? genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)] : genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repne)]); break; case StringMethodKind.Rep: default: throw new InvalidOperationException(); } writer.WriteLine(");"); } } protected override void GenCreateString_ESRDI_Reg(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) { WriteDocs(writer, method); var methodName = idConverter.Method("Create" + methodBaseName); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") =>"); using (writer.Indent()) { writer.Write("CreateString_ESRDI_Reg("); switch (kind) { case StringMethodKind.Full: if (method.Args.Count != 2) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, register); WriteComma(writer); Write(writer, method.Args[1]); break; case StringMethodKind.Rep: if (method.Args.Count != 1) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, register); WriteComma(writer); Write(writer, genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)]); break; case StringMethodKind.Repe: case StringMethodKind.Repne: default: throw new InvalidOperationException(); } writer.WriteLine(");"); } } protected override void GenCreateString_SegRSI_ESRDI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code) { WriteDocs(writer, method); var methodName = idConverter.Method("Create" + methodBaseName); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") =>"); using (writer.Indent()) { writer.Write("CreateString_SegRSI_ESRDI("); switch (kind) { case StringMethodKind.Full: if (method.Args.Count != 3) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, method.Args[1]); WriteComma(writer); Write(writer, method.Args[2]); break; case StringMethodKind.Repe: case StringMethodKind.Repne: if (method.Args.Count != 1) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, genTypes[TypeIds.Register][nameof(Register.None)]); WriteComma(writer); Write(writer, kind == StringMethodKind.Repe ? genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)] : genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repne)]); break; case StringMethodKind.Rep: default: throw new InvalidOperationException(); } writer.WriteLine(");"); } } protected override void GenCreateString_ESRDI_SegRSI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code) { WriteDocs(writer, method); var methodName = idConverter.Method("Create" + methodBaseName); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") =>"); using (writer.Indent()) { writer.Write("CreateString_ESRDI_SegRSI("); switch (kind) { case StringMethodKind.Full: if (method.Args.Count != 3) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, method.Args[1]); WriteComma(writer); Write(writer, method.Args[2]); break; case StringMethodKind.Rep: if (method.Args.Count != 1) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, genTypes[TypeIds.Register][nameof(Register.None)]); WriteComma(writer); Write(writer, genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)]); break; case StringMethodKind.Repe: case StringMethodKind.Repne: default: throw new InvalidOperationException(); } writer.WriteLine(");"); } } protected override void GenCreateMaskmov(FileWriter writer, CreateMethod method, string methodBaseName, EnumValue code) { WriteDocs(writer, method); var methodName = idConverter.Method("Create" + methodBaseName); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") =>"); using (writer.Indent()) { writer.Write("CreateMaskmov("); if (method.Args.Count != 4) throw new InvalidOperationException(); Write(writer, code); WriteComma(writer); Write(writer, method.Args[0]); WriteComma(writer); Write(writer, method.Args[1]); WriteComma(writer); Write(writer, method.Args[2]); WriteComma(writer); Write(writer, method.Args[3]); writer.WriteLine(");"); } } protected override void GenCreateDeclareData(FileWriter writer, CreateMethod method, DeclareDataKind kind) { EnumValue code; string setValueName; string methodName; switch (kind) { case DeclareDataKind.Byte: code = codeType[nameof(Code.DeclareByte)]; setValueName = "SetDeclareByteValue"; methodName = "CreateDeclareByte"; break; case DeclareDataKind.Word: code = codeType[nameof(Code.DeclareWord)]; setValueName = "SetDeclareWordValue"; methodName = "CreateDeclareWord"; break; case DeclareDataKind.Dword: code = codeType[nameof(Code.DeclareDword)]; setValueName = "SetDeclareDwordValue"; methodName = "CreateDeclareDword"; break; case DeclareDataKind.Qword: code = codeType[nameof(Code.DeclareQword)]; setValueName = "SetDeclareQwordValue"; methodName = "CreateDeclareQword"; break; default: throw new InvalidOperationException(); } writer.WriteLine(); WriteDocs(writer, method); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { WriteInitializeInstruction(writer, code); writer.WriteLine($"instruction.InternalDeclareDataCount = {method.Args.Count};"); writer.WriteLine(); for (int i = 0; i < method.Args.Count; i++) writer.WriteLine($"instruction.{setValueName}({i}, {idConverter.Argument(method.Args[i].Name)});"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); } void GenCreateDeclareDataArray(FileWriter writer, CreateMethod method, string methodName, string calledMethodName) { writer.WriteLine(); WriteDocs(writer, method); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { var dataName = idConverter.Argument(method.Args[0].Name); writer.WriteLine($"if ({dataName} is null)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentNullException_{dataName}();"); writer.WriteLine($"return {calledMethodName}({dataName}, 0, {dataName}.Length);"); } writer.WriteLine("}"); } void GenCreateDeclareDataSlice(FileWriter writer, CreateMethod method, int elemSize, EnumValue code, string methodName, string setDeclValueName) { writer.WriteLine(); writer.WriteLineNoIndent($"#if {CSharpConstants.HasSpanDefine}"); WriteDocs(writer, method); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { var dataName = idConverter.Argument(method.Args[0].Name); writer.WriteLine($"if ((uint){dataName}.Length - 1 > {16 / elemSize} - 1)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{dataName}();"); writer.WriteLine(); WriteInitializeInstruction(writer, code); writer.WriteLine($"instruction.InternalDeclareDataCount = (uint){dataName}.Length;"); writer.WriteLine(); writer.WriteLine($"for (int i = 0; i < {dataName}.Length; i++)"); using (writer.Indent()) writer.WriteLine($"instruction.{setDeclValueName}(i, {dataName}[i]);"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); writer.WriteLineNoIndent($"#endif"); } protected override void GenCreateDeclareDataArray(FileWriter writer, CreateMethod method, DeclareDataKind kind, ArrayType arrayType) { switch (kind) { case DeclareDataKind.Byte: switch (arrayType) { case ArrayType.BytePtr: break; case ArrayType.ByteArray: GenCreateDeclareDataArray(writer, method, "CreateDeclareByte", "CreateDeclareByte"); break; case ArrayType.ByteSlice: GenCreateDeclareDataSlice(writer, method, 1, codeType[nameof(Code.DeclareByte)], "CreateDeclareByte", "SetDeclareByteValue"); break; default: throw new InvalidOperationException(); } break; case DeclareDataKind.Word: switch (arrayType) { case ArrayType.BytePtr: case ArrayType.WordPtr: break; case ArrayType.ByteArray: case ArrayType.WordArray: GenCreateDeclareDataArray(writer, method, "CreateDeclareWord", "CreateDeclareWord"); break; case ArrayType.ByteSlice: writer.WriteLine(); writer.WriteLineNoIndent($"#if {CSharpConstants.HasSpanDefine}"); WriteDocs(writer, method); writer.Write($"public static Instruction CreateDeclareWord("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { var dataName = idConverter.Argument(method.Args[0].Name); writer.WriteLine($"if ((uint){dataName}.Length - 1 > 16 - 1 || ((uint){dataName}.Length & 1) != 0)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{dataName}();"); writer.WriteLine(); WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareWord)]); writer.WriteLine($"instruction.InternalDeclareDataCount = (uint){dataName}.Length / 2;"); writer.WriteLine(); writer.WriteLine($"for (int i = 0; i < {dataName}.Length; i += 2) {{"); using (writer.Indent()) { writer.WriteLine($"uint v = {dataName}[i] | ((uint){dataName}[i + 1] << 8);"); writer.WriteLine("instruction.SetDeclareWordValue(i / 2, (ushort)v);"); } writer.WriteLine("}"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); writer.WriteLineNoIndent($"#endif"); break; case ArrayType.WordSlice: GenCreateDeclareDataSlice(writer, method, 2, codeType[nameof(Code.DeclareWord)], "CreateDeclareWord", "SetDeclareWordValue"); break; default: throw new InvalidOperationException(); } break; case DeclareDataKind.Dword: switch (arrayType) { case ArrayType.BytePtr: case ArrayType.DwordPtr: break; case ArrayType.ByteArray: case ArrayType.DwordArray: GenCreateDeclareDataArray(writer, method, "CreateDeclareDword", "CreateDeclareDword"); break; case ArrayType.ByteSlice: writer.WriteLine(); writer.WriteLineNoIndent($"#if {CSharpConstants.HasSpanDefine}"); WriteDocs(writer, method); writer.Write($"public static Instruction CreateDeclareDword("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { var dataName = idConverter.Argument(method.Args[0].Name); writer.WriteLine($"if ((uint){dataName}.Length - 1 > 16 - 1 || ((uint){dataName}.Length & 3) != 0)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{dataName}();"); writer.WriteLine(); WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareDword)]); writer.WriteLine($"instruction.InternalDeclareDataCount = (uint){dataName}.Length / 4;"); writer.WriteLine(); writer.WriteLine($"for (int i = 0; i < {dataName}.Length; i += 4) {{"); using (writer.Indent()) { writer.WriteLine($"uint v = {dataName}[i] | ((uint){dataName}[i + 1] << 8) | ((uint){dataName}[i + 2] << 16) | ((uint){dataName}[i + 3] << 24);"); writer.WriteLine("instruction.SetDeclareDwordValue(i / 4, v);"); } writer.WriteLine("}"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); writer.WriteLineNoIndent($"#endif"); break; case ArrayType.DwordSlice: GenCreateDeclareDataSlice(writer, method, 4, codeType[nameof(Code.DeclareDword)], "CreateDeclareDword", "SetDeclareDwordValue"); break; default: throw new InvalidOperationException(); } break; case DeclareDataKind.Qword: switch (arrayType) { case ArrayType.BytePtr: case ArrayType.QwordPtr: break; case ArrayType.ByteArray: case ArrayType.QwordArray: GenCreateDeclareDataArray(writer, method, "CreateDeclareQword", "CreateDeclareQword"); break; case ArrayType.ByteSlice: writer.WriteLine(); writer.WriteLineNoIndent($"#if {CSharpConstants.HasSpanDefine}"); WriteDocs(writer, method); writer.Write($"public static Instruction CreateDeclareQword("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { var dataName = idConverter.Argument(method.Args[0].Name); writer.WriteLine($"if ((uint){dataName}.Length - 1 > 16 - 1 || ((uint){dataName}.Length & 7) != 0)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{dataName}();"); writer.WriteLine(); WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareQword)]); writer.WriteLine($"instruction.InternalDeclareDataCount = (uint){dataName}.Length / 8;"); writer.WriteLine(); writer.WriteLine($"for (int i = 0; i < {dataName}.Length; i += 8) {{"); using (writer.Indent()) { writer.WriteLine($"uint v1 = {dataName}[i] | ((uint){dataName}[i + 1] << 8) | ((uint){dataName}[i + 2] << 16) | ((uint){dataName}[i + 3] << 24);"); writer.WriteLine($"uint v2 = {dataName}[i + 4] | ((uint){dataName}[i + 5] << 8) | ((uint){dataName}[i + 6] << 16) | ((uint){dataName}[i + 7] << 24);"); writer.WriteLine("instruction.SetDeclareQwordValue(i / 8, (ulong)v1 | ((ulong)v2 << 32));"); } writer.WriteLine("}"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); writer.WriteLineNoIndent($"#endif"); break; case ArrayType.QwordSlice: GenCreateDeclareDataSlice(writer, method, 8, codeType[nameof(Code.DeclareQword)], "CreateDeclareQword", "SetDeclareQwordValue"); break; default: throw new InvalidOperationException(); } break; default: throw new InvalidOperationException(); } } void GenCreateDeclareDataArrayLength(FileWriter writer, CreateMethod method, int elemSize, EnumValue code, string methodName, string setDeclValueName) { writer.WriteLine(); WriteDocs(writer, method); writer.Write($"public static Instruction {methodName}("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { var dataName = idConverter.Argument(method.Args[0].Name); var indexName = idConverter.Argument(method.Args[1].Name); var lengthName = idConverter.Argument(method.Args[2].Name); writer.WriteLine($"if ({dataName} is null)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentNullException_{dataName}();"); writer.WriteLine($"if ((uint){lengthName} - 1 > {16 / elemSize} - 1)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{lengthName}();"); writer.WriteLine($"if ((ulong)(uint){indexName} + (uint){lengthName} > (uint){dataName}.Length)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{indexName}();"); writer.WriteLine(); WriteInitializeInstruction(writer, code); writer.WriteLine($"instruction.InternalDeclareDataCount = (uint){lengthName};"); writer.WriteLine(); writer.WriteLine($"for (int i = 0; i < {lengthName}; i++)"); using (writer.Indent()) writer.WriteLine($"instruction.{setDeclValueName}(i, {dataName}[{indexName} + i]);"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); } protected override void GenCreateDeclareDataArrayLength(FileWriter writer, CreateMethod method, DeclareDataKind kind, ArrayType arrayType) { string dataName, lengthName, indexName; switch (kind) { case DeclareDataKind.Byte: switch (arrayType) { case ArrayType.ByteArray: GenCreateDeclareDataArrayLength(writer, method, 1, codeType[nameof(Code.DeclareByte)], "CreateDeclareByte", "SetDeclareByteValue"); break; default: throw new InvalidOperationException(); } break; case DeclareDataKind.Word: switch (arrayType) { case ArrayType.ByteArray: writer.WriteLine(); WriteDocs(writer, method); writer.Write($"public static Instruction CreateDeclareWord("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { dataName = idConverter.Argument(method.Args[0].Name); indexName = idConverter.Argument(method.Args[1].Name); lengthName = idConverter.Argument(method.Args[2].Name); writer.WriteLine($"if ({dataName} is null)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentNullException_{dataName}();"); writer.WriteLine($"if ((uint){lengthName} - 1 > 16 - 1 || ((uint){lengthName} & 1) != 0)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{lengthName}();"); writer.WriteLine($"if ((ulong)(uint){indexName} + (uint){lengthName} > (uint){dataName}.Length)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{indexName}();"); writer.WriteLine(); WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareWord)]); writer.WriteLine($"instruction.InternalDeclareDataCount = (uint){lengthName} / 2;"); writer.WriteLine(); writer.WriteLine($"for (int i = 0; i < {lengthName}; i += 2) {{"); using (writer.Indent()) { writer.WriteLine($"uint v = {dataName}[{indexName} + i] | ((uint){dataName}[{indexName} + i + 1] << 8);"); writer.WriteLine("instruction.SetDeclareWordValue(i / 2, (ushort)v);"); } writer.WriteLine("}"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); break; case ArrayType.WordArray: GenCreateDeclareDataArrayLength(writer, method, 2, codeType[nameof(Code.DeclareWord)], "CreateDeclareWord", "SetDeclareWordValue"); break; default: throw new InvalidOperationException(); } break; case DeclareDataKind.Dword: switch (arrayType) { case ArrayType.ByteArray: writer.WriteLine(); WriteDocs(writer, method); writer.Write($"public static Instruction CreateDeclareDword("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { dataName = idConverter.Argument(method.Args[0].Name); indexName = idConverter.Argument(method.Args[1].Name); lengthName = idConverter.Argument(method.Args[2].Name); writer.WriteLine($"if ({dataName} is null)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentNullException_{dataName}();"); writer.WriteLine($"if ((uint){lengthName} - 1 > 16 - 1 || ((uint){lengthName} & 3) != 0)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{lengthName}();"); writer.WriteLine($"if ((ulong)(uint){indexName} + (uint){lengthName} > (uint){dataName}.Length)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{indexName}();"); writer.WriteLine(); WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareDword)]); writer.WriteLine($"instruction.InternalDeclareDataCount = (uint){lengthName} / 4;"); writer.WriteLine(); writer.WriteLine($"for (int i = 0; i < {lengthName}; i += 4) {{"); using (writer.Indent()) { writer.WriteLine($"uint v = {dataName}[{indexName} + i] | ((uint){dataName}[{indexName} + i + 1] << 8) | ((uint){dataName}[{indexName} + i + 2] << 16) | ((uint){dataName}[{indexName} + i + 3] << 24);"); writer.WriteLine("instruction.SetDeclareDwordValue(i / 4, v);"); } writer.WriteLine("}"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); break; case ArrayType.DwordArray: GenCreateDeclareDataArrayLength(writer, method, 4, codeType[nameof(Code.DeclareDword)], "CreateDeclareDword", "SetDeclareDwordValue"); break; default: throw new InvalidOperationException(); } break; case DeclareDataKind.Qword: switch (arrayType) { case ArrayType.ByteArray: writer.WriteLine(); WriteDocs(writer, method); writer.Write($"public static Instruction CreateDeclareQword("); WriteMethodDeclArgs(writer, method); writer.WriteLine(") {"); using (writer.Indent()) { dataName = idConverter.Argument(method.Args[0].Name); indexName = idConverter.Argument(method.Args[1].Name); lengthName = idConverter.Argument(method.Args[2].Name); writer.WriteLine($"if ({dataName} is null)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentNullException_{dataName}();"); writer.WriteLine($"if ((uint){lengthName} - 1 > 16 - 1 || ((uint){lengthName} & 7) != 0)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{lengthName}();"); writer.WriteLine($"if ((ulong)(uint){indexName} + (uint){lengthName} > (uint){dataName}.Length)"); using (writer.Indent()) writer.WriteLine($"ThrowHelper.ThrowArgumentOutOfRangeException_{indexName}();"); writer.WriteLine(); WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareQword)]); writer.WriteLine($"instruction.InternalDeclareDataCount = (uint){lengthName} / 8;"); writer.WriteLine(); writer.WriteLine($"for (int i = 0; i < {lengthName}; i += 8) {{"); using (writer.Indent()) { writer.WriteLine($"uint v1 = {dataName}[{indexName} + i] | ((uint){dataName}[{indexName} + i + 1] << 8) | ((uint){dataName}[{indexName} + i + 2] << 16) | ((uint){dataName}[{indexName} + i + 3] << 24);"); writer.WriteLine($"uint v2 = {dataName}[{indexName} + i + 4] | ((uint){dataName}[{indexName} + i + 5] << 8) | ((uint){dataName}[{indexName} + i + 6] << 16) | ((uint){dataName}[{indexName} + i + 7] << 24);"); writer.WriteLine("instruction.SetDeclareQwordValue(i / 8, (ulong)v1 | ((ulong)v2 << 32));"); } writer.WriteLine("}"); WriteMethodFooter(writer, 0); } writer.WriteLine("}"); break; case ArrayType.QwordArray: GenCreateDeclareDataArrayLength(writer, method, 8, codeType[nameof(Code.DeclareQword)], "CreateDeclareQword", "SetDeclareQwordValue"); break; default: throw new InvalidOperationException(); } break; default: throw new InvalidOperationException(); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary.IO { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using Apache.Ignite.Core.Impl.Memory; /// <summary> /// Binary onheap stream. /// </summary> internal unsafe class BinaryHeapStream : IBinaryStream { /** Byte: zero. */ private const byte ByteZero = 0; /** Byte: one. */ private const byte ByteOne = 1; /** LITTLE_ENDIAN flag. */ private static readonly bool LittleEndian = BitConverter.IsLittleEndian; /** Position. */ private int _pos; /** Disposed flag. */ private bool _disposed; /** Data array. */ private byte[] _data; /// <summary> /// Constructor. /// </summary> /// <param name="cap">Initial capacity.</param> public BinaryHeapStream(int cap) { Debug.Assert(cap >= 0); _data = new byte[cap]; } /// <summary> /// Constructor. /// </summary> /// <param name="data">Data array.</param> public BinaryHeapStream(byte[] data) { Debug.Assert(data != null); _data = data; } /// <summary> /// Internal routine to write byte array. /// </summary> /// <param name="val">Byte array.</param> /// <param name="data">Data pointer.</param> private static void WriteByteArray0(byte[] val, byte* data) { fixed (byte* val0 = val) { CopyMemory(val0, data, val.Length); } } /// <summary> /// Internal routine to read byte array. /// </summary> /// <param name="len">Array length.</param> /// <param name="data">Data pointer.</param> /// <returns>Byte array</returns> private static byte[] ReadByteArray0(int len, byte* data) { byte[] res = new byte[len]; fixed (byte* res0 = res) { CopyMemory(data, res0, len); } return res; } /** <inheritdoc /> */ public void WriteBool(bool val) { WriteByte(val ? ByteOne : ByteZero); } /** <inheritdoc /> */ public bool ReadBool() { return ReadByte() == ByteOne; } /// <summary> /// Internal routine to write bool array. /// </summary> /// <param name="val">Bool array.</param> /// <param name="data">Data pointer.</param> private static void WriteBoolArray0(bool[] val, byte* data) { fixed (bool* val0 = val) { CopyMemory((byte*)val0, data, val.Length); } } /// <summary> /// Internal routine to read bool array. /// </summary> /// <param name="len">Array length.</param> /// <param name="data">Data pointer.</param> /// <returns>Bool array</returns> private static bool[] ReadBoolArray0(int len, byte* data) { bool[] res = new bool[len]; fixed (bool* res0 = res) { CopyMemory(data, (byte*)res0, len); } return res; } /// <summary> /// Internal routine to write short value. /// </summary> /// <param name="val">Short value.</param> /// <param name="data">Data pointer.</param> private static void WriteShort0(short val, byte* data) { if (LittleEndian) *((short*)data) = val; else { byte* valPtr = (byte*)&val; data[0] = valPtr[1]; data[1] = valPtr[0]; } } /// <summary> /// Internal routine to read short value. /// </summary> /// <param name="data">Data pointer.</param> /// <returns>Short value</returns> private static short ReadShort0(byte* data) { short val; if (LittleEndian) val = *((short*)data); else { byte* valPtr = (byte*)&val; valPtr[0] = data[1]; valPtr[1] = data[0]; } return val; } /// <summary> /// Internal routine to write short array. /// </summary> /// <param name="val">Short array.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> private static void WriteShortArray0(short[] val, byte* data, int cnt) { if (LittleEndian) { fixed (short* val0 = val) { CopyMemory((byte*)val0, data, cnt); } } else { byte* curPos = data; for (int i = 0; i < val.Length; i++) { short val0 = val[i]; byte* valPtr = (byte*)&(val0); *curPos++ = valPtr[1]; *curPos++ = valPtr[0]; } } } /// <summary> /// Internal routine to read short array. /// </summary> /// <param name="len">Array length.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> /// <returns>Short array</returns> private static short[] ReadShortArray0(int len, byte* data, int cnt) { short[] res = new short[len]; if (LittleEndian) { fixed (short* res0 = res) { CopyMemory(data, (byte*)res0, cnt); } } else { for (int i = 0; i < len; i++) { short val; byte* valPtr = (byte*)&val; valPtr[1] = *data++; valPtr[0] = *data++; res[i] = val; } } return res; } /** <inheritdoc /> */ public void WriteChar(char val) { WriteShort(*(short*)(&val)); } /** <inheritdoc /> */ public char ReadChar() { short val = ReadShort(); return *(char*)(&val); } /// <summary> /// Internal routine to write char array. /// </summary> /// <param name="val">Char array.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> private static void WriteCharArray0(char[] val, byte* data, int cnt) { if (LittleEndian) { fixed (char* val0 = val) { CopyMemory((byte*)val0, data, cnt); } } else { byte* curPos = data; for (int i = 0; i < val.Length; i++) { char val0 = val[i]; byte* valPtr = (byte*)&(val0); *curPos++ = valPtr[1]; *curPos++ = valPtr[0]; } } } /// <summary> /// Internal routine to read char array. /// </summary> /// <param name="len">Count.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> /// <returns>Char array</returns> private static char[] ReadCharArray0(int len, byte* data, int cnt) { char[] res = new char[len]; if (LittleEndian) { fixed (char* res0 = res) { CopyMemory(data, (byte*)res0, cnt); } } else { for (int i = 0; i < len; i++) { char val; byte* valPtr = (byte*)&val; valPtr[1] = *data++; valPtr[0] = *data++; res[i] = val; } } return res; } /// <summary> /// Internal routine to write int value. /// </summary> /// <param name="val">Int value.</param> /// <param name="data">Data pointer.</param> private static void WriteInt0(int val, byte* data) { if (LittleEndian) *((int*)data) = val; else { byte* valPtr = (byte*)&val; data[0] = valPtr[3]; data[1] = valPtr[2]; data[2] = valPtr[1]; data[3] = valPtr[0]; } } /// <summary> /// Internal routine to read int value. /// </summary> /// <param name="data">Data pointer.</param> /// <returns>Int value</returns> private static int ReadInt0(byte* data) { int val; if (LittleEndian) val = *((int*)data); else { byte* valPtr = (byte*)&val; valPtr[0] = data[3]; valPtr[1] = data[2]; valPtr[2] = data[1]; valPtr[3] = data[0]; } return val; } /// <summary> /// Internal routine to write int array. /// </summary> /// <param name="val">Int array.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> private static void WriteIntArray0(int[] val, byte* data, int cnt) { if (LittleEndian) { fixed (int* val0 = val) { CopyMemory((byte*)val0, data, cnt); } } else { byte* curPos = data; for (int i = 0; i < val.Length; i++) { int val0 = val[i]; byte* valPtr = (byte*)&(val0); *curPos++ = valPtr[3]; *curPos++ = valPtr[2]; *curPos++ = valPtr[1]; *curPos++ = valPtr[0]; } } } /// <summary> /// Internal routine to read int array. /// </summary> /// <param name="len">Count.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> /// <returns>Int array</returns> private static int[] ReadIntArray0(int len, byte* data, int cnt) { int[] res = new int[len]; if (LittleEndian) { fixed (int* res0 = res) { CopyMemory(data, (byte*)res0, cnt); } } else { for (int i = 0; i < len; i++) { int val; byte* valPtr = (byte*)&val; valPtr[3] = *data++; valPtr[2] = *data++; valPtr[1] = *data++; valPtr[0] = *data++; res[i] = val; } } return res; } /** <inheritdoc /> */ public void WriteFloat(float val) { int val0 = *(int*)(&val); WriteInt(val0); } /** <inheritdoc /> */ public float ReadFloat() { int val = ReadInt(); return BinaryUtils.IntToFloatBits(val); } /// <summary> /// Internal routine to write float array. /// </summary> /// <param name="val">Int array.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> private static void WriteFloatArray0(float[] val, byte* data, int cnt) { if (LittleEndian) { fixed (float* val0 = val) { CopyMemory((byte*)val0, data, cnt); } } else { byte* curPos = data; for (int i = 0; i < val.Length; i++) { float val0 = val[i]; byte* valPtr = (byte*)&(val0); *curPos++ = valPtr[3]; *curPos++ = valPtr[2]; *curPos++ = valPtr[1]; *curPos++ = valPtr[0]; } } } /// <summary> /// Internal routine to read float array. /// </summary> /// <param name="len">Count.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> /// <returns>Float array</returns> private static float[] ReadFloatArray0(int len, byte* data, int cnt) { float[] res = new float[len]; if (LittleEndian) { fixed (float* res0 = res) { CopyMemory(data, (byte*)res0, cnt); } } else { for (int i = 0; i < len; i++) { int val; byte* valPtr = (byte*)&val; valPtr[3] = *data++; valPtr[2] = *data++; valPtr[1] = *data++; valPtr[0] = *data++; res[i] = val; } } return res; } /// <summary> /// Internal routine to write long value. /// </summary> /// <param name="val">Long value.</param> /// <param name="data">Data pointer.</param> private static void WriteLong0(long val, byte* data) { if (LittleEndian) *((long*)data) = val; else { byte* valPtr = (byte*)&val; data[0] = valPtr[7]; data[1] = valPtr[6]; data[2] = valPtr[5]; data[3] = valPtr[4]; data[4] = valPtr[3]; data[5] = valPtr[2]; data[6] = valPtr[1]; data[7] = valPtr[0]; } } /// <summary> /// Internal routine to read long value. /// </summary> /// <param name="data">Data pointer.</param> /// <returns>Long value</returns> private static long ReadLong0(byte* data) { long val; if (LittleEndian) val = *((long*)data); else { byte* valPtr = (byte*)&val; valPtr[0] = data[7]; valPtr[1] = data[6]; valPtr[2] = data[5]; valPtr[3] = data[4]; valPtr[4] = data[3]; valPtr[5] = data[2]; valPtr[6] = data[1]; valPtr[7] = data[0]; } return val; } /// <summary> /// Internal routine to write long array. /// </summary> /// <param name="val">Long array.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> private static void WriteLongArray0(long[] val, byte* data, int cnt) { if (LittleEndian) { fixed (long* val0 = val) { CopyMemory((byte*)val0, data, cnt); } } else { byte* curPos = data; for (int i = 0; i < val.Length; i++) { long val0 = val[i]; byte* valPtr = (byte*)&(val0); *curPos++ = valPtr[7]; *curPos++ = valPtr[6]; *curPos++ = valPtr[5]; *curPos++ = valPtr[4]; *curPos++ = valPtr[3]; *curPos++ = valPtr[2]; *curPos++ = valPtr[1]; *curPos++ = valPtr[0]; } } } /// <summary> /// Internal routine to read long array. /// </summary> /// <param name="len">Count.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> /// <returns>Long array</returns> private static long[] ReadLongArray0(int len, byte* data, int cnt) { long[] res = new long[len]; if (LittleEndian) { fixed (long* res0 = res) { CopyMemory(data, (byte*)res0, cnt); } } else { for (int i = 0; i < len; i++) { long val; byte* valPtr = (byte*)&val; valPtr[7] = *data++; valPtr[6] = *data++; valPtr[5] = *data++; valPtr[4] = *data++; valPtr[3] = *data++; valPtr[2] = *data++; valPtr[1] = *data++; valPtr[0] = *data++; res[i] = val; } } return res; } /** <inheritdoc /> */ public void WriteDouble(double val) { long val0 = *(long*)(&val); WriteLong(val0); } /** <inheritdoc /> */ public double ReadDouble() { long val = ReadLong(); return BinaryUtils.LongToDoubleBits(val); } /// <summary> /// Internal routine to write double array. /// </summary> /// <param name="val">Double array.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> private static void WriteDoubleArray0(double[] val, byte* data, int cnt) { if (LittleEndian) { fixed (double* val0 = val) { CopyMemory((byte*)val0, data, cnt); } } else { byte* curPos = data; for (int i = 0; i < val.Length; i++) { double val0 = val[i]; byte* valPtr = (byte*)&(val0); *curPos++ = valPtr[7]; *curPos++ = valPtr[6]; *curPos++ = valPtr[5]; *curPos++ = valPtr[4]; *curPos++ = valPtr[3]; *curPos++ = valPtr[2]; *curPos++ = valPtr[1]; *curPos++ = valPtr[0]; } } } /// <summary> /// Internal routine to read double array. /// </summary> /// <param name="len">Count.</param> /// <param name="data">Data pointer.</param> /// <param name="cnt">Bytes count.</param> /// <returns>Double array</returns> private static double[] ReadDoubleArray0(int len, byte* data, int cnt) { double[] res = new double[len]; if (LittleEndian) { fixed (double* res0 = res) { CopyMemory(data, (byte*)res0, cnt); } } else { for (int i = 0; i < len; i++) { double val; byte* valPtr = (byte*)&val; valPtr[7] = *data++; valPtr[6] = *data++; valPtr[5] = *data++; valPtr[4] = *data++; valPtr[3] = *data++; valPtr[2] = *data++; valPtr[1] = *data++; valPtr[0] = *data++; res[i] = val; } } return res; } /** <inheritdoc /> */ public void Write(byte[] src, int off, int cnt) { fixed (byte* src0 = src) { Write(src0 + off, cnt); } } /** <inheritdoc /> */ public void Read(byte[] dest, int off, int cnt) { fixed (byte* dest0 = dest) { Read(dest0 + off, cnt); } } /// <summary> /// Internal write routine. /// </summary> /// <param name="src">Source.</param> /// <param name="cnt">Count.</param> /// <param name="data">Data (dsetination).</param> private void WriteInternal(byte* src, int cnt, byte* data) { CopyMemory(src, data + _pos, cnt); } /// <summary> /// Internal read routine. /// </summary> /// <param name="src">Source</param> /// <param name="dest">Destination.</param> /// <param name="cnt">Count.</param> /// <returns>Amount of bytes written.</returns> private void ReadInternal(byte* src, byte* dest, int cnt) { int cnt0 = Math.Min(Remaining, cnt); CopyMemory(src + _pos, dest, cnt0); ShiftRead(cnt0); } /** <inheritdoc /> */ public int Position { get { return _pos; } } /** <inheritdoc /> */ public int Remaining { get { return _data.Length - _pos; } } /// <summary> /// Internal array. /// </summary> internal byte[] InternalArray { get { return _data; } } /// <inheritdoc /> /// <exception cref="T:System.ArgumentException"> /// Unsupported seek origin: + origin /// or /// Seek before origin: + newPos /// </exception> public int Seek(int offset, SeekOrigin origin) { int newPos; switch (origin) { case SeekOrigin.Begin: { newPos = offset; break; } case SeekOrigin.Current: { newPos = _pos + offset; break; } default: throw new ArgumentException("Unsupported seek origin: " + origin); } if (newPos < 0) throw new ArgumentException("Seek before origin: " + newPos); EnsureWriteCapacity(newPos); _pos = newPos; return _pos; } /** <inheritdoc /> */ public void Flush() { // No-op. } /** <inheritdoc /> */ public void Dispose() { if (_disposed) return; GC.SuppressFinalize(this); _disposed = true; } /// <summary> /// Ensure capacity for write and shift position. /// </summary> /// <param name="cnt">Bytes count.</param> /// <returns>Position before shift.</returns> private int EnsureWriteCapacityAndShift(int cnt) { int pos0 = _pos; EnsureWriteCapacity(_pos + cnt); ShiftWrite(cnt); return pos0; } /// <summary> /// Ensure capacity for read and shift position. /// </summary> /// <param name="cnt">Bytes count.</param> /// <returns>Position before shift.</returns> private int EnsureReadCapacityAndShift(int cnt) { int pos0 = _pos; EnsureReadCapacity(cnt); ShiftRead(cnt); return pos0; } /// <summary> /// Shift position due to write /// </summary> /// <param name="cnt">Bytes count.</param> private void ShiftWrite(int cnt) { _pos += cnt; } /// <summary> /// Shift position due to read. /// </summary> /// <param name="cnt">Bytes count.</param> private void ShiftRead(int cnt) { _pos += cnt; } /// <summary> /// Calculate new capacity. /// </summary> /// <param name="curCap">Current capacity.</param> /// <param name="reqCap">Required capacity.</param> /// <returns>New capacity.</returns> private static int Capacity(int curCap, int reqCap) { int newCap; if (reqCap < 256) newCap = 256; else { newCap = curCap << 1; if (newCap < reqCap) newCap = reqCap; } return newCap; } /// <summary> /// Unsafe memory copy routine. /// </summary> /// <param name="src">Source.</param> /// <param name="dest">Destination.</param> /// <param name="len">Length.</param> private static void CopyMemory(byte* src, byte* dest, int len) { PlatformMemoryUtils.CopyMemory(src, dest, len); } /** <inheritdoc /> */ public void WriteByte(byte val) { int pos0 = EnsureWriteCapacityAndShift(1); _data[pos0] = val; } /** <inheritdoc /> */ public byte ReadByte() { int pos0 = EnsureReadCapacityAndShift(1); return _data[pos0]; } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public void WriteByteArray(byte[] val) { int pos0 = EnsureWriteCapacityAndShift(val.Length); fixed (byte* data0 = _data) { WriteByteArray0(val, data0 + pos0); } } /** <inheritdoc /> */ public byte[] ReadByteArray(int cnt) { int pos0 = EnsureReadCapacityAndShift(cnt); fixed (byte* data0 = _data) { return ReadByteArray0(cnt, data0 + pos0); } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public void WriteBoolArray(bool[] val) { int pos0 = EnsureWriteCapacityAndShift(val.Length); fixed (byte* data0 = _data) { WriteBoolArray0(val, data0 + pos0); } } /** <inheritdoc /> */ public bool[] ReadBoolArray(int cnt) { int pos0 = EnsureReadCapacityAndShift(cnt); fixed (byte* data0 = _data) { return ReadBoolArray0(cnt, data0 + pos0); } } /** <inheritdoc /> */ public void WriteShort(short val) { int pos0 = EnsureWriteCapacityAndShift(2); fixed (byte* data0 = _data) { WriteShort0(val, data0 + pos0); } } /** <inheritdoc /> */ public short ReadShort() { int pos0 = EnsureReadCapacityAndShift(2); fixed (byte* data0 = _data) { return ReadShort0(data0 + pos0); } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public void WriteShortArray(short[] val) { int cnt = val.Length << 1; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = _data) { WriteShortArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public short[] ReadShortArray(int cnt) { int cnt0 = cnt << 1; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = _data) { return ReadShortArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public void WriteCharArray(char[] val) { int cnt = val.Length << 1; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = _data) { WriteCharArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public char[] ReadCharArray(int cnt) { int cnt0 = cnt << 1; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = _data) { return ReadCharArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public void WriteInt(int val) { int pos0 = EnsureWriteCapacityAndShift(4); fixed (byte* data0 = _data) { WriteInt0(val, data0 + pos0); } } /** <inheritdoc /> */ public void WriteInt(int writePos, int val) { EnsureWriteCapacity(writePos + 4); fixed (byte* data0 = _data) { WriteInt0(val, data0 + writePos); } } /** <inheritdoc /> */ public int ReadInt() { int pos0 = EnsureReadCapacityAndShift(4); fixed (byte* data0 = _data) { return ReadInt0(data0 + pos0); } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public void WriteIntArray(int[] val) { int cnt = val.Length << 2; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = _data) { WriteIntArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public int[] ReadIntArray(int cnt) { int cnt0 = cnt << 2; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = _data) { return ReadIntArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public void WriteFloatArray(float[] val) { int cnt = val.Length << 2; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = _data) { WriteFloatArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public float[] ReadFloatArray(int cnt) { int cnt0 = cnt << 2; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = _data) { return ReadFloatArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public void WriteLong(long val) { int pos0 = EnsureWriteCapacityAndShift(8); fixed (byte* data0 = _data) { WriteLong0(val, data0 + pos0); } } /** <inheritdoc /> */ public long ReadLong() { int pos0 = EnsureReadCapacityAndShift(8); fixed (byte* data0 = _data) { return ReadLong0(data0 + pos0); } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public void WriteLongArray(long[] val) { int cnt = val.Length << 3; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = _data) { WriteLongArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public long[] ReadLongArray(int cnt) { int cnt0 = cnt << 3; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = _data) { return ReadLongArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public void WriteDoubleArray(double[] val) { int cnt = val.Length << 3; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = _data) { WriteDoubleArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public double[] ReadDoubleArray(int cnt) { int cnt0 = cnt << 3; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = _data) { return ReadDoubleArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding) { int pos0 = EnsureWriteCapacityAndShift(byteCnt); int written; fixed (byte* data0 = _data) { written = BinaryUtils.StringToUtf8Bytes(chars, charCnt, byteCnt, encoding, data0 + pos0); } return written; } /** <inheritdoc /> */ public void Write(byte* src, int cnt) { EnsureWriteCapacity(_pos + cnt); fixed (byte* data0 = _data) { WriteInternal(src, cnt, data0); } ShiftWrite(cnt); } /** <inheritdoc /> */ public void Read(byte* dest, int cnt) { fixed (byte* data0 = _data) { ReadInternal(data0, dest, cnt); } } /** <inheritdoc /> */ public byte[] GetArray() { return _data; } /** <inheritdoc /> */ public byte[] GetArrayCopy() { byte[] copy = new byte[_pos]; Buffer.BlockCopy(_data, 0, copy, 0, _pos); return copy; } /** <inheritdoc /> */ public bool IsSameArray(byte[] arr) { return _data == arr; } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public T Apply<TArg, T>(IBinaryStreamProcessor<TArg, T> proc, TArg arg) { Debug.Assert(proc != null); fixed (byte* data0 = _data) { return proc.Invoke(data0, arg); } } /// <summary> /// Ensure capacity for write. /// </summary> /// <param name="cnt">Bytes count.</param> private void EnsureWriteCapacity(int cnt) { if (cnt > _data.Length) { int newCap = Capacity(_data.Length, cnt); byte[] data0 = new byte[newCap]; // Copy the whole initial array length here because it can be changed // from Java without position adjusting. Buffer.BlockCopy(_data, 0, data0, 0, _data.Length); _data = data0; } } /// <summary> /// Ensure capacity for write and shift position. /// </summary> /// <param name="cnt">Bytes count.</param> /// <returns>Position before shift.</returns> private void EnsureReadCapacity(int cnt) { if (_data.Length - _pos < cnt) throw new EndOfStreamException("Not enough data in stream [expected=" + cnt + ", remaining=" + (_data.Length - _pos) + ']'); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Multiverse.ToolBox; using Multiverse.AssetRepository; namespace Multiverse.Tools.WorldEditor { public partial class Preferences_Dialog : Form { WorldEditor app; List<string> repositoryDirectoryList = new List<string>(); public Preferences_Dialog(WorldEditor app) { this.app = app; InitializeComponent(); } private void designateAssetRepositoryDirectoriesButton_Click(object sender, EventArgs e) { DesignateRepositories(); } private void ChangeRepositoriesButton_Click(object sender, EventArgs e) { DesignateRepositories(); } private void DesignateRepositories() { DesignateRepositoriesDialog designateRepositoriesDialog = new DesignateRepositoriesDialog(repositoryDirectoryList); DialogResult result = designateRepositoriesDialog.ShowDialog(); if (result == DialogResult.OK) { List<string> dirs = designateRepositoriesDialog.RepositoryDirectoryList; repositoryDirectoryList = new List<string>(dirs); repositoryDirectoryListLabel.Text = RepositoryClass.Instance.MakeRepositoryDirectoryListString(dirs); // filesListBox.Items.Clear(); // foreach (string dir in dirs) // filesListBox.Items.Add(dir); } } #region View Panel public bool DisplayOceanCheckbox { get { return displayOceanCheckbox.Checked; } set { displayOceanCheckbox.Checked = value; } } public bool DisplayFogEffects { get { return fogEffectsCheckBox.Checked; } set { fogEffectsCheckBox.Checked = value; } } public bool LightEffectsDisplay { get { return lightEffectsCheckBox.Checked; } set { lightEffectsCheckBox.Checked = value; } } public bool ShadowsDisplay { get { return shadowsCheckBox.Checked; } set { shadowsCheckBox.Checked = value; } } public bool DisplayRegionMarkers { get { return displayRegionMarkerCheckBox.Checked; } set { displayRegionMarkerCheckBox.Checked = value; } } public bool DisplayRoadMarkers { get { return displayRoadMarkerCheckBox.Checked; } set { displayRoadMarkerCheckBox.Checked = value; } } public bool DisplayMarkerPoints { get { return displayMarkerPointsCheckBox.Checked; } set { displayMarkerPointsCheckBox.Checked = value; } } public bool DisplayPointLightMarkers { get { return displayPointLightMarkersCheckbox.Checked; } set { displayPointLightMarkersCheckbox.Checked = value; } } public bool DisableAllMarkerPoints { get { return disableAllMarkersDisplayCheckBox.Checked; } set { disableAllMarkersDisplayCheckBox.Checked = value; } } public bool DisplayTerrainDecals { get { return displayTerrainDecalsCheckBox.Checked; } set { displayTerrainDecalsCheckBox.Checked = value; } } public bool CameraFollowsTerrain { get { return cameraFollowsTerrainCheckBox.Checked; } set { cameraFollowsTerrainCheckBox.Checked = value; if (value == true) { cameraStaysAboveTerrainCheckbox.Checked = value; } } } public bool CameraStaysAboveTerrain { get { return cameraStaysAboveTerrainCheckbox.Checked; } set { cameraStaysAboveTerrainCheckbox.Checked = value; } } public float CameraNearDistanceFloat { get { float ret; if (float.TryParse(cameraNearDistanceTextBox.Text, out ret)) { return ret; } else { return 1f; } } set { cameraNearDistanceTextBox.Text = value.ToString(); } } public bool MaxFramesPerSecondEnabled { get { return maxFramesPerSecondCheckBox.Checked; } set { maxFramesPerSecondCheckBox.Checked = value; } } public uint MaxFramesPerSesconduInt { get { uint ret; if (uint.TryParse(maxFPSTextbox.Text, out ret)) { return ret; } else { return 10; } } set { maxFPSTextbox.Text = value.ToString(); } } public bool LockCameraToObject { get { return lockCameraToObjectCheckbox.Checked; } set { lockCameraToObjectCheckbox.Checked = value; } } public bool DisableVideoPlayback { get { return disableVideoPlaybackCheckbox.Checked; } set { disableVideoPlaybackCheckbox.Checked = value; } } #endregion View Panel #region AutoSave Panel public bool AutoSaveEnabled { get { return autoSaveCheckBox.Checked; } set { autoSaveCheckBox.Checked = value; } } public uint AutoSaveTimeuInt { get { uint i; if (uint.TryParse(autoSaveTimeTextBox.Text, out i)) { return i; } else { return (uint)30; } } set { autoSaveTimeTextBox.Text = value.ToString(); } } #endregion AutoSave Panel #region AssetRepositoryPanel #endregion AssetRepositoryPanel #region CameraControlPanel public float CameraDefaultSpeedTextBoxAsFloat { get { float speed; if (float.TryParse(cameraDefaultSpeedTextBox.Text, out speed)) { return speed; } return 0f; } set { cameraDefaultSpeedTextBox.Text = value.ToString(); } } public float CameraSpeedIncrementTextBoxAsFloat { get { float inc; if(float.TryParse(cameraSpeedIncrementTextBox.Text, out inc)) { return inc; } return 0f; } set { cameraSpeedIncrementTextBox.Text = value.ToString(); } } public float PresetCameraSpeed1TextBoxAsFloat { get { float speed; if (float.TryParse(presetCameraSpeed1TextBox.Text, out speed)) { return speed; } return 0f; } set { presetCameraSpeed1TextBox.Text = value.ToString(); } } public float PresetCameraSpeed2TextBoxAsFloat { get { float speed; if (float.TryParse(presetCameraSpeed2TextBox.Text, out speed)) { return speed; } return 0f; } set { presetCameraSpeed2TextBox.Text = value.ToString(); } } public float PresetCameraSpeed3TextBoxAsFloat { get { float speed; if (float.TryParse(presetCameraSpeed3TextBox.Text, out speed)) { return speed; } return 0f; } set { presetCameraSpeed3TextBox.Text = value.ToString(); } } public float PresetCameraSpeed4TextBoxAsFloat { get { float speed; if (float.TryParse(persetCameraSpeed4TextBox.Text, out speed)) { return speed; } return 0f; } set { persetCameraSpeed4TextBox.Text = value.ToString(); } } public bool AccelerateCameraCheckBoxChecked { get { return accelerateCameraCheckBox.Checked; } set { accelerateCameraCheckBox.Checked = value; } } public float CameraAccelerationRateTextBoxAsFloat { get { float acc; if(float.TryParse(cameraAccelerationRateTextBox.Text, out acc)) { return acc; } return 0f; } set { cameraAccelerationRateTextBox.Text = value.ToString(); } } public float CameraAccelerationIncrementTextBoxAsFloat { get { float inc; if (float.TryParse(cameraAccelerationIncrementTextBox.Text, out inc)) { return inc; } return 0f; } set { cameraAccelerationIncrementTextBox.Text = value.ToString(); } } public float PresetCameraAcceleration1TextBoxAsFloat { get { float acc; if (float.TryParse(presetCameraAcceleration1TextBox.Text, out acc)) { return acc; } return 0f; } set { presetCameraAcceleration1TextBox.Text = value.ToString(); } } public float PresetCameraAcceleration2TextBoxAsFloat { get { float acc; if (float.TryParse(presetCameraAcceleration2TextBox.Text, out acc)) { return acc; } return 0f; } set { presetCameraAcceleration2TextBox.Text = value.ToString(); } } public float PresetCameraAcceleration3TextBoxAsFloat { get { float acc; if (float.TryParse(presetCameraAcceleration3TextBox.Text, out acc)) { return acc; } return 0f; } set { presetCameraAcceleration3TextBox.Text = value.ToString(); } } public float PresetCameraAcceleration4TextBoxAsFloat { get { float acc; if (float.TryParse(presetBarCameraAcceleration4TextBox.Text, out acc)) { return acc; } return 0f; } set { presetBarCameraAcceleration4TextBox.Text = value.ToString(); } } public float CameraTurnRateTextBoxAsFloat { get { float dps; if (float.TryParse(cameraTurnRateTextBox.Text, out dps)) { return dps; } return 0f; } set { cameraTurnRateTextBox.Text = value.ToString(); } } public float MouseWheelMultiplierTextBoxAsFloat { get { float mult; if (float.TryParse(mouseWheelMultiplierTextBox.Text, out mult)) { return mult; } return 0f; } set { mouseWheelMultiplierTextBox.Text = value.ToString(); } } public float Preset1MWMTextBoxAsFloat { get { float preset; if (float.TryParse(presetMWM1TextBox.Text, out preset)) { return preset; } return 0f; } set { presetMWM1TextBox.Text = value.ToString(); } } public float Preset2MWMTextBoxAsFloat { get { float preset; if (float.TryParse(presetMWM2TextBox.Text, out preset)) { return preset; } return 0f; } set { presetMWM2TextBox.Text = value.ToString(); } } public float Preset3MWMTextBoxAsFloat { get { float preset; if (float.TryParse(presetMWM3TextBox.Text, out preset)) { return preset; } return 0f; } set { presetMWM3TextBox.Text = value.ToString(); } } public float Preset4MWMTextBoxAsFloat { get { float preset; if (float.TryParse(presetMWM4TextBox.Text, out preset)) { return preset; } return 0f; } set { presetMWM4TextBox.Text = value.ToString(); } } public List<string> RepositoryDirectoryList { get { return repositoryDirectoryList; } set { repositoryDirectoryList = new List<string>(value); repositoryDirectoryListLabel.Text = RepositoryClass.Instance.MakeRepositoryDirectoryListString(repositoryDirectoryList); // filesListBox.Items.Clear(); // foreach (string dir in value) { // filesListBox.Items.Add(dir); // } } } #endregion CameraControlPanel private void floatValidateEvent(object sender, CancelEventArgs e) { if (!ValidityHelperClass.isFloat(((TextBox)sender).Text)) { Color textColor = Color.Red; ((TextBox)sender).ForeColor = textColor; } else { Color textColor = Color.Black; ((TextBox)sender).ForeColor = textColor; } } private void intValidateEvent(object sender, CancelEventArgs e) { if (!ValidityHelperClass.isInt(((TextBox)sender).Text)) { Color textColor = Color.Red; ((TextBox)sender).ForeColor = textColor; } else { Color textColor = Color.Black; ((TextBox)sender).ForeColor = textColor; } } private void uintAutoSaveValidateEvent(object sender, CancelEventArgs e) { if (!ValidityHelperClass.isUint(((TextBox)sender).Text) || uint.Parse(((TextBox)sender).Text) == 0) { Color textColor = Color.Red; ((TextBox)sender).ForeColor = textColor; } else { Color textColor = Color.Black; ((TextBox)sender).ForeColor = textColor; } } private void uintValidateEvent(object sender, CancelEventArgs e) { if (!ValidityHelperClass.isUint(((TextBox)sender).Text)) { Color textColor = Color.Red; ((TextBox)sender).ForeColor = textColor; } else { Color textColor = Color.Black; ((TextBox)sender).ForeColor = textColor; } } public bool okButton_validating() { if (!ValidityHelperClass.isUint(autoSaveTimeTextBox.Text) || uint.Parse(autoSaveTimeTextBox.Text) == 0) { return false; } else { if (!maxFPSValidate()) { return false; } else { if (!ValidityHelperClass.isFloat(cameraNearDistanceTextBox.Text)) { return false; } } } return true; } private void displayRoadMarkerCheckBox_CheckedChange(object sender, EventArgs e) { if (displayRoadMarkerCheckBox.Checked && disableAllMarkersDisplayCheckBox.Checked) { disableAllMarkersDisplayCheckBox.Checked = false; } else { if (!displayMarkerPointsCheckBox.Checked && !displayRoadMarkerCheckBox.Checked && !displayRegionMarkerCheckBox.Checked && !displayPointLightMarkersCheckbox.Checked && !disableAllMarkersDisplayCheckBox.Checked) { disableAllMarkersDisplayCheckBox.Checked = true; } } } private void displayMarkerPointCheckBox_CheckedChange(object sender, EventArgs e) { if (displayMarkerPointsCheckBox.Checked && disableAllMarkersDisplayCheckBox.Checked) { disableAllMarkersDisplayCheckBox.Checked = false; } else { if (!displayMarkerPointsCheckBox.Checked && !displayRoadMarkerCheckBox.Checked && !displayRegionMarkerCheckBox.Checked && !displayPointLightMarkersCheckbox.Checked && !disableAllMarkersDisplayCheckBox.Checked) { disableAllMarkersDisplayCheckBox.Checked = true; } } } private void displayRegionMarkerCheckBox_CheckedChange(object sender, EventArgs e) { if (displayRegionMarkerCheckBox.Checked && disableAllMarkersDisplayCheckBox.Checked) { disableAllMarkersDisplayCheckBox.Checked = false; } else { if (!displayMarkerPointsCheckBox.Checked && !displayRoadMarkerCheckBox.Checked && !displayRegionMarkerCheckBox.Checked && !displayPointLightMarkersCheckbox.Checked && !disableAllMarkersDisplayCheckBox.Checked) { disableAllMarkersDisplayCheckBox.Checked = true; } } } private void displayPointLightMarkerCheckBox_CheckedChanged(object sender, EventArgs e) { if (displayPointLightMarkersCheckbox.Checked && disableAllMarkersDisplayCheckBox.Checked) { disableAllMarkersDisplayCheckBox.Checked = false; } else { if (!displayMarkerPointsCheckBox.Checked && !displayRoadMarkerCheckBox.Checked && !displayRegionMarkerCheckBox.Checked && !displayPointLightMarkersCheckbox.Checked && !disableAllMarkersDisplayCheckBox.Checked) { disableAllMarkersDisplayCheckBox.Checked = true; } } } private void disableAllMarkerDisplayCheckBox_CheckedChanged(object sender, EventArgs e) { if (disableAllMarkersDisplayCheckBox.Checked) { displayMarkerPointsCheckBox.Checked = false; displayRegionMarkerCheckBox.Checked = false; displayRoadMarkerCheckBox.Checked = false; displayPointLightMarkersCheckbox.Checked = false; } } private void disableAllMarkersDisplayCheckBox_Click(object sender, EventArgs e) { if (!disableAllMarkersDisplayCheckBox.Checked) { displayMarkerPointsCheckBox.Checked = true; displayRegionMarkerCheckBox.Checked = true; displayRoadMarkerCheckBox.Checked = true; displayPointLightMarkersCheckbox.Checked = true; } } private void maxFPSTextbox_Validate(object sender, EventArgs e) { maxFPSValidate(); } private bool maxFPSValidate() { if (maxFramesPerSecondCheckBox.Checked) { if (ValidityHelperClass.isUint(maxFPSTextbox.Text) && uint.Parse(maxFPSTextbox.Text) > 0) { return true; } maxFPSTextbox.ForeColor = Color.Red; return false; } return true; } private void cameraFollowsTerrainCheckBox_CheckedChanged(object sender, EventArgs e) { if (cameraFollowsTerrainCheckBox.Checked && !cameraStaysAboveTerrainCheckbox.Checked) { cameraStaysAboveTerrainCheckbox.Checked = true; } } private void maxFramesPerSecondCheckBox_CheckedChanged(object sender, EventArgs e) { if (maxFramesPerSecondCheckBox.Checked) { maxFPSTextbox.Enabled = true; } else { maxFPSTextbox.Enabled = false; } } } }
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net.Sockets; using System.Text; using ToolKit.Validation; namespace ToolKit.Syslog { /// <summary> /// This class is used to send SYSLOG messages to a SYSLOG server. /// </summary> public class SyslogClient { private int _port; private string _server; private bool _useTcp; /// <summary> /// Initializes a new instance of the <see cref="SyslogClient" /> class. /// </summary> public SyslogClient() { Port = 514; Server = "127.0.0.1"; } /// <summary> /// Initializes a new instance of the <see cref="SyslogClient" /> class. /// </summary> /// <param name="server">The SYSLOG server to communicate with.</param> public SyslogClient(string server) { Port = 514; Server = server; } /// <summary> /// Initializes a new instance of the <see cref="SyslogClient" /> class. /// </summary> /// <param name="server">The SYSLOG server to communicate with.</param> /// <param name="port">An integer that contains the port number on the SYSLOG server.</param> public SyslogClient(string server, int port) { Port = port; Server = server; } /// <summary> /// Gets or sets a value indicating whether to include process info in message that is sent /// to the SYSLOG server. /// </summary> /// <value> /// <c>true</c> if process is to be included; otherwise, <c>false</c>. The default value is true. /// </value> public bool IncludeProcessInfo { get; set; } = true; /// <summary> /// Gets or sets the port to communicate with. /// </summary> public int Port { get => _port; set { if ((value < 0) || (value > 65535)) { throw new ArgumentOutOfRangeException( nameof(value), "Valid port numbers are between 0 and 65535"); } _port = value; } } /// <summary> /// Gets or sets the SYSLOG server to communicate with. /// </summary> public string Server { get => _server; set { Check.NotNull(value, nameof(value)); Check.NotEmpty(value, "The value specified for a set operation is equal to Empty."); _server = value.Trim(); } } /// <summary> /// Sends the message to the SYSLOG server. /// </summary> /// <param name="message">The SYSLOG message.</param> public void Send(IMessage message) { Check.NotNull(message, nameof(message)); if (_useTcp) { var client = new TcpClient(_server, _port); using (var write = new StreamWriter(client.GetStream())) { write.Write(PrepareMessageToSend(message)); } client.Close(); client.Dispose(); } else { var bytesToSend = Encoding.ASCII.GetBytes(PrepareMessageToSend(message)); using (var client = new UdpClient(_server, _port)) { client.Send(bytesToSend, bytesToSend.Length); } } } /// <summary> /// Uses TCP for communication with SYSLOG server. /// </summary> /// <returns>This client configured to use TCP.</returns> public SyslogClient UseTcp() { _useTcp = true; return this; } /// <summary> /// Uses UDP for communication with SYSLOG server. /// </summary> /// <returns>This client configured to use UDP.</returns> public SyslogClient UseUdp() { _useTcp = false; return this; } [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Exposed Only For Unit Testing")] internal static string TruncateTagIfNeeded(string tag, string processID) { if (tag.Length > 32 - processID.Length) { tag = tag.Substring(0, 32 - processID.Length); } return $"{tag}{processID}: "; } private string PrepareMessageToSend(IMessage message) { // The PRI value is calculated by first multiplying the Facility number by 8 and then // adding the numerical value of the Severity. For example, a kernel message // (Facility=0) with a Severity of Emergency (Severity=0) would have a Priority value of // 0. Also, a "Local Use 4" message (Facility=20) with a Severity of Notice (Severity=5) // would have a Priority value of 165. var pri = ((int)message.Facility * 8) + (int)message.Level; // The TIMESTAMP will be the current local time of the sender. Single digits in the date // (5 in this case) are preceded by a space in the TIMESTAMP format. var timestamp = DateTime.Now.ToString("MMM dd HH:mm:ss", CultureInfo.InvariantCulture); // The HOSTNAME will be the name of the device, as it is known by the relay. If the name // cannot be determined, the IP address of the device will be used. var hostname = Environment.MachineName.ToLower(CultureInfo.CurrentCulture); // The MSG part has two fields known as the TAG field and the CONTENT field. The value // in the TAG field will be the name of the program or process that generated the // message. The TAG is a string of alphanumeric characters that MUST NOT exceed 32 // characters. The CONTENT contains the details of the message. This has traditionally // been a free form message that gives some detailed information of the event. var tag = string.Empty; if (IncludeProcessInfo) { tag = Process.GetCurrentProcess().ProcessName; var processID = $"[{Process.GetCurrentProcess().Id}]"; tag = TruncateTagIfNeeded(tag, processID); } var msg = tag + message.Text; // The SYSLOG message is transmitted: <PRI>TIMESTAMP HOSTNAME MSG / \ TAG CONTENT // // <34>Oct 11 22:14:15 mymachine su: 'su root' failed for lonvick on /dev/pts/8 return $"<{pri}>{timestamp} {hostname} {msg}\n"; } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace IO.Swagger.Model { /// <summary> /// /// </summary> [DataContract] public partial class PrivateIndividualName : IEquatable<PrivateIndividualName> { [JsonConverter(typeof(StringEnumConverter))] public enum GenderEnum { [EnumMember(Value = "Male")] Male, [EnumMember(Value = "Female")] Female, [EnumMember(Value = "Not Specified")] NotSpecified } /// <summary> /// Gets or Sets Gender /// </summary> [DataMember(Name="gender", EmitDefaultValue=false)] public GenderEnum? Gender { get; set; } /// <summary> /// Initializes a new instance of the <see cref="PrivateIndividualName" /> class. /// Initializes a new instance of the <see cref="PrivateIndividualName" />class. /// </summary> /// <param name="Forename">Forename (required).</param> /// <param name="MiddleName">MiddleName.</param> /// <param name="Surname">Surname (required).</param> /// <param name="Dob">Dob (required).</param> /// <param name="Gender">Gender.</param> /// <param name="PhoneNumber">PhoneNumber (required).</param> /// <param name="Address">Address (required).</param> public PrivateIndividualName(string Forename = null, string MiddleName = null, string Surname = null, string Dob = null, GenderEnum? Gender = null, string PhoneNumber = null, string Address = null) { // to ensure "Forename" is required (not null) if (Forename == null) { throw new InvalidDataException("Forename is a required property for PrivateIndividualName and cannot be null"); } else { this.Forename = Forename; } // to ensure "Surname" is required (not null) if (Surname == null) { throw new InvalidDataException("Surname is a required property for PrivateIndividualName and cannot be null"); } else { this.Surname = Surname; } // to ensure "Dob" is required (not null) if (Dob == null) { throw new InvalidDataException("Dob is a required property for PrivateIndividualName and cannot be null"); } else { this.Dob = Dob; } // to ensure "PhoneNumber" is required (not null) if (PhoneNumber == null) { throw new InvalidDataException("PhoneNumber is a required property for PrivateIndividualName and cannot be null"); } else { this.PhoneNumber = PhoneNumber; } // to ensure "Address" is required (not null) if (Address == null) { throw new InvalidDataException("Address is a required property for PrivateIndividualName and cannot be null"); } else { this.Address = Address; } this.MiddleName = MiddleName; this.Gender = Gender; } /// <summary> /// Gets or Sets Forename /// </summary> [DataMember(Name="forename", EmitDefaultValue=false)] public string Forename { get; set; } /// <summary> /// Gets or Sets MiddleName /// </summary> [DataMember(Name="middle_name", EmitDefaultValue=false)] public string MiddleName { get; set; } /// <summary> /// Gets or Sets Surname /// </summary> [DataMember(Name="surname", EmitDefaultValue=false)] public string Surname { get; set; } /// <summary> /// Gets or Sets Dob /// </summary> [DataMember(Name="dob", EmitDefaultValue=false)] public string Dob { get; set; } /// <summary> /// Gets or Sets PhoneNumber /// </summary> [DataMember(Name="phone_number", EmitDefaultValue=false)] public string PhoneNumber { get; set; } /// <summary> /// Gets or Sets Address /// </summary> [DataMember(Name="address", EmitDefaultValue=false)] public string Address { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PrivateIndividualName {\n"); sb.Append(" Forename: ").Append(Forename).Append("\n"); sb.Append(" MiddleName: ").Append(MiddleName).Append("\n"); sb.Append(" Surname: ").Append(Surname).Append("\n"); sb.Append(" Dob: ").Append(Dob).Append("\n"); sb.Append(" Gender: ").Append(Gender).Append("\n"); sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n"); sb.Append(" Address: ").Append(Address).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as PrivateIndividualName); } /// <summary> /// Returns true if PrivateIndividualName instances are equal /// </summary> /// <param name="other">Instance of PrivateIndividualName to be compared</param> /// <returns>Boolean</returns> public bool Equals(PrivateIndividualName other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Forename == other.Forename || this.Forename != null && this.Forename.Equals(other.Forename) ) && ( this.MiddleName == other.MiddleName || this.MiddleName != null && this.MiddleName.Equals(other.MiddleName) ) && ( this.Surname == other.Surname || this.Surname != null && this.Surname.Equals(other.Surname) ) && ( this.Dob == other.Dob || this.Dob != null && this.Dob.Equals(other.Dob) ) && ( this.Gender == other.Gender || this.Gender != null && this.Gender.Equals(other.Gender) ) && ( this.PhoneNumber == other.PhoneNumber || this.PhoneNumber != null && this.PhoneNumber.Equals(other.PhoneNumber) ) && ( this.Address == other.Address || this.Address != null && this.Address.Equals(other.Address) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Forename != null) hash = hash * 59 + this.Forename.GetHashCode(); if (this.MiddleName != null) hash = hash * 59 + this.MiddleName.GetHashCode(); if (this.Surname != null) hash = hash * 59 + this.Surname.GetHashCode(); if (this.Dob != null) hash = hash * 59 + this.Dob.GetHashCode(); if (this.Gender != null) hash = hash * 59 + this.Gender.GetHashCode(); if (this.PhoneNumber != null) hash = hash * 59 + this.PhoneNumber.GetHashCode(); if (this.Address != null) hash = hash * 59 + this.Address.GetHashCode(); return hash; } } } }
/* * 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 MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using System; using System.Reflection; namespace OpenSim.Data.MySQL { public class MySQLGroupsData : IGroupsData { private MySqlGroupsGroupsHandler m_Groups; private MySqlGroupsMembershipHandler m_Membership; private MySqlGroupsRolesHandler m_Roles; private MySqlGroupsRoleMembershipHandler m_RoleMembership; private MySqlGroupsInvitesHandler m_Invites; private MySqlGroupsNoticesHandler m_Notices; private MySqlGroupsPrincipalsHandler m_Principals; public MySQLGroupsData(string connectionString, string realm) { m_Groups = new MySqlGroupsGroupsHandler(connectionString, realm + "_groups", realm + "_Store"); m_Membership = new MySqlGroupsMembershipHandler(connectionString, realm + "_membership"); m_Roles = new MySqlGroupsRolesHandler(connectionString, realm + "_roles"); m_RoleMembership = new MySqlGroupsRoleMembershipHandler(connectionString, realm + "_rolemembership"); m_Invites = new MySqlGroupsInvitesHandler(connectionString, realm + "_invites"); m_Notices = new MySqlGroupsNoticesHandler(connectionString, realm + "_notices"); m_Principals = new MySqlGroupsPrincipalsHandler(connectionString, realm + "_principals"); } #region groups table public bool StoreGroup(GroupData data) { return m_Groups.Store(data); } public GroupData RetrieveGroup(UUID groupID) { GroupData[] groups = m_Groups.Get("GroupID", groupID.ToString()); if (groups.Length > 0) return groups[0]; return null; } public GroupData RetrieveGroup(string name) { GroupData[] groups = m_Groups.Get("Name", name); if (groups.Length > 0) return groups[0]; return null; } public GroupData[] RetrieveGroups(string pattern) { if (string.IsNullOrEmpty(pattern)) pattern = "1"; else pattern = string.Format("Name LIKE '%{0}%'", MySqlHelper.EscapeString(pattern)); return m_Groups.Get(string.Format("ShowInList=1 AND ({0}) ORDER BY Name LIMIT 100", pattern)); } public bool DeleteGroup(UUID groupID) { return m_Groups.Delete("GroupID", groupID.ToString()); } public int GroupsCount() { return (int)m_Groups.GetCount("Location=\"\""); } #endregion #region membership table public MembershipData[] RetrieveMembers(UUID groupID) { return m_Membership.Get("GroupID", groupID.ToString()); } public MembershipData RetrieveMember(UUID groupID, string pricipalID) { MembershipData[] m = m_Membership.Get(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), pricipalID }); if (m != null && m.Length > 0) return m[0]; return null; } public MembershipData[] RetrieveMemberships(string pricipalID) { return m_Membership.Get("PrincipalID", pricipalID.ToString()); } public bool StoreMember(MembershipData data) { return m_Membership.Store(data); } public bool DeleteMember(UUID groupID, string pricipalID) { return m_Membership.Delete(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), pricipalID }); } public int MemberCount(UUID groupID) { return (int)m_Membership.GetCount("GroupID", groupID.ToString()); } #endregion #region roles table public bool StoreRole(RoleData data) { return m_Roles.Store(data); } public RoleData RetrieveRole(UUID groupID, UUID roleID) { RoleData[] data = m_Roles.Get(new string[] { "GroupID", "RoleID" }, new string[] { groupID.ToString(), roleID.ToString() }); if (data != null && data.Length > 0) return data[0]; return null; } public RoleData[] RetrieveRoles(UUID groupID) { //return m_Roles.RetrieveRoles(groupID); return m_Roles.Get("GroupID", groupID.ToString()); } public bool DeleteRole(UUID groupID, UUID roleID) { return m_Roles.Delete(new string[] { "GroupID", "RoleID" }, new string[] { groupID.ToString(), roleID.ToString() }); } public int RoleCount(UUID groupID) { return (int)m_Roles.GetCount("GroupID", groupID.ToString()); } #endregion #region rolememberhip table public RoleMembershipData[] RetrieveRolesMembers(UUID groupID) { RoleMembershipData[] data = m_RoleMembership.Get("GroupID", groupID.ToString()); return data; } public RoleMembershipData[] RetrieveRoleMembers(UUID groupID, UUID roleID) { RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID" }, new string[] { groupID.ToString(), roleID.ToString() }); return data; } public RoleMembershipData[] RetrieveMemberRoles(UUID groupID, string principalID) { RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), principalID.ToString() }); return data; } public RoleMembershipData RetrieveRoleMember(UUID groupID, UUID roleID, string principalID) { RoleMembershipData[] data = m_RoleMembership.Get(new string[] { "GroupID", "RoleID", "PrincipalID" }, new string[] { groupID.ToString(), roleID.ToString(), principalID.ToString() }); if (data != null && data.Length > 0) return data[0]; return null; } public int RoleMemberCount(UUID groupID, UUID roleID) { return (int)m_RoleMembership.GetCount(new string[] { "GroupID", "RoleID" }, new string[] { groupID.ToString(), roleID.ToString() }); } public bool StoreRoleMember(RoleMembershipData data) { return m_RoleMembership.Store(data); } public bool DeleteRoleMember(RoleMembershipData data) { return m_RoleMembership.Delete(new string[] { "GroupID", "RoleID", "PrincipalID"}, new string[] { data.GroupID.ToString(), data.RoleID.ToString(), data.PrincipalID }); } public bool DeleteMemberAllRoles(UUID groupID, string principalID) { return m_RoleMembership.Delete(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), principalID }); } #endregion #region principals table public bool StorePrincipal(PrincipalData data) { return m_Principals.Store(data); } public PrincipalData RetrievePrincipal(string principalID) { PrincipalData[] p = m_Principals.Get("PrincipalID", principalID); if (p != null && p.Length > 0) return p[0]; return null; } public bool DeletePrincipal(string principalID) { return m_Principals.Delete("PrincipalID", principalID); } #endregion #region invites table public bool StoreInvitation(InvitationData data) { return m_Invites.Store(data); } public InvitationData RetrieveInvitation(UUID inviteID) { InvitationData[] invites = m_Invites.Get("InviteID", inviteID.ToString()); if (invites != null && invites.Length > 0) return invites[0]; return null; } public InvitationData RetrieveInvitation(UUID groupID, string principalID) { InvitationData[] invites = m_Invites.Get(new string[] { "GroupID", "PrincipalID" }, new string[] { groupID.ToString(), principalID }); if (invites != null && invites.Length > 0) return invites[0]; return null; } public bool DeleteInvite(UUID inviteID) { return m_Invites.Delete("InviteID", inviteID.ToString()); } public void DeleteOldInvites() { m_Invites.DeleteOld(); } #endregion #region notices table public bool StoreNotice(NoticeData data) { return m_Notices.Store(data); } public NoticeData RetrieveNotice(UUID noticeID) { NoticeData[] notices = m_Notices.Get("NoticeID", noticeID.ToString()); if (notices != null && notices.Length > 0) return notices[0]; return null; } public NoticeData[] RetrieveNotices(UUID groupID) { NoticeData[] notices = m_Notices.Get("GroupID", groupID.ToString()); return notices; } public bool DeleteNotice(UUID noticeID) { return m_Notices.Delete("NoticeID", noticeID.ToString()); } public void DeleteOldNotices() { m_Notices.DeleteOld(); } #endregion #region combinations public MembershipData RetrievePrincipalGroupMembership(string principalID, UUID groupID) { // TODO return null; } public MembershipData[] RetrievePrincipalGroupMemberships(string principalID) { // TODO return null; } #endregion } public class MySqlGroupsGroupsHandler : MySQLGenericTableHandler<GroupData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsGroupsHandler(string connectionString, string realm, string store) : base(connectionString, realm, store) { } } public class MySqlGroupsMembershipHandler : MySQLGenericTableHandler<MembershipData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsMembershipHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } } public class MySqlGroupsRolesHandler : MySQLGenericTableHandler<RoleData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsRolesHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } } public class MySqlGroupsRoleMembershipHandler : MySQLGenericTableHandler<RoleMembershipData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsRoleMembershipHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } } public class MySqlGroupsInvitesHandler : MySQLGenericTableHandler<InvitationData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsInvitesHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } public void DeleteOld() { uint now = (uint)Util.UnixTimeSinceEpoch(); using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = String.Format("delete from {0} where TMStamp < ?tstamp", m_Realm); cmd.Parameters.AddWithValue("?tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old ExecuteNonQuery(cmd); } } } public class MySqlGroupsNoticesHandler : MySQLGenericTableHandler<NoticeData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsNoticesHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } public void DeleteOld() { uint now = (uint)Util.UnixTimeSinceEpoch(); using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = String.Format("delete from {0} where TMStamp < ?tstamp", m_Realm); cmd.Parameters.AddWithValue("?tstamp", now - 14 * 24 * 60 * 60); // > 2 weeks old ExecuteNonQuery(cmd); } } } public class MySqlGroupsPrincipalsHandler : MySQLGenericTableHandler<PrincipalData> { protected override Assembly Assembly { // WARNING! Moving migrations to this assembly!!! get { return GetType().Assembly; } } public MySqlGroupsPrincipalsHandler(string connectionString, string realm) : base(connectionString, realm, string.Empty) { } } }
using System; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml.Linq; using Skybrud.Social.Interfaces; using Skybrud.Social.Json; namespace Skybrud.Social { public static class SocialUtils { /// <summary> /// Gets the assembly version as a string. /// </summary> public static string GetVersion() { return typeof (SocialUtils).Assembly.GetName().Version.ToString(); } /// <summary> /// Gets the file version as a string. /// </summary> /// <returns></returns> public static string GetFileVersion() { Assembly assembly = typeof(SocialUtils).Assembly; return FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; } /// <summary> /// Gets the amount of days between the date of this build and the date the project was started - that is the 30th of July, 2012. /// </summary> public static int GetDaysSinceStart() { // Get the third bit as a string string str = GetFileVersion().Split('.')[2]; // Parse the string into an integer return Int32.Parse(str); } /// <summary> /// Gets the date of this build of Skybrud.Social. /// </summary> public static DateTime GetBuildDate() { return new DateTime(2012, 7, 30).AddDays(GetDaysSinceStart()); } /// <summary> /// Gets the build number of the day. This is mostly used for internal /// purposes to distinguish builds with the same assembly version. /// </summary> public static int GetBuildNumber() { // Get the fourth bit as a string string str = GetFileVersion().Split('.')[3]; // Parse the string into an integer return Int32.Parse(str); } #region HTTP helpers private static HttpWebResponse DoHttpRequest(string url, string method, NameValueCollection queryString, NameValueCollection postData) { // TODO: Decide better naming of method // Merge the query string url = new UriBuilder(url).MergeQueryString(queryString).ToString(); // Initialize the request HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); // Set the method request.Method = method; // Add the request body (if a POST request) if (method == "POST" && postData != null && postData.Count > 0) { string dataString = NameValueCollectionToQueryString(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = dataString.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(Encoding.UTF8.GetBytes(dataString), 0, dataString.Length); } } // Get the response try { return (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { return (HttpWebResponse)ex.Response; } } #region GET public static HttpWebResponse DoHttpGetRequest(string baseUrl, NameValueCollection queryString = null) { return DoHttpRequest(baseUrl, "GET", queryString, null); } public static string DoHttpGetRequestAndGetBodyAsString(string url, NameValueCollection queryString = null) { return DoHttpGetRequest(url, queryString).GetAsString(); } public static IJsonObject DoHttpGetRequestAndGetBodyAsJson(string url, NameValueCollection queryString = null) { return DoHttpGetRequest(url, queryString).GetAsJson(); } public static JsonObject DoHttpGetRequestAndGetBodyAsJsonObject(string url, NameValueCollection queryString = null) { return DoHttpGetRequest(url, queryString).GetAsJsonObject(); } public static JsonArray DoHttpGetRequestAndGetBodyAsJsonArray(string url, NameValueCollection queryString = null) { return DoHttpGetRequest(url, queryString).GetAsJsonArray(); } public static XElement DoHttpGetRequestAndGetBodyAsXml(string url, NameValueCollection queryString = null) { HttpWebResponse response = DoHttpGetRequest(url, queryString); Stream stream = response.GetResponseStream(); return stream == null ? null : XElement.Parse(new StreamReader(stream).ReadToEnd()); } #endregion #region POST public static HttpWebResponse DoHttpPostRequest(string baseUrl, NameValueCollection queryString, NameValueCollection postData) { return DoHttpRequest(baseUrl, "POST", queryString, postData); } public static string DoHttpPostRequestAndGetBodyAsString(string url, NameValueCollection queryString = null, NameValueCollection postData = null) { return DoHttpPostRequest(url, queryString, postData).GetAsString(); } public static IJsonObject DoHttpPostRequestAndGetBodyAsJson(string url, NameValueCollection queryString = null, NameValueCollection postData = null) { return DoHttpPostRequest(url, queryString, postData).GetAsJson(); } public static JsonObject DoHttpPostRequestAndGetBodyAsJsonObject(string url, NameValueCollection queryString = null, NameValueCollection postData = null) { return DoHttpPostRequest(url, queryString, postData).GetAsJsonObject(); } public static JsonArray DoHttpPostRequestAndGetBodyAsJsonArray(string url, NameValueCollection queryString = null, NameValueCollection postData = null) { return DoHttpPostRequest(url, queryString, postData).GetAsJsonArray(); } public static XElement DoHttpPostRequestAndGetBodyAsXml(string url, NameValueCollection queryString = null, NameValueCollection postData = null) { HttpWebResponse response = DoHttpPostRequest(url, queryString, postData); Stream stream = response.GetResponseStream(); return stream == null ? null : XElement.Parse(new StreamReader(stream).ReadToEnd()); } #endregion #endregion #region Other public static string CamelCaseToUnderscore(Enum e) { return CamelCaseToUnderscore(e.ToString()); } public static string CamelCaseToUnderscore(string str) { return Regex.Replace(str, @"(\p{Ll})(\p{Lu})", "$1_$2").ToLower(); } /// <summary> /// Converts the specified <var>NameValueCollection</var> into a query string using the proper encoding. /// </summary> /// <param name="collection">The collection to convert.</param> /// <returns></returns> public static string NameValueCollectionToQueryString(NameValueCollection collection) { return String.Join("&", Array.ConvertAll(collection.AllKeys, key => HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(collection[key]))); } public static string NameValueCollectionToQueryString(NameValueCollection collection, bool includeIfNull) { return String.Join("&", ( from string key in collection.Keys where collection[key] != null || includeIfNull select HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(collection[key]) )); } public static T GetAttributeValue<T>(XElement xElement, string name) { string value = xElement.Attribute(name).Value; return (T)Convert.ChangeType(value, typeof(T)); } public static T GetAttributeValueOrDefault<T>(XElement xElement, string name) { XAttribute attr = xElement.Attribute(name); if (attr == null) return default(T); return (T)Convert.ChangeType(attr.Value, typeof(T)); } public static T GetElementValue<T>(XElement xElement, string name) { string value = xElement.Element(name).Value; return (T)Convert.ChangeType(value, typeof(T)); } public static T GetElementValueOrDefault<T>(XElement xElement, string name) { XElement e = xElement.Element(name); if (e == null) return default(T); return (T)Convert.ChangeType(e.Value, typeof(T)); } #endregion #region Timestamps /// <summary> /// ISO 8601 date format. /// </summary> public const string IsoDateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK"; /// <summary> /// Returns the current unix timestamp which is defined as the amount of seconds /// since the start of the Unix epoch - 1st of January, 1970 - 00:00:00 GMT. /// </summary> public static long GetCurrentUnixTimestamp() { return (long) Math.Floor(GetCurrentUnixTimestampAsDouble()); } /// <summary> /// Returns the current unix timestamp which is defined as the amount of seconds /// since the start of the Unix epoch - 1st of January, 1970 - 00:00:00 GMT. /// </summary> public static double GetCurrentUnixTimestampAsDouble() { return (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; } public static DateTime GetDateTimeFromUnixTime(int timestamp) { return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp); } public static DateTime GetDateTimeFromUnixTime(double timestamp) { return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp); } public static DateTime GetDateTimeFromUnixTime(long timestamp) { return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp); } public static DateTime GetDateTimeFromUnixTime(string timestamp) { return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Int64.Parse(timestamp)); } public static long GetUnixTimeFromDateTime(DateTime dateTime) { return (int) (dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; } #endregion #region Locations and distance /// <summary> /// Calculates the distance in meters between two GPS locations. /// </summary> /// <param name="loc1">The first location.</param> /// <param name="loc2">The second location.</param> public static double GetDistance(ILocation loc1, ILocation loc2) { return GetDistance(loc1.Latitude, loc1.Longitude, loc2.Latitude, loc2.Longitude); } /// <summary> /// Calculates the distance in meters between two GPS locations. /// </summary> public static double GetDistance(double lat1, double lng1, double lat2, double lng2) { // http://stackoverflow.com/a/3440123 double ee = (Math.PI * lat1 / 180); double f = (Math.PI * lng1 / 180); double g = (Math.PI * lat2 / 180); double h = (Math.PI * lng2 / 180); double i = (Math.Cos(ee) * Math.Cos(g) * Math.Cos(f) * Math.Cos(h) + Math.Cos(ee) * Math.Sin(f) * Math.Cos(g) * Math.Sin(h) + Math.Sin(ee) * Math.Sin(g)); double j = (Math.Acos(i)); return (6371 * j) * 1000d; } #endregion #region Enums public static T ParseEnum<T>(string str) where T : struct { // Check whether the type of T is an enum if (!typeof(T).IsEnum) throw new ArgumentException("Generic type T must be an enum"); // Parse the enum foreach (string name in Enum.GetNames(typeof(T))) { if (name.ToLowerInvariant() == str.ToLowerInvariant()) { return (T)Enum.Parse(typeof(T), str, true); } } throw new Exception("Unable to parse enum of type " + typeof(T).Name); } public static T ParseEnum<T>(string str, T fallback) where T : struct { // Check whether the type of T is an enum if (!typeof(T).IsEnum) throw new ArgumentException("Generic type T must be an enum"); // Parse the enum foreach (string name in Enum.GetNames(typeof(T))) { if (name.ToLowerInvariant() == str.ToLowerInvariant()) { return (T)Enum.Parse(typeof(T), str, true); } } return fallback; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.IO.Tests { public class File_Exists : FileSystemTest { #region Utilities public virtual bool Exists(string path) { return File.Exists(path); } #endregion #region UniversalTests [Fact] public void NullAsPath_ReturnsFalse() { Assert.False(Exists(null)); } [Fact] public void EmptyAsPath_ReturnsFalse() { Assert.False(Exists(string.Empty)); } [Fact] public void NonExistentValidPath_ReturnsFalse() { Assert.All((IOInputs.GetValidPathComponentNames()), (path) => { Assert.False(Exists(path), path); }); } [Fact] public void ValidPathExists_ReturnsTrue() { Assert.All((IOInputs.GetValidPathComponentNames()), (component) => { string path = Path.Combine(TestDirectory, component); FileInfo testFile = new FileInfo(path); testFile.Create().Dispose(); Assert.True(Exists(path)); }); } [Theory, MemberData(nameof(PathsWithInvalidCharacters))] public void PathWithInvalidCharactersAsPath_ReturnsFalse(string invalidPath) { // Checks that errors aren't thrown when calling Exists() on paths with impossible to create characters Assert.False(Exists(invalidPath)); Assert.False(Exists("..")); Assert.False(Exists(".")); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.True(Exists(IOServices.RemoveTrailingSlash(path))); Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path)))); Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path)))); } [Fact] public void PathEndsInTrailingSlash() { string path = GetTestFilePath() + Path.DirectorySeparatorChar; Assert.False(Exists(path)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void PathEndsInAltTrailingSlash_Windows() { string path = GetTestFilePath() + Path.DirectorySeparatorChar; Assert.False(Exists(path)); } [Fact] public void PathEndsInTrailingSlash_AndExists() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.False(Exists(path + Path.DirectorySeparatorChar)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void PathEndsInAltTrailingSlash_AndExists_Windows() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.False(Exists(path + Path.DirectorySeparatorChar)); } [Fact] public void PathAlreadyExistsAsDirectory() { string path = GetTestFilePath(); DirectoryInfo testDir = Directory.CreateDirectory(path); Assert.False(Exists(IOServices.RemoveTrailingSlash(path))); Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path)))); Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path)))); } [Fact] public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow() { Assert.All((IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath())), (path) => { Assert.False(Exists(path)); }); } [Fact] public void DirectoryLongerThanMaxPathAsPath_DoesntThrow() { Assert.All((IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath())), (path) => { Assert.False(Exists(path), path); }); } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void SymLinksMayExistIndependentlyOfTarget() { var path = GetTestFilePath(); var linkPath = GetTestFilePath(); File.Create(path).Dispose(); Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false)); // Both the symlink and the target exist Assert.True(File.Exists(path), "path should exist"); Assert.True(File.Exists(linkPath), "linkPath should exist"); // Delete the target. The symlink should still exist File.Delete(path); Assert.False(File.Exists(path), "path should now not exist"); Assert.True(File.Exists(linkPath), "linkPath should still exist"); // Now delete the symlink. File.Delete(linkPath); Assert.False(File.Exists(linkPath), "linkPath should no longer exist"); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix equivalent tested already in CreateDirectory public void WindowsNonSignificantWhiteSpaceAsPath_ReturnsFalse() { // Checks that errors aren't thrown when calling Exists() on impossible paths Assert.All((IOInputs.GetWhiteSpace()), (component) => { Assert.False(Exists(component)); }); } [Fact] [PlatformSpecific(CaseInsensitivePlatforms)] public void DoesCaseInsensitiveInvariantComparions() { FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); Assert.True(Exists(testFile.FullName)); Assert.True(Exists(testFile.FullName.ToUpperInvariant())); Assert.True(Exists(testFile.FullName.ToLowerInvariant())); } [Fact] [PlatformSpecific(CaseSensitivePlatforms)] public void DoesCaseSensitiveComparions() { FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); Assert.True(Exists(testFile.FullName)); Assert.False(Exists(testFile.FullName.ToUpperInvariant())); Assert.False(Exists(testFile.FullName.ToLowerInvariant())); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // In Windows, trailing whitespace in a path is trimmed public void TrimTrailingWhitespacePath() { FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); Assert.All((IOInputs.GetWhiteSpace()), (component) => { Assert.True(Exists(testFile.FullName + component)); // string concat in case Path.Combine() trims whitespace before Exists gets to it }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // alternate data stream public void PathWithAlternateDataStreams_ReturnsFalse() { Assert.All((IOInputs.GetPathsWithAlternativeDataStreams()), (component) => { Assert.False(Exists(component)); }); } [Fact] [OuterLoop] [PlatformSpecific(TestPlatforms.Windows)] // device names public void PathWithReservedDeviceNameAsPath_ReturnsFalse() { Assert.All((IOInputs.GetPathsWithReservedDeviceNames()), (component) => { Assert.False(Exists(component)); }); } [Fact] public void UncPathWithoutShareNameAsPath_ReturnsFalse() { Assert.All((IOInputs.GetUncPathsWithoutShareName()), (component) => { Assert.False(Exists(component)); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // max directory length not fixed on Unix public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse() { Assert.All((IOInputs.GetPathsWithComponentLongerThanMaxComponent()), (component) => { Assert.False(Exists(component)); }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes public void FalseForNonRegularFile() { string fileName = GetTestFilePath(); Assert.Equal(0, mkfifo(fileName, 0)); Assert.True(File.Exists(fileName)); } #endregion } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1 using System.Numerics; #endif using System.Text; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JTokenWriterTest : TestFixtureBase { [Test] public void ValueFormatting() { byte[] data = Encoding.UTF8.GetBytes("Hello world."); JToken root; using (JTokenWriter jsonWriter = new JTokenWriter()) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteValue(data); jsonWriter.WriteEndArray(); root = jsonWriter.Token; } CustomAssert.IsInstanceOfType(typeof(JArray), root); Assert.AreEqual(13, root.Children().Count()); Assert.AreEqual("@", (string)root[0]); Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]); Assert.AreEqual(true, (bool)root[2]); Assert.AreEqual(10, (int)root[3]); Assert.AreEqual(10.99, (double)root[4]); Assert.AreEqual(0.99, (double)root[5]); Assert.AreEqual(0.000000000000000001d, (double)root[6]); Assert.AreEqual(0.000000000000000001m, (decimal)root[7]); Assert.AreEqual(null, (string)root[8]); Assert.AreEqual("This is a string.", (string)root[9]); Assert.AreEqual(null, ((JValue)root[10]).Value); Assert.AreEqual(null, ((JValue)root[11]).Value); Assert.AreEqual(data, (byte[])root[12]); } [Test] public void State() { using (JsonWriter jsonWriter = new JTokenWriter()) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); #if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1 jsonWriter.WriteValue(new BigInteger(123)); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); #endif jsonWriter.WriteValue(new byte[0]); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); } } [Test] public void CurrentToken() { using (JTokenWriter jsonWriter = new JTokenWriter()) { Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual(null, jsonWriter.CurrentToken); jsonWriter.WriteStartObject(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual(jsonWriter.Token, jsonWriter.CurrentToken); JObject o = (JObject)jsonWriter.Token; jsonWriter.WritePropertyName("CPU"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual(o.Property("CPU"), jsonWriter.CurrentToken); jsonWriter.WriteValue("Intel"); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual(o["CPU"], jsonWriter.CurrentToken); jsonWriter.WritePropertyName("Drives"); Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); Assert.AreEqual(o.Property("Drives"), jsonWriter.CurrentToken); jsonWriter.WriteStartArray(); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual(o["Drives"], jsonWriter.CurrentToken); JArray a = (JArray)jsonWriter.CurrentToken; jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); #if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1 jsonWriter.WriteValue(new BigInteger(123)); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); #endif jsonWriter.WriteValue(new byte[0]); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); jsonWriter.WriteEnd(); Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); Assert.AreEqual(a, jsonWriter.CurrentToken); jsonWriter.WriteEndObject(); Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); Assert.AreEqual(o, jsonWriter.CurrentToken); } } [Test] public void WriteComment() { JTokenWriter writer = new JTokenWriter(); writer.WriteStartArray(); writer.WriteComment("fail"); writer.WriteEndArray(); StringAssert.AreEqual(@"[ /*fail*/]", writer.Token.ToString()); } #if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1 [Test] public void WriteBigInteger() { JTokenWriter writer = new JTokenWriter(); writer.WriteStartArray(); writer.WriteValue(new BigInteger(123)); writer.WriteEndArray(); JValue i = (JValue)writer.Token[0]; Assert.AreEqual(new BigInteger(123), i.Value); Assert.AreEqual(JTokenType.Integer, i.Type); StringAssert.AreEqual(@"[ 123 ]", writer.Token.ToString()); } #endif [Test] public void WriteRaw() { JTokenWriter writer = new JTokenWriter(); writer.WriteStartArray(); writer.WriteRaw("fail"); writer.WriteRaw("fail"); writer.WriteEndArray(); // this is a bug. write raw shouldn't be autocompleting like this // hard to fix without introducing Raw and RawValue token types // meh StringAssert.AreEqual(@"[ fail, fail ]", writer.Token.ToString()); } [Test] public void WriteTokenWithParent() { JObject o = new JObject { ["prop1"] = new JArray(1), ["prop2"] = 1 }; JTokenWriter writer = new JTokenWriter(); writer.WriteStartArray(); writer.WriteToken(o.CreateReader()); Assert.AreEqual(WriteState.Array, writer.WriteState); writer.WriteEndArray(); Console.WriteLine(writer.Token.ToString()); StringAssert.AreEqual(@"[ { ""prop1"": [ 1 ], ""prop2"": 1 } ]", writer.Token.ToString()); } [Test] public void WriteTokenWithPropertyParent() { JValue v = new JValue(1); JTokenWriter writer = new JTokenWriter(); writer.WriteStartObject(); writer.WritePropertyName("Prop1"); writer.WriteToken(v.CreateReader()); Assert.AreEqual(WriteState.Object, writer.WriteState); writer.WriteEndObject(); StringAssert.AreEqual(@"{ ""Prop1"": 1 }", writer.Token.ToString()); } [Test] public void WriteValueTokenWithParent() { JValue v = new JValue(1); JTokenWriter writer = new JTokenWriter(); writer.WriteStartArray(); writer.WriteToken(v.CreateReader()); Assert.AreEqual(WriteState.Array, writer.WriteState); writer.WriteEndArray(); StringAssert.AreEqual(@"[ 1 ]", writer.Token.ToString()); } [Test] public void WriteEmptyToken() { JObject o = new JObject(); JsonReader reader = o.CreateReader(); while (reader.Read()) { } JTokenWriter writer = new JTokenWriter(); writer.WriteStartArray(); writer.WriteToken(reader); Assert.AreEqual(WriteState.Array, writer.WriteState); writer.WriteEndArray(); StringAssert.AreEqual(@"[]", writer.Token.ToString()); } [Test] public void WriteRawValue() { JTokenWriter writer = new JTokenWriter(); writer.WriteStartArray(); writer.WriteRawValue("fail"); writer.WriteRawValue("fail"); writer.WriteEndArray(); StringAssert.AreEqual(@"[ fail, fail ]", writer.Token.ToString()); } [Test] public void WriteDuplicatePropertyName() { JTokenWriter writer = new JTokenWriter(); writer.WriteStartObject(); writer.WritePropertyName("prop1"); writer.WriteStartObject(); writer.WriteEndObject(); writer.WritePropertyName("prop1"); writer.WriteStartArray(); writer.WriteEndArray(); writer.WriteEndObject(); StringAssert.AreEqual(@"{ ""prop1"": [] }", writer.Token.ToString()); } [Test] public void DateTimeZoneHandling() { JTokenWriter writer = new JTokenWriter { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); JValue value = (JValue)writer.Token; DateTime dt = (DateTime)value.Value; Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt); } } }