context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// <copyright file="Processing.cs" company="Public Domain"> // Released into the public domain // </copyright> // This file is part of the C# Packet Capture Analyser application. It is // free and unencumbered software released into the public domain as detailed // in the UNLICENSE file in the top level directory of this distribution namespace PacketCaptureAnalyzer.EthernetFrame.IPPacket.IPv4Packet { /// <summary> /// This class provides the IP v4 packet processing /// </summary> public class Processing { /// <summary> /// The object that provides for the logging of debug information /// </summary> private Analysis.DebugInformation theDebugInformation; /// <summary> /// The object that provides for binary reading from the packet capture /// </summary> private System.IO.BinaryReader theBinaryReader; /// <summary> /// The reusable instance of the processing class for ICMP v4 packets /// </summary> private ICMPv4Packet.Processing theICMPv4PacketProcessing; /// <summary> /// The reusable instance of the processing class for IGMP v2 packets /// </summary> private IGMPv2Packet.Processing theIGMPv2PacketProcessing; /// <summary> /// The reusable instance of the processing class for TCP packets /// </summary> private TCPPacket.Processing theTCPPacketProcessing; /// <summary> /// The reusable instance of the processing class for UDP datagrams /// </summary> private UDPDatagram.Processing theUDPDatagramProcessing; /// <summary> /// The reusable instance of the processing class for EIGRP packets /// </summary> private EIGRPPacket.Processing theEIGRPPacketProcessing; /// <summary> /// Initializes a new instance of the Processing class /// </summary> /// <param name="theDebugInformation">The object that provides for the logging of debug information</param> /// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param> /// <param name="performLatencyAnalysisProcessing">Boolean flag that indicates whether to perform latency analysis processing for data read from the packet capture</param> /// <param name="theLatencyAnalysisProcessing">The object that provides the latency analysis processing for data read from the packet capture</param> /// <param name="performBurstAnalysisProcessing">Boolean flag that indicates whether to perform burst analysis processing for data read from the packet capture</param> /// <param name="theBurstAnalysisProcessing">The object that provides the burst analysis processing for data read from the packet capture</param> /// <param name="performTimeAnalysisProcessing">Boolean flag that indicates whether to perform time analysis processing for data read from the packet capture</param> /// <param name="theTimeAnalysisProcessing">The object that provides the time analysis processing for data read from the packet capture</param> /// <param name="useAlternativeSequenceNumber">Boolean flag that indicates whether to use the alternative sequence number in the data read from the packet capture, required for legacy recordings</param> public Processing(Analysis.DebugInformation theDebugInformation, System.IO.BinaryReader theBinaryReader, bool performLatencyAnalysisProcessing, Analysis.LatencyAnalysis.Processing theLatencyAnalysisProcessing, bool performBurstAnalysisProcessing, Analysis.BurstAnalysis.Processing theBurstAnalysisProcessing, bool performTimeAnalysisProcessing, Analysis.TimeAnalysis.Processing theTimeAnalysisProcessing, bool useAlternativeSequenceNumber) { this.theDebugInformation = theDebugInformation; this.theBinaryReader = theBinaryReader; //// Create instances of the processing classes for each protocol this.theICMPv4PacketProcessing = new ICMPv4Packet.Processing(theBinaryReader); this.theIGMPv2PacketProcessing = new IGMPv2Packet.Processing(theBinaryReader); this.theTCPPacketProcessing = new TCPPacket.Processing( theDebugInformation, theBinaryReader, performLatencyAnalysisProcessing, theLatencyAnalysisProcessing, performBurstAnalysisProcessing, theBurstAnalysisProcessing, performTimeAnalysisProcessing, theTimeAnalysisProcessing, useAlternativeSequenceNumber); this.theUDPDatagramProcessing = new UDPDatagram.Processing( theDebugInformation, theBinaryReader, performLatencyAnalysisProcessing, theLatencyAnalysisProcessing, performBurstAnalysisProcessing, theBurstAnalysisProcessing, performTimeAnalysisProcessing, theTimeAnalysisProcessing, useAlternativeSequenceNumber); this.theEIGRPPacketProcessing = new EIGRPPacket.Processing(theBinaryReader); } /// <summary> /// Processes an IP v4 packet /// </summary> /// <param name="theEthernetFrameLength">The length of the Ethernet frame</param> /// <param name="thePacketNumber">The number for the packet read from the packet capture</param> /// <param name="thePacketTimestamp">The timestamp for the packet read from the packet capture</param> /// <returns>Boolean flag that indicates whether the IP v4 packet could be processed</returns> public bool ProcessIPv4Packet(long theEthernetFrameLength, ulong thePacketNumber, double thePacketTimestamp) { bool theResult = true; ushort theIPv4HeaderLength; ushort theIPv4PacketPayloadLength; byte theIPv4PacketProtocol; // Process the IP v4 packet header theResult = this.ProcessIPv4PacketHeader( theEthernetFrameLength, out theIPv4HeaderLength, out theIPv4PacketPayloadLength, out theIPv4PacketProtocol); if (theResult) { // Process the payload of the IP v4 packet, supplying the length of the payload and the values for the source port and the destination port as returned by the processing of the IP v4 packet header theResult = this.ProcessIPv4PacketPayload( thePacketNumber, thePacketTimestamp, theIPv4PacketPayloadLength, theIPv4PacketProtocol); } return theResult; } /// <summary> /// Processes an IP v4 packet header /// </summary> /// <param name="theEthernetFrameLength">The length of the Ethernet frame</param> /// <param name="theIPv4PacketHeaderLength">The length of the header for the IP v4 packet</param> /// <param name="theIPv4PacketPayloadLength">The length of the payload of the IP v4 packet</param> /// <param name="theIPv4PacketProtocol">The protocol for the IP v4 packet</param> /// <returns>Boolean flag that indicates whether the IP v4 packet header could be processed</returns> private bool ProcessIPv4PacketHeader(long theEthernetFrameLength, out ushort theIPv4PacketHeaderLength, out ushort theIPv4PacketPayloadLength, out byte theIPv4PacketProtocol) { bool theResult = true; // Provide a default value for the output parameter for the length of the IP v4 packet header theIPv4PacketHeaderLength = 0; // Provide a default value for the output parameter for the length of the IP v4 packet payload theIPv4PacketPayloadLength = 0; // Provide a default value for the output parameter for the protocol for the IP v4 packet theIPv4PacketProtocol = 0; // Read the values for the IP v4 packet header from the packet capture // Read off and store the IP packet version and IP v4 packet header length for use below byte theVersionAndHeaderLength = this.theBinaryReader.ReadByte(); // Just read off the bytes for the IP v4 packet header type of service from the packet capture so we can move on this.theBinaryReader.ReadByte(); // Read off and store the total length of the IP v4 packet for use below ushort theIPv4PacketTotalLength = (ushort)System.Net.IPAddress.NetworkToHostOrder(this.theBinaryReader.ReadInt16()); // Just read off the bytes for the IP v4 packet header identifier from the packet capture so we can move on this.theBinaryReader.ReadInt16(); // Just read off the bytes for the IP v4 packet header flags and offset from the packet capture so we can move on this.theBinaryReader.ReadUInt16(); // Just read off the bytes for the IP v4 packet header time to live from the packet capture so we can move on this.theBinaryReader.ReadByte(); // Set up the output parameter for the protocol for the IP v4 packet theIPv4PacketProtocol = this.theBinaryReader.ReadByte(); // Just read off the bytes for the IP v4 packet header checksum from the packet capture so we can move on this.theBinaryReader.ReadUInt16(); // Just read off the bytes for the IP v4 packet header source address from the packet capture so we can move on this.theBinaryReader.ReadInt32(); // Just read off the bytes for the IP v4 packet header destination address from the packet capture so we can move on this.theBinaryReader.ReadInt32(); // Determine the version of the IP v4 packet header // Need to first extract the version value from the combined IP version/IP header length field // We want the higher four bits from the combined IP version/IP header length field (as it's in a big endian representation) so do a bitwise OR with 0xF0 (i.e. 11110000 in binary) and shift down by four bits ushort theIPv4PacketHeaderVersion = (ushort)((theVersionAndHeaderLength & 0xF0) >> 4); // Determine the length of the IP v4 packet header // Need to first extract the length value from the combined IP version/IP header length field // We want the lower four bits from the combined IP version/IP header length field (as it's in a big endian representation) so do a bitwise OR with 0xF (i.e. 00001111 in binary) // The extracted length value is the length of the IP v4 packet header in 32-bit words so multiply by four to get the actual length in bytes of the IP v4 packet header theIPv4PacketHeaderLength = (ushort)((theVersionAndHeaderLength & 0xF) * 4); // Validate the IP v4 packet header theResult = this.ValidateIPv4PacketHeader( theEthernetFrameLength, theIPv4PacketHeaderVersion, theIPv4PacketHeaderLength, theIPv4PacketTotalLength); if (theResult) { // Set up the output parameter for the length of the payload of the IP v4 packet (e.g. a TCP packet), which is the total length of the IP v4 packet minus the length of the IP v4 packet header just calculated theIPv4PacketPayloadLength = (ushort)(theIPv4PacketTotalLength - theIPv4PacketHeaderLength); if (theIPv4PacketHeaderLength > Constants.HeaderMinimumLength) { // The IP v4 packet contains a header length which is greater than the minimum and so contains extra Options bytes at the end (e.g. timestamps from the capture application) // Just read off these remaining Options bytes of the IP v4 packet header from the packet capture so we can move on this.theBinaryReader.ReadBytes( theIPv4PacketHeaderLength - Constants.HeaderMinimumLength); } } return theResult; } /// <summary> /// Processes the payload of the IP v4 packet /// </summary> /// <param name="thePacketNumber">The number for the packet read from the packet capture</param> /// <param name="thePacketTimestamp">The timestamp for the packet read from the packet capture</param> /// <param name="theIPv4PacketPayloadLength">The length of the payload of the IP v4 packet</param> /// <param name="theIPv4Protocol">The protocol for the IP v4 packet</param> /// <returns>Boolean flag that indicates whether the payload of the IP v4 packet could be processed</returns> private bool ProcessIPv4PacketPayload(ulong thePacketNumber, double thePacketTimestamp, ushort theIPv4PacketPayloadLength, byte theIPv4Protocol) { bool theResult = true; // Process the IP v4 packet based on the value indicated for the protocol in the the IP v4 packet header switch (theIPv4Protocol) { case (byte)Constants.Protocol.ICMP: { // We have got an IP v4 packet containing an ICMP v4 packet so process it this.theICMPv4PacketProcessing.ProcessICMPv4Packet( theIPv4PacketPayloadLength); break; } case (byte)Constants.Protocol.IGMP: { // We have got an IP v4 packet containing an IGMP v2 packet so process it this.theIGMPv2PacketProcessing.ProcessIGMPv2Packet(); break; } case (byte)Constants.Protocol.TCP: { // We have got an IP v4 packet containing an TCP packet so process it theResult = this.theTCPPacketProcessing.ProcessTCPPacket( thePacketNumber, thePacketTimestamp, theIPv4PacketPayloadLength); break; } case (byte)Constants.Protocol.UDP: { // We have got an IP v4 packet containing an UDP datagram so process it theResult = this.theUDPDatagramProcessing.ProcessUDPDatagram( thePacketNumber, thePacketTimestamp, theIPv4PacketPayloadLength); break; } case (byte)Constants.Protocol.EIGRP: { // We have got an IP v4 packet containing a Cisco EIGRP packet so process it this.theEIGRPPacketProcessing.ProcessEIGRPPacket( theIPv4PacketPayloadLength); break; } default: { //// We have got an IP v4 packet containing an unknown protocol //// Processing of packets with network data link types not enumerated above are obviously not currently supported! this.theDebugInformation.WriteErrorEvent( "The IP v4 packet contains an unexpected protocol of " + string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:X}", theIPv4Protocol) + "!!!"); theResult = false; break; } } return theResult; } /// <summary> /// Validates the IP v4 packet header /// </summary> /// <param name="theEthernetFrameLength">The length of the Ethernet frame</param> /// <param name="theIPv4HeaderVersion">The version of the IP v4 packet header</param> /// <param name="theIPv4HeaderLength">The length of the IP v4 packet header</param> /// <param name="theIPv4PacketTotalLength">The total length of the IP v4 packet</param> /// <returns>Boolean flag that indicates whether the IP v4 packet header is valid</returns> private bool ValidateIPv4PacketHeader(long theEthernetFrameLength, ushort theIPv4HeaderVersion, ushort theIPv4HeaderLength, ushort theIPv4PacketTotalLength) { bool theResult = true; // Validate the version in the IP v4 packet header if (theIPv4PacketTotalLength > theEthernetFrameLength) { //// We have got an IP v4 packet containing a total length that is higher than the payload in the Ethernet frame which is invalid this.theDebugInformation.WriteErrorEvent( "The IP v4 packet indicates a total length of " + theIPv4PacketTotalLength.ToString(System.Globalization.CultureInfo.CurrentCulture) + " bytes that is greater than the length of " + theEthernetFrameLength.ToString(System.Globalization.CultureInfo.CurrentCulture) + " bytes in the Ethernet frame!!!"); theResult = false; } // Validate the version in the IP v4 packet header if (theIPv4HeaderVersion != Constants.HeaderVersion) { //// We have got an IP v4 packet header containing an unknown version this.theDebugInformation.WriteErrorEvent( "The IP v4 packet header contains an unexpected version of " + theIPv4HeaderVersion.ToString(System.Globalization.CultureInfo.CurrentCulture) + "!!!"); theResult = false; } // Validate the length of the IP v4 packet header if (theIPv4HeaderLength > Constants.HeaderMaximumLength || theIPv4HeaderLength < Constants.HeaderMinimumLength) { //// We have got an IP v4 packet header containing an out of range header length this.theDebugInformation.WriteErrorEvent( "The IP v4 packet header contains a header length " + theIPv4HeaderLength.ToString(System.Globalization.CultureInfo.CurrentCulture) + " which is outside the range " + Constants.HeaderMinimumLength.ToString(System.Globalization.CultureInfo.CurrentCulture) + " to " + Constants.HeaderMaximumLength.ToString(System.Globalization.CultureInfo.CurrentCulture) + "!!!"); theResult = false; } return theResult; } } }
/*============================================================================ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================ */ #region Using directives using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Globalization; using Microsoft.Management.Infrastructure.Options; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { #region CimSessionWrapper internal class CimSessionWrapper { #region members /// <summary> /// id of the cimsession /// </summary> public uint SessionId { get { return this.sessionId; } } private uint sessionId; /// <summary> /// instanceId of the cimsession /// </summary> public Guid InstanceId { get { return this.instanceId; } } private Guid instanceId; /// <summary> /// name of the cimsession /// </summary> public string Name { get { return this.name; } } private string name; /// <summary> /// computer name of the cimsession /// </summary> public string ComputerName { get { return this.computerName; } } private string computerName; /// <summary> /// wrapped cimsession object /// </summary> public CimSession CimSession { get { return this.cimSession; } } private CimSession cimSession; /// <summary> /// computer name of the cimsession /// </summary> public string Protocol { get { switch (protocol) { case ProtocolType.Dcom: return "DCOM"; case ProtocolType.Default: case ProtocolType.Wsman: default: return "WSMAN"; } } } internal ProtocolType GetProtocolType() { return protocol; } private ProtocolType protocol; /// <summary> /// PSObject that wrapped the cimSession /// </summary> private PSObject psObject; #endregion internal CimSessionWrapper( uint theSessionId, Guid theInstanceId, string theName, string theComputerName, CimSession theCimSession, ProtocolType theProtocol) { this.sessionId = theSessionId; this.instanceId = theInstanceId; this.name = theName; this.computerName = theComputerName; this.cimSession = theCimSession; this.psObject = null; this.protocol = theProtocol; } internal PSObject GetPSObject() { if (psObject == null) { psObject = new PSObject(this.cimSession); psObject.Properties.Add(new PSNoteProperty(CimSessionState.idPropName, this.sessionId)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.namePropName, this.name)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.instanceidPropName, this.instanceId)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.computernamePropName, this.ComputerName)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.protocolPropName, this.Protocol)); } else { psObject.Properties[CimSessionState.idPropName].Value = this.SessionId; psObject.Properties[CimSessionState.namePropName].Value = this.name; psObject.Properties[CimSessionState.instanceidPropName].Value = this.instanceId; psObject.Properties[CimSessionState.computernamePropName].Value = this.ComputerName; psObject.Properties[CimSessionState.protocolPropName].Value = this.Protocol; } return psObject; } } #endregion #region CimSessionState /// <summary> /// <para> /// Class used to hold all cimsession related status data related to a runspace. /// Including the CimSession cache, session counters for generating session name. /// </para> /// </summary> internal class CimSessionState : IDisposable { #region private members /// <summary> /// Default session name. /// If a name is not passed, then the session is given the name CimSession<int>, /// where <int> is the next available session number. /// For example, CimSession1, CimSession2, etc... /// </summary> internal static string CimSessionClassName = "CimSession"; /// <summary> /// CimSession object name /// </summary> internal static string CimSessionObject = "{CimSession Object}"; /// <summary> /// <para> /// CimSession object path, which is identifying a cimsession object /// </para> /// </summary> internal static string SessionObjectPath = @"CimSession id = {0}, name = {2}, ComputerName = {3}, instance id = {1}"; /// <summary> /// Id property name of cimsession wrapper object /// </summary> internal static string idPropName = "Id"; /// <summary> /// Instanceid property name of cimsession wrapper object /// </summary> internal static string instanceidPropName = "InstanceId"; /// <summary> /// Name property name of cimsession wrapper object /// </summary> internal static string namePropName = "Name"; /// <summary> /// Computer name property name of cimsession object /// </summary> internal static string computernamePropName = "ComputerName"; /// <summary> /// Protocol name property name of cimsession object /// </summary> internal static string protocolPropName = "Protocol"; /// <summary> /// <para> /// session counter bound to current runspace. /// </para> /// </summary> private UInt32 sessionNameCounter; /// <summary> /// <para> /// Dictionary used to holds all CimSessions in current runspace by session name. /// </para> /// </summary> private Dictionary<string, HashSet<CimSessionWrapper>> curCimSessionsByName; /// <summary> /// <para> /// Dictionary used to holds all CimSessions in current runspace by computer name. /// </para> /// </summary> private Dictionary<string, HashSet<CimSessionWrapper>> curCimSessionsByComputerName; /// <summary> /// <para> /// Dictionary used to holds all CimSessions in current runspace by instance ID. /// </para> /// </summary> private Dictionary<Guid, CimSessionWrapper> curCimSessionsByInstanceId; /// <summary> /// <para> /// Dictionary used to holds all CimSessions in current runspace by session id. /// </para> /// </summary> private Dictionary<UInt32, CimSessionWrapper> curCimSessionsById; /// <summary> /// <para> /// Dictionary used to link CimSession object with PSObject. /// </para> /// </summary> private Dictionary<CimSession, CimSessionWrapper> curCimSessionWrapper; #endregion /// <summary> /// <para> /// constructor /// </para> /// </summary> internal CimSessionState() { sessionNameCounter = 1; curCimSessionsByName = new Dictionary<string, HashSet<CimSessionWrapper>>( StringComparer.OrdinalIgnoreCase); curCimSessionsByComputerName = new Dictionary<string, HashSet<CimSessionWrapper>>( StringComparer.OrdinalIgnoreCase); curCimSessionsByInstanceId = new Dictionary<Guid, CimSessionWrapper>(); curCimSessionsById = new Dictionary<uint, CimSessionWrapper>(); curCimSessionWrapper = new Dictionary<CimSession, CimSessionWrapper>(); } /// <summary> /// <para> /// Get sessions count. /// </para> /// </summary> /// <returns>The count of session objects in current runspace.</returns> internal int GetSessionsCount() { return this.curCimSessionsById.Count; } /// <summary> /// <para> /// Generates an unique session id. /// </para> /// </summary> /// <returns>Unique session id under current runspace</returns> internal UInt32 GenerateSessionId() { return this.sessionNameCounter++; } #region IDisposable /// <summary> /// <para> /// Indicates whether this object was disposed or not /// </para> /// </summary> private bool _disposed; /// <summary> /// <para> /// Dispose() calls Dispose(true). /// Implement IDisposable. Do not make this method virtual. /// A derived class should not be able to override this method. /// </para> /// </summary> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// <para> /// 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. /// </para> /// </summary> /// <param name="disposing">Whether it is directly called</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // free managed resources Cleanup(); this._disposed = true; } // free native resources if there are any } } /// <summary> /// <para> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </para> /// </summary> public void Cleanup() { foreach (CimSession session in curCimSessionWrapper.Keys) { session.Dispose(); } curCimSessionWrapper.Clear(); curCimSessionsByName.Clear(); curCimSessionsByComputerName.Clear(); curCimSessionsByInstanceId.Clear(); curCimSessionsById.Clear(); sessionNameCounter = 1; } #endregion #region Add CimSession to/remove CimSession from cache /// <summary> /// <para> /// Add new CimSession object to cache /// </para> /// </summary> /// <param name="session"></param> /// <param name="sessionId"></param> /// <param name="instanceId"></param> /// <param name="name"></param> /// <returns></returns> internal PSObject AddObjectToCache( CimSession session, UInt32 sessionId, Guid instanceId, String name, String computerName, ProtocolType protocol) { CimSessionWrapper wrapper = new CimSessionWrapper( sessionId, instanceId, name, computerName, session, protocol); HashSet<CimSessionWrapper> objects; if (!this.curCimSessionsByComputerName.TryGetValue(computerName, out objects)) { objects = new HashSet<CimSessionWrapper>(); this.curCimSessionsByComputerName.Add(computerName, objects); } objects.Add(wrapper); if (!this.curCimSessionsByName.TryGetValue(name, out objects)) { objects = new HashSet<CimSessionWrapper>(); this.curCimSessionsByName.Add(name, objects); } objects.Add(wrapper); this.curCimSessionsByInstanceId.Add(instanceId, wrapper); this.curCimSessionsById.Add(sessionId, wrapper); this.curCimSessionWrapper.Add(session, wrapper); return wrapper.GetPSObject(); } /// <summary> /// <para> /// Generates remove session message by given wrapper object. /// </para> /// </summary> /// <param name="psObject"></param> internal string GetRemoveSessionObjectTarget(PSObject psObject) { String message = String.Empty; if (psObject.BaseObject is CimSession) { UInt32 id = 0x0; Guid instanceId = Guid.Empty; String name = String.Empty; String computerName = string.Empty; if (psObject.Properties[idPropName].Value is UInt32) { id = Convert.ToUInt32(psObject.Properties[idPropName].Value, null); } if (psObject.Properties[instanceidPropName].Value is Guid) { instanceId = (Guid)psObject.Properties[instanceidPropName].Value; } if (psObject.Properties[namePropName].Value is String) { name = (String)psObject.Properties[namePropName].Value; } if (psObject.Properties[computernamePropName].Value is String) { computerName = (String)psObject.Properties[computernamePropName].Value; } message = String.Format(CultureInfo.CurrentUICulture, SessionObjectPath, id, instanceId, name, computerName); } return message; } /// <summary> /// <para> /// Remove given <see cref="PSObject"/> object from cache /// </para> /// </summary> /// <param name="psObject"></param> internal void RemoveOneSessionObjectFromCache(PSObject psObject) { DebugHelper.WriteLogEx(); if (psObject.BaseObject is CimSession) { RemoveOneSessionObjectFromCache(psObject.BaseObject as CimSession); } } /// <summary> /// <para> /// Remove given <see cref="CimSession"/> object from cache /// </para> /// </summary> /// <param name="session"></param> internal void RemoveOneSessionObjectFromCache(CimSession session) { DebugHelper.WriteLogEx(); if (!this.curCimSessionWrapper.ContainsKey(session)) { return; } CimSessionWrapper wrapper = this.curCimSessionWrapper[session]; String name = wrapper.Name; String computerName = wrapper.ComputerName; DebugHelper.WriteLog("name {0}, computername {1}, id {2}, instanceId {3}", 1, name, computerName, wrapper.SessionId, wrapper.InstanceId); HashSet<CimSessionWrapper> objects; if (this.curCimSessionsByComputerName.TryGetValue(computerName, out objects)) { objects.Remove(wrapper); } if (this.curCimSessionsByName.TryGetValue(name, out objects)) { objects.Remove(wrapper); } RemoveSessionInternal(session, wrapper); } /// <summary> /// <para> /// Remove given <see cref="CimSession"/> object from partial of the cache only. /// </para> /// </summary> /// <param name="session"></param> /// <param name="psObject"></param> private void RemoveSessionInternal(CimSession session, CimSessionWrapper wrapper) { DebugHelper.WriteLogEx(); this.curCimSessionsByInstanceId.Remove(wrapper.InstanceId); this.curCimSessionsById.Remove(wrapper.SessionId); this.curCimSessionWrapper.Remove(session); session.Dispose(); } #endregion #region Query CimSession from cache /// <summary> /// <para> /// Add ErrorRecord to list. /// </para> /// </summary> /// <param name="errRecords"></param> /// <param name="propertyName"></param> /// <param name="propertyValue"></param> private void AddErrorRecord( ref List<ErrorRecord> errRecords, string propertyName, object propertyValue) { errRecords.Add( new ErrorRecord( new CimException(String.Format(CultureInfo.CurrentUICulture, Strings.CouldNotFindCimsessionObject, propertyName, propertyValue)), string.Empty, ErrorCategory.ObjectNotFound, null)); } /// <summary> /// Query session list by given id array /// </summary> /// <param name="ids"></param> /// <returns>List of session wrapper objects</returns> internal IEnumerable<PSObject> QuerySession(IEnumerable<UInt32> ids, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; // NOTES: use template function to implement this will save duplicate code foreach (UInt32 id in ids) { if (this.curCimSessionsById.ContainsKey(id)) { if (!sessionIds.Contains(id)) { sessionIds.Add(id); sessions.Add(this.curCimSessionsById[id].GetPSObject()); } } else { AddErrorRecord(ref errRecords, idPropName, id); } } return sessions; } /// <summary> /// Query session list by given instance id array /// </summary> /// <param name="instanceIds"></param> /// <returns>List of session wrapper objects</returns> internal IEnumerable<PSObject> QuerySession(IEnumerable<Guid> instanceIds, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; foreach (Guid instanceid in instanceIds) { if (this.curCimSessionsByInstanceId.ContainsKey(instanceid)) { CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[instanceid]; if (!sessionIds.Contains(wrapper.SessionId)) { sessionIds.Add(wrapper.SessionId); sessions.Add(wrapper.GetPSObject()); } } else { AddErrorRecord(ref errRecords, instanceidPropName, instanceid); } } return sessions; } /// <summary> /// Query session list by given name array /// </summary> /// <param name="nameArray"></param> /// <returns>List of session wrapper objects</returns> internal IEnumerable<PSObject> QuerySession(IEnumerable<string> nameArray, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; foreach (string name in nameArray) { bool foundSession = false; WildcardPattern pattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); foreach (KeyValuePair<String, HashSet<CimSessionWrapper>> kvp in this.curCimSessionsByName) { if (pattern.IsMatch(kvp.Key)) { HashSet<CimSessionWrapper> wrappers = kvp.Value; foundSession = (wrappers.Count > 0); foreach (CimSessionWrapper wrapper in wrappers) { if (!sessionIds.Contains(wrapper.SessionId)) { sessionIds.Add(wrapper.SessionId); sessions.Add(wrapper.GetPSObject()); } } } } if (!foundSession && !WildcardPattern.ContainsWildcardCharacters(name)) { AddErrorRecord(ref errRecords, namePropName, name); } } return sessions; } /// <summary> /// Query session list by given computer name array /// </summary> /// <param name="computernameArray"></param> /// <returns>List of session wrapper objects</returns> internal IEnumerable<PSObject> QuerySessionByComputerName( IEnumerable<string> computernameArray, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; foreach (string computername in computernameArray) { bool foundSession = false; if (this.curCimSessionsByComputerName.ContainsKey(computername)) { HashSet<CimSessionWrapper> wrappers = this.curCimSessionsByComputerName[computername]; foundSession = (wrappers.Count > 0); foreach (CimSessionWrapper wrapper in wrappers) { if (!sessionIds.Contains(wrapper.SessionId)) { sessionIds.Add(wrapper.SessionId); sessions.Add(wrapper.GetPSObject()); } } } if (!foundSession) { AddErrorRecord(ref errRecords, computernamePropName, computername); } } return sessions; } /// <summary> /// Query session list by given session objects array /// </summary> /// <param name="cimsessions"></param> /// <returns>List of session wrapper objects</returns> internal IEnumerable<PSObject> QuerySession(IEnumerable<CimSession> cimsessions, out IEnumerable<ErrorRecord> errorRecords) { HashSet<PSObject> sessions = new HashSet<PSObject>(); HashSet<uint> sessionIds = new HashSet<uint>(); List<ErrorRecord> errRecords = new List<ErrorRecord>(); errorRecords = errRecords; foreach (CimSession cimsession in cimsessions) { if (this.curCimSessionWrapper.ContainsKey(cimsession)) { CimSessionWrapper wrapper = this.curCimSessionWrapper[cimsession]; if (!sessionIds.Contains(wrapper.SessionId)) { sessionIds.Add(wrapper.SessionId); sessions.Add(wrapper.GetPSObject()); } } else { AddErrorRecord(ref errRecords, CimSessionClassName, CimSessionObject); } } return sessions; } /// <summary> /// Query session wrapper object /// </summary> /// <param name="cimsessions"></param> /// <returns>session wrapper</returns> internal CimSessionWrapper QuerySession(CimSession cimsession) { CimSessionWrapper wrapper; this.curCimSessionWrapper.TryGetValue(cimsession, out wrapper); return wrapper; } /// <summary> /// Query session object with given CimSessionInstanceID /// </summary> /// <param name="cimSessionInstanceId"></param> /// <returns>CimSession object</returns> internal CimSession QuerySession(Guid cimSessionInstanceId) { if (this.curCimSessionsByInstanceId.ContainsKey(cimSessionInstanceId)) { CimSessionWrapper wrapper = this.curCimSessionsByInstanceId[cimSessionInstanceId]; return wrapper.CimSession; } return null; } #endregion } #endregion #region CimSessionBase /// <summary> /// <para> /// Base class of all session operation classes. /// All sessions created will be held in a ConcurrentDictionary:cimSessions. /// It manages the lifecyclye of the sessions being created for each /// runspace according to the state of the runspace. /// </para> /// </summary> internal class CimSessionBase { #region constructor /// <summary> /// Constructor /// </summary> public CimSessionBase() { this.sessionState = cimSessions.GetOrAdd( CurrentRunspaceId, delegate(Guid instanceId) { if (Runspace.DefaultRunspace != null) { Runspace.DefaultRunspace.StateChanged += DefaultRunspace_StateChanged; } return new CimSessionState(); }); } #endregion #region members /// <summary> /// <para> /// Thread safe static dictionary to store session objects associated /// with each runspace, which is identified by a GUID. NOTE: cmdlet /// can running parallelly under more than one runspace(s). /// </para> /// </summary> static internal ConcurrentDictionary<Guid, CimSessionState> cimSessions = new ConcurrentDictionary<Guid, CimSessionState>(); /// <summary> /// <para> /// Default runspace id /// </para> /// </summary> static internal Guid defaultRunspaceId = Guid.Empty; /// <summary> /// <para> /// Object used to hold all CimSessions and status data bound /// to current runspace. /// </para> /// </summary> internal CimSessionState sessionState; /// <summary> /// Get current runspace id /// </summary> private static Guid CurrentRunspaceId { get { if (Runspace.DefaultRunspace != null) { return Runspace.DefaultRunspace.InstanceId; } else { return CimSessionBase.defaultRunspaceId; } } } #endregion public static CimSessionState GetCimSessionState() { CimSessionState state = null; cimSessions.TryGetValue(CurrentRunspaceId, out state); return state; } /// <summary> /// <para> /// clean up the dictionaries if the runspace is closed or broken. /// </para> /// </summary> /// <param name="sender">Runspace</param> /// <param name="e">Event args</param> private static void DefaultRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { Runspace runspace = (Runspace)sender; switch (e.RunspaceStateInfo.State) { case RunspaceState.Broken: case RunspaceState.Closed: CimSessionState state; if (cimSessions.TryRemove(runspace.InstanceId, out state)) { DebugHelper.WriteLog(String.Format(CultureInfo.CurrentUICulture, DebugHelper.runspaceStateChanged, runspace.InstanceId, e.RunspaceStateInfo.State)); state.Dispose(); } runspace.StateChanged -= DefaultRunspace_StateChanged; break; default: break; } } } #endregion #region CimTestConnection #endregion #region CimNewSession /// <summary> /// <para> /// <c>CimNewSession</c> is the class to create cimSession /// based on given <c>NewCimSessionCommand</c>. /// </para> /// </summary> internal class CimNewSession : CimSessionBase, IDisposable { /// <summary> /// CimTestCimSessionContext /// </summary> internal class CimTestCimSessionContext : XOperationContextBase { /// <summary> /// <para> /// Constructor /// </para> /// </summary> /// <param name="theProxy"></param> /// <param name="wrapper"></param> internal CimTestCimSessionContext( CimSessionProxy theProxy, CimSessionWrapper wrapper) { this.proxy = theProxy; this.cimSessionWrapper = wrapper; this.nameSpace = null; } /// <summary> /// <para>namespce</para> /// </summary> internal CimSessionWrapper CimSessionWrapper { get { return this.cimSessionWrapper; } } private CimSessionWrapper cimSessionWrapper; } /// <summary> /// <para> /// constructor /// </para> /// </summary> internal CimNewSession() : base() { this.cimTestSession = new CimTestSession(); this._disposed = false; } /// <summary> /// Create a new <see cref="CimSession"/> base on given cmdlet /// and its parameter /// </summary> /// <param name="cmdlet"></param> /// <param name="sessionOptions"></param> /// <param name="credential"></param> internal void NewCimSession(NewCimSessionCommand cmdlet, CimSessionOptions sessionOptions, CimCredential credential) { DebugHelper.WriteLogEx(); IEnumerable<string> computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); foreach (string computerName in computerNames) { CimSessionProxy proxy; if (sessionOptions == null) { DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, cmdlet.OperationTimeoutSec, credential); } proxy = new CimSessionProxyTestConnection(computerName, sessionOptions); string computerNameValue = (computerName == ConstValue.NullComputerName) ? ConstValue.LocalhostComputerName : computerName; CimSessionWrapper wrapper = new CimSessionWrapper(0, Guid.Empty, cmdlet.Name, computerNameValue, proxy.CimSession, proxy.Protocol); CimTestCimSessionContext context = new CimTestCimSessionContext(proxy, wrapper); proxy.ContextObject = context; // Skip test the connection if user intend to if(cmdlet.SkipTestConnection.IsPresent) { AddSessionToCache(proxy.CimSession, context, new CmdletOperationBase(cmdlet)); } else { //CimSession will be retunred as part of TestConnection this.cimTestSession.TestCimSession(computerName, proxy); } } } /// <summary> /// <para> /// Add session to global cache /// </para> /// </summary> /// <param name="cimSession"></param> /// <param name="context"></param> /// <param name="cmdlet"></param> internal void AddSessionToCache(CimSession cimSession, XOperationContextBase context, CmdletOperationBase cmdlet) { DebugHelper.WriteLogEx(); CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext; UInt32 sessionId = this.sessionState.GenerateSessionId(); string orginalSessioName = testCimSessionContext.CimSessionWrapper.Name; string sessionName = (orginalSessioName != null) ? orginalSessioName : String.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId); // detach CimSession from the proxy object CimSession createdCimSession = testCimSessionContext.Proxy.Detach(); PSObject psObject = this.sessionState.AddObjectToCache( createdCimSession, sessionId, createdCimSession.InstanceId, sessionName, testCimSessionContext.CimSessionWrapper.ComputerName, testCimSessionContext.Proxy.Protocol); cmdlet.WriteObject(psObject, null); } /// <summary> /// <para> /// process all actions in the action queue /// </para> /// </summary> /// <param name="cmdletOperation"> /// wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details /// </param> public void ProcessActions(CmdletOperationBase cmdletOperation) { this.cimTestSession.ProcessActions(cmdletOperation); } /// <summary> /// <para> /// process remaining actions until all operations are completed or /// current cmdlet is terminated by user /// </para> /// </summary> /// <param name="cmdletOperation"> /// wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details /// </param> public void ProcessRemainActions(CmdletOperationBase cmdletOperation) { this.cimTestSession.ProcessRemainActions(cmdletOperation); } #region private members /// <summary> /// <para> /// <see cref="CimTestSession"/> object. /// </para> /// </summary> private CimTestSession cimTestSession; #endregion //private members #region IDisposable /// <summary> /// <para> /// Indicates whether this object was disposed or not /// </para> /// </summary> protected bool Disposed { get { return _disposed; } } private bool _disposed; /// <summary> /// <para> /// Dispose() calls Dispose(true). /// Implement IDisposable. Do not make this method virtual. /// A derived class should not be able to override this method. /// </para> /// </summary> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// <para> /// 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. /// </para> /// </summary> /// <param name="disposing">Whether it is directly called</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // free managed resources this.cimTestSession.Dispose(); this._disposed = true; } // free native resources if there are any } } #endregion }//End Class #endregion #region CimGetSession /// <summary> /// <para> /// Get CimSession based on given id/instanceid/computername/name /// </para> /// </summary> internal class CimGetSession : CimSessionBase { /// <summary> /// constructor /// </summary> public CimGetSession() : base() { } /// <summary> /// Get <see cref="CimSession"/> objects based on the given cmdlet /// and its parameter /// </summary> /// <param name="cmdlet"></param> public void GetCimSession(GetCimSessionCommand cmdlet) { DebugHelper.WriteLogEx(); IEnumerable<PSObject> sessionToGet = null; IEnumerable<ErrorRecord> errorRecords = null; switch (cmdlet.ParameterSetName) { case CimBaseCommand.ComputerNameSet: if (cmdlet.ComputerName == null) { sessionToGet = this.sessionState.QuerySession(ConstValue.DefaultSessionName, out errorRecords); } else { sessionToGet = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords); } break; case CimBaseCommand.SessionIdSet: sessionToGet = this.sessionState.QuerySession(cmdlet.Id, out errorRecords); break; case CimBaseCommand.InstanceIdSet: sessionToGet = this.sessionState.QuerySession(cmdlet.InstanceId, out errorRecords); break; case CimBaseCommand.NameSet: sessionToGet = this.sessionState.QuerySession(cmdlet.Name, out errorRecords); break; default: break; } if (sessionToGet != null) { foreach(PSObject psobject in sessionToGet) { cmdlet.WriteObject(psobject); } } if (errorRecords != null) { foreach (ErrorRecord errRecord in errorRecords) { cmdlet.WriteError(errRecord); } } } #region helper methods #endregion }//End Class #endregion #region CimRemoveSession /// <summary> /// <para> /// Get CimSession based on given id/instanceid/computername/name /// </para> /// </summary> internal class CimRemoveSession : CimSessionBase { /// <summary> /// Remove session action string /// </summary> internal static string RemoveCimSessionActionName = "Remove CimSession"; /// <summary> /// constructor /// </summary> public CimRemoveSession() : base() { } /// <summary> /// Remove the <see cref="CimSession"/> objects based on given cmdlet /// and its parameter /// </summary> /// <param name="cmdlet"></param> public void RemoveCimSession(RemoveCimSessionCommand cmdlet) { DebugHelper.WriteLogEx(); IEnumerable<PSObject> sessionToRemove = null; IEnumerable<ErrorRecord> errorRecords = null; switch (cmdlet.ParameterSetName) { case CimBaseCommand.CimSessionSet: sessionToRemove = this.sessionState.QuerySession(cmdlet.CimSession, out errorRecords); break; case CimBaseCommand.ComputerNameSet: sessionToRemove = this.sessionState.QuerySessionByComputerName(cmdlet.ComputerName, out errorRecords); break; case CimBaseCommand.SessionIdSet: sessionToRemove = this.sessionState.QuerySession(cmdlet.Id, out errorRecords); break; case CimBaseCommand.InstanceIdSet: sessionToRemove = this.sessionState.QuerySession(cmdlet.InstanceId, out errorRecords); break; case CimBaseCommand.NameSet: sessionToRemove = this.sessionState.QuerySession(cmdlet.Name, out errorRecords); break; default: break; } if (sessionToRemove != null) { foreach (PSObject psobject in sessionToRemove) { if (cmdlet.ShouldProcess(this.sessionState.GetRemoveSessionObjectTarget(psobject), RemoveCimSessionActionName)) { this.sessionState.RemoveOneSessionObjectFromCache(psobject); } } } if (errorRecords != null) { foreach (ErrorRecord errRecord in errorRecords) { cmdlet.WriteError(errRecord); } } } }//End Class #endregion #region CimTestSession /// <summary> /// Class <see cref="CimTestSession"/>, which is used to /// test cimsession and execute async operations. /// </summary> internal class CimTestSession : CimAsyncOperation { /// <summary> /// Constructor /// </summary> internal CimTestSession() : base() { } /// <summary> /// Test the session connection with /// given <see cref="CimSessionProxy"/> object. /// </summary> /// <param name="computerName"></param> /// <param name="proxy"></param> internal void TestCimSession( string computerName, CimSessionProxy proxy) { DebugHelper.WriteLogEx(); this.SubscribeEventAndAddProxytoCache(proxy); proxy.TestConnectionAsync(); } } #endregion }//End namespace
using System; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.Text; using Xunit; namespace NReco.Linq.Tests { public class LambdaParserTests { Dictionary<string,object> getContext() { var varContext = new Dictionary<string, object>(); varContext["pi"] = 3.14M; varContext["one"] = 1M; varContext["two"] = 2M; varContext["test"] = "test"; varContext["now"] = DateTime.Now; varContext["testObj"] = new TestClass(); varContext["getTestObj"] = (Func<TestClass>)(() => new TestClass()); varContext["toString"] = (Func<object,string>)((o) => o.ToString()); varContext["arr1"] = new double[] { 1.5, 2.5 }; varContext["NOT"] = (Func<bool, bool>)((t) => !t); varContext["Yes"] = true; varContext["nullVar"] = null; varContext["name_with_underscore"] = "a_b"; varContext["_name_with_underscore"] = "_a_b"; varContext["day1"] = new DateTime().AddDays(1); varContext["day2"] = new DateTime().AddDays(2); varContext["oneDay"] = new TimeSpan(1,0,0,0); varContext["twoDays"] = new TimeSpan(2,0,0,0); return varContext; } [Fact] public void Eval() { var lambdaParser = new LambdaParser(); var varContext = getContext(); Assert.Equal("st", lambdaParser.Eval("test.Substring(2)", varContext ) ); Assert.Equal(true, lambdaParser.Eval("NOT(NOT(1==1))", varContext)); Assert.Equal(3M, lambdaParser.Eval("1+2", varContext) ); Assert.Equal(6M, lambdaParser.Eval("1+2+3", varContext)); Assert.Equal("b{0}_", lambdaParser.Eval("\"b{0}_\"", varContext)); Assert.Equal(3M, lambdaParser.Eval("(1+(3-1)*4)/3", varContext)); Assert.Equal(1M, lambdaParser.Eval("one*5*one-(-1+5*5%10)", varContext)); Assert.Equal("ab", lambdaParser.Eval("\"a\"+\"b\"", varContext)); Assert.Equal(4.14M, lambdaParser.Eval("pi + 1", varContext) ); Assert.Equal(5.14M, lambdaParser.Eval("2 +pi", varContext) ); Assert.Equal(2.14M, lambdaParser.Eval("pi + -one", varContext) ); Assert.Equal("test1", lambdaParser.Eval("test + \"1\"", varContext) ); Assert.Equal("a_b_a_b", lambdaParser.Eval(" name_with_underscore + _name_with_underscore ", varContext)); Assert.Equal(1M, lambdaParser.Eval("true or false ? 1 : 0", varContext) ); Assert.Equal(true, lambdaParser.Eval("5<=3 ? false : true", varContext)); Assert.Equal(5M, lambdaParser.Eval("pi>one && 0<one ? (1+8)/3+1*two : 0", varContext)); Assert.Equal(4M, lambdaParser.Eval("pi>0 ? one+two+one : 0", varContext)); Assert.Equal(DateTime.Now.Year, lambdaParser.Eval("now.Year", varContext) ); Assert.Equal(true, lambdaParser.Eval(" (1+testObj.IntProp)==2 ? testObj.FldTrue : false ", varContext)); Assert.Equal("ab2_3", lambdaParser.Eval(" \"a\"+testObj.Format(\"b{0}_{1}\", 2, \"3\".ToString() ).ToString() ", varContext)); Assert.Equal(true, lambdaParser.Eval(" testObj.Hash[\"a\"] == \"1\"", varContext)); Assert.Equal(true, lambdaParser.Eval(" (testObj.Hash[\"a\"]-1)==testObj.Hash[\"b\"].Length ", varContext)); Assert.Equal(4.0M, lambdaParser.Eval(" arr1[0]+arr1[1] ", varContext)); Assert.Equal(2M, lambdaParser.Eval(" (new[]{1,2})[1] ", varContext)); Assert.Equal(true, lambdaParser.Eval(" new[]{ one } == new[] { 1 } ", varContext)); Assert.Equal(3, lambdaParser.Eval(" new dictionary{ {\"a\", 1}, {\"b\", 2}, {\"c\", 3} }.Count ", varContext)); Assert.Equal(2M, lambdaParser.Eval(" new dictionary{ {\"a\", 1}, {\"b\", 2}, {\"c\", 3} }[\"b\"] ", varContext)); var arr = ((Array)lambdaParser.Eval(" new []{ new dictionary{{\"test\",2}}, new[] { one } }", varContext) ); Assert.Equal(2M, ((IDictionary)arr.GetValue(0) )["test"] ); Assert.Equal(1M, ((Array)arr.GetValue(1) ).GetValue(0) ); Assert.Equal("str", lambdaParser.Eval(" testObj.GetDelegNoParam()() ", varContext)); Assert.Equal("zzz", lambdaParser.Eval(" testObj.GetDelegOneParam()(\"zzz\") ", varContext)); Assert.Equal(false, lambdaParser.Eval("(testObj.FldTrue and false) || (testObj.FldTrue && false)", varContext ) ); Assert.Equal(true, lambdaParser.Eval("false or testObj.FldTrue", varContext ) ); Assert.Equal("True", lambdaParser.Eval("testObj.BoolParam(true)", varContext ) ); Assert.Equal("True", lambdaParser.Eval("getTestObj().BoolParam(true)", varContext)); Assert.Equal("NReco.Linq.Tests.LambdaParserTests+TestClass", lambdaParser.Eval("toString(testObj)", varContext)); Assert.True( (bool) lambdaParser.Eval("true && NOT( false )", varContext ) ); Assert.True( (bool) lambdaParser.Eval("true && !( false )", varContext ) ); Assert.False( (bool) lambdaParser.Eval("!Yes", varContext ) ); Assert.True((bool)lambdaParser.Eval("5>two && (5>7 || test.Contains(\"t\") )", varContext)); Assert.True((bool)lambdaParser.Eval("null!=test && test!=null && test.Contains(\"t\") && true == Yes && false==!Yes && false!=Yes", varContext)); Assert.Equal(new DateTime().AddDays(2), lambdaParser.Eval("day1 + oneDay", varContext)); Assert.Equal(new DateTime().AddDays(2), lambdaParser.Eval("oneDay + day1", varContext)); Assert.Equal(new DateTime().AddDays(1), lambdaParser.Eval("day2 - oneDay", varContext)); Assert.Equal(new DateTime().AddDays(1), lambdaParser.Eval("day2 + -oneDay", varContext)); Assert.Equal(new DateTime().AddDays(1), lambdaParser.Eval("-oneDay + day2", varContext)); Assert.Equal(new TimeSpan(1,0,0,0), lambdaParser.Eval("day2 - day1", varContext)); Assert.Equal(new TimeSpan(1,0,0,0).Negate(), lambdaParser.Eval("day1 - day2", varContext)); Assert.Equal(new TimeSpan(1,0,0,0), lambdaParser.Eval("day2 - day1", varContext)); Assert.Equal(new TimeSpan(2,0,0,0), lambdaParser.Eval("oneDay + oneDay", varContext)); Assert.Equal(new TimeSpan(1,0,0,0), lambdaParser.Eval("twoDays - oneDay", varContext)); Assert.Equal(new TimeSpan(1,0,0,0), lambdaParser.Eval("twoDays + -oneDay", varContext)); Assert.Equal(new TimeSpan(1,0,0,0).Negate(), lambdaParser.Eval("oneDay - twoDays", varContext)); Assert.Equal(new TimeSpan(1,0,0,0).Negate(), lambdaParser.Eval("-twoDays + oneDay", varContext)); } [Fact] public void SingleEqualSign() { var varContext = getContext(); var lambdaParser = new LambdaParser(); lambdaParser.AllowSingleEqualSign = true; Assert.True((bool)lambdaParser.Eval("null = nullVar", varContext)); Assert.True((bool)lambdaParser.Eval("5 = (5+1-1)", varContext)); } [Fact] public void NullComparison() { var varContext = getContext(); var lambdaParser = new LambdaParser(); Assert.True((bool)lambdaParser.Eval("null == nullVar", varContext)); Assert.True((bool)lambdaParser.Eval("5>nullVar", varContext)); Assert.True((bool)lambdaParser.Eval("testObj!=null", varContext)); Assert.Equal(0, LambdaParser.GetExpressionParameters(lambdaParser.Parse("20 == null")).Length); lambdaParser = new LambdaParser(new ValueComparer() { NullComparison = ValueComparer.NullComparisonMode.Sql }); Assert.False((bool)lambdaParser.Eval("null == nullVar", varContext)); Assert.False((bool)lambdaParser.Eval("nullVar<5", varContext)); Assert.False((bool)lambdaParser.Eval("nullVar>5", varContext)); } [Fact] public void EvalCachePerf() { var lambdaParser = new LambdaParser(); var varContext = new Dictionary<string, object>(); varContext["a"] = 55; varContext["b"] = 2; var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 10000; i++) { Assert.Equal(105M, lambdaParser.Eval("(a*2 + 100)/b", varContext)); } sw.Stop(); Console.WriteLine("10000 iterations: {0}", sw.Elapsed); } public class TestClass { public int IntProp { get { return 1; } } public string StrProp { get { return "str"; } } public bool FldTrue { get { return true; } } public IDictionary Hash { get { return new Hashtable() { {"a", 1}, {"b", ""} }; } } public string Format(string s, object arg1, int arg2) { return String.Format(s, arg1, arg2); } public string BoolParam(bool flag) { return flag.ToString(); } public Func<string, string> GetDelegOneParam() { return (s) => { return s; }; } public Func<string> GetDelegNoParam() { return () => { return StrProp; }; } } } }
/* * AttributeCollection.cs - Implementation of the * "System.ComponentModel.ComponentModel.AttributeCollection" class. * * Copyright (C) 2002, 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 System.ComponentModel { #if CONFIG_COMPONENT_MODEL using System.Collections; using System.Reflection; using System.Runtime.InteropServices; [ComVisible(true)] public class AttributeCollection : ICollection, IEnumerable { // Internal state. private ArrayList coll; // The empty attribute collection. public static readonly AttributeCollection Empty = new AttributeCollection(null); // Constructor. public AttributeCollection(Attribute[] attributes) { coll = new ArrayList(); if(attributes != null) { coll.AddRange(attributes); } } // Implement the ICollection interface. public void CopyTo(Array array, int index) { coll.CopyTo(array, index); } int ICollection.Count { get { return coll.Count; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return this; } } // Implement the IEnumerable interface. IEnumerator IEnumerable.GetEnumerator() { return coll.GetEnumerator(); } // Get the number of elements in this collection. public int Count { get { return coll.Count; } } // Get an element from this collection, by index. public virtual Attribute this[int index] { get { return (Attribute)(coll[index]); } } // Get an element from this collection, by type. public virtual Attribute this[Type type] { get { foreach(Attribute attr in coll) { if(attr != null && attr.GetType() == type) { return attr; } } return GetDefaultAttribute(type); } } // Determine if this collection contains a particular attribute. public bool Contains(Attribute attr) { return coll.Contains(attr); } // Determine if this collection contains a list of attributes. public bool Contains(Attribute[] attributes) { if(attributes != null) { foreach(Attribute attr in attributes) { if(!Contains(attr)) { return false; } } } return true; } // Get the default attribute value of a particular type. protected Attribute GetDefaultAttribute(Type attributeType) { FieldInfo field = attributeType.GetField ("Default", BindingFlags.Public | BindingFlags.Static); if(field != null) { return (Attribute)(field.GetValue(null)); } else { Attribute attr; attr = (Attribute)(Activator.CreateInstance(attributeType)); if(attr != null && attr.IsDefaultAttribute()) { return attr; } else { return null; } } } // Get an enumerator for this collection. public IEnumerator GetEnumerator() { return coll.GetEnumerator(); } // Determine if an attribute matches something in the collection. public bool Matches(Attribute attr) { foreach(Attribute attr2 in coll) { if(attr2 != null && attr2.Match(attr)) { return true; } } return false; } // Determine if all attributes in a list match something. public bool Matches(Attribute[] attributes) { if(attributes != null) { foreach(Attribute attr in attributes) { if(!Matches(attr)) { return false; } } } return true; } }; // class AttributeCollection #endif // CONFIG_COMPONENT_MODEL }; // namespace System.ComponentModel
using System; using System.Xml; using System.ComponentModel; using System.IO; using System.Collections.Generic; using System.Drawing; namespace InstallerLib { /// <summary> /// Control type. /// </summary> public enum ControlType { /// <summary> /// Undefined. /// </summary> undefined, /// <summary> /// Label with static text. /// </summary> label, /// <summary> /// Checkbox. /// </summary> checkbox, /// <summary> /// Edit box. /// </summary> edit, /// <summary> /// Browse for file or folder button. /// </summary> browse, /// <summary> /// License checkbox and link. /// </summary> license, /// <summary> /// Hyperlink. /// </summary> hyperlink, /// <summary> /// Image. /// </summary> image } /// <summary> /// Controls whether the nested installed check applies to control's enabled, display or both properties. /// </summary> public enum ControlCheckType { /// <summary> /// Apply to the enabled property. /// </summary> enabled, /// <summary> /// Apply to the display property. /// </summary> display, /// <summary> /// Apply to both enabled and display property. /// </summary> both }; /// <summary> /// A dynamic dialog control. /// </summary> [XmlChild(typeof(InstalledCheck))] [XmlChild(typeof(InstalledCheckOperator))] public abstract class Control : XmlClass { public Control(ControlType type) { m_type = type; } private ControlType m_type = ControlType.undefined; [Description("Control type.")] [Required] public ControlType type { get { return m_type; } } private Rectangle m_position; [Description("Control position and size.")] [Category("Layout")] public Rectangle Position { get { return m_position; } set { m_position = value; } } private bool m_enabled = true; [Description("Default enabled state.")] [Category("Layout")] [Required] public bool Enabled { get { return m_enabled; } set { m_enabled = value; } } private bool m_has_value_disabled = false; [Description("When 'true', collect value even if the control is disabled.")] [Category("Value")] [Required] public bool HasValueDisabled { get { return m_has_value_disabled; } set { m_has_value_disabled = value; } } private bool m_display_install = true; [Description("Display control on install.")] [Category("Layout")] [Required] public bool DisplayInstall { get { return m_display_install; } set { m_display_install = value; } } private bool m_display_uninstall = true; [Description("Display control on uninstall.")] [Category("Layout")] [Required] public bool DisplayUninstall { get { return m_display_uninstall; } set { m_display_uninstall = value; } } private ControlCheckType m_check = ControlCheckType.enabled; [Description("Defines how to apply a nested installed check ('enable', 'display' or 'both').")] [Category("Layout")] [Required] public ControlCheckType Check { get { return m_check; } set { m_check = value; } } #region XmlClass Members public override string XmlTag { get { return "control"; } } #endregion protected override void OnXmlWriteTag(XmlWriterEventArgs e) { e.XmlWriter.WriteAttributeString("type", m_type.ToString()); e.XmlWriter.WriteAttributeString("position", XmlRectangle.ToString(m_position)); e.XmlWriter.WriteAttributeString("enabled", m_enabled.ToString()); e.XmlWriter.WriteAttributeString("display_install", m_display_install.ToString()); e.XmlWriter.WriteAttributeString("display_uninstall", m_display_uninstall.ToString()); e.XmlWriter.WriteAttributeString("check", m_check.ToString()); e.XmlWriter.WriteAttributeString("has_value_disabled", m_has_value_disabled.ToString()); base.OnXmlWriteTag(e); } protected override void OnXmlReadTag(XmlElementEventArgs e) { // type ControlType type = ControlType.undefined; ReadAttributeValue(e, "type", ref type); if (type != m_type) { throw new Exception(string.Format("Unexpected type: {0}", type)); } // other ReadAttributeValue(e, "position", ref m_position); ReadAttributeValue(e, "enabled", ref m_enabled); ReadAttributeValue(e, "display_install", ref m_display_install); ReadAttributeValue(e, "display_uninstall", ref m_display_uninstall); ReadAttributeValue(e, "check", ref m_check); ReadAttributeValue(e, "has_value_disabled", ref m_has_value_disabled); base.OnXmlReadTag(e); } public static Control CreateFromXml(XmlElement element) { string xmltype = element.Attributes["type"].InnerText; Control control = null; ControlType type = (ControlType)Enum.Parse(typeof(ControlType), xmltype); switch (type) { case ControlType.label: control = new ControlLabel(); break; case ControlType.checkbox: control = new ControlCheckBox(); break; case ControlType.edit: control = new ControlEdit(); break; case ControlType.browse: control = new ControlBrowse(); break; case ControlType.license: control = new ControlLicense(); break; case ControlType.hyperlink: control = new ControlHyperlink(); break; case ControlType.image: control = new ControlImage(); break; default: throw new Exception(string.Format("Invalid type: {0}", xmltype)); } control.FromXml(element); return control; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: XMLParser and Tree builder internal to BCL ** ** ===========================================================*/ namespace System { using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Security.Permissions; using System.Security; using System.Globalization; using System.IO; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [Serializable] internal enum ConfigEvents { StartDocument = 0, StartDTD = StartDocument + 1, EndDTD = StartDTD + 1, StartDTDSubset = EndDTD + 1, EndDTDSubset = StartDTDSubset + 1, EndProlog = EndDTDSubset + 1, StartEntity = EndProlog + 1, EndEntity = StartEntity + 1, EndDocument = EndEntity + 1, DataAvailable = EndDocument + 1, LastEvent = DataAvailable } [Serializable] internal enum ConfigNodeType { Element = 1, Attribute = Element + 1, Pi = Attribute + 1, XmlDecl = Pi + 1, DocType = XmlDecl + 1, DTDAttribute = DocType + 1, EntityDecl = DTDAttribute + 1, ElementDecl = EntityDecl + 1, AttlistDecl = ElementDecl + 1, Notation = AttlistDecl + 1, Group = Notation + 1, IncludeSect = Group + 1, PCData = IncludeSect + 1, CData = PCData + 1, IgnoreSect = CData + 1, Comment = IgnoreSect + 1, EntityRef = Comment + 1, Whitespace = EntityRef + 1, Name = Whitespace + 1, NMToken = Name + 1, String = NMToken + 1, Peref = String + 1, Model = Peref + 1, ATTDef = Model + 1, ATTType = ATTDef + 1, ATTPresence = ATTType + 1, DTDSubset = ATTPresence + 1, LastNodeType = DTDSubset + 1 } [Serializable] internal enum ConfigNodeSubType { Version = (int)ConfigNodeType.LastNodeType, Encoding = Version + 1, Standalone = Encoding + 1, NS = Standalone + 1, XMLSpace = NS + 1, XMLLang = XMLSpace + 1, System = XMLLang + 1, Public = System + 1, NData = Public + 1, AtCData = NData + 1, AtId = AtCData + 1, AtIdref = AtId + 1, AtIdrefs = AtIdref + 1, AtEntity = AtIdrefs + 1, AtEntities = AtEntity + 1, AtNmToken = AtEntities + 1, AtNmTokens = AtNmToken + 1, AtNotation = AtNmTokens + 1, AtRequired = AtNotation + 1, AtImplied = AtRequired + 1, AtFixed = AtImplied + 1, PentityDecl = AtFixed + 1, Empty = PentityDecl + 1, Any = Empty + 1, Mixed = Any + 1, Sequence = Mixed + 1, Choice = Sequence + 1, Star = Choice + 1, Plus = Star + 1, Questionmark = Plus + 1, LastSubNodeType = Questionmark + 1 } internal abstract class BaseConfigHandler { // These delegates must be at the very start of the object // This is necessary because unmanaged code takes a dependency on this layout // Any changes made to this must be reflected in ConfigHelper.h in ConfigFactory class protected Delegate[] eventCallbacks; public BaseConfigHandler() { InitializeCallbacks(); } private void InitializeCallbacks() { if (eventCallbacks == null) { eventCallbacks = new Delegate[6]; eventCallbacks[0] = new NotifyEventCallback(this.NotifyEvent); eventCallbacks[1] = new BeginChildrenCallback(this.BeginChildren); eventCallbacks[2] = new EndChildrenCallback(this.EndChildren); eventCallbacks[3] = new ErrorCallback(this.Error); eventCallbacks[4] = new CreateNodeCallback(this.CreateNode); eventCallbacks[5] = new CreateAttributeCallback(this.CreateAttribute); } } private delegate void NotifyEventCallback(ConfigEvents nEvent); public abstract void NotifyEvent(ConfigEvents nEvent); private delegate void BeginChildrenCallback(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength); public abstract void BeginChildren(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength); private delegate void EndChildrenCallback(int fEmpty, int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength); public abstract void EndChildren(int fEmpty, int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength); private delegate void ErrorCallback(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); public abstract void Error(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); private delegate void CreateNodeCallback(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); public abstract void CreateNode(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); private delegate void CreateAttributeCallback(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); public abstract void CreateAttribute(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void RunParser(String fileName); } // Class used to build a DOM like tree of parsed XML internal class ConfigTreeParser : BaseConfigHandler { ConfigNode rootNode = null; ConfigNode currentNode = null; String fileName = null; int attributeEntry; String key = null; String [] treeRootPath = null; // element to start tree bool parsing = false; int depth = 0; int pathDepth = 0; int searchDepth = 0; bool bNoSearchPath = false; // Track state for error message formatting String lastProcessed = null; bool lastProcessedEndElement; // NOTE: This parser takes a path eg. /configuration/system.runtime.remoting // and will return a node which matches this. internal ConfigNode Parse(String fileName, String configPath) { return Parse(fileName, configPath, false); } [System.Security.SecuritySafeCritical] // auto-generated internal ConfigNode Parse(String fileName, String configPath, bool skipSecurityStuff) { if (fileName == null) throw new ArgumentNullException("fileName"); Contract.EndContractBlock(); this.fileName = fileName; if (configPath[0] == '/'){ treeRootPath = configPath.Substring(1).Split('/'); pathDepth = treeRootPath.Length - 1; bNoSearchPath = false; } else{ treeRootPath = new String[1]; treeRootPath[0] = configPath; bNoSearchPath = true; } if (!skipSecurityStuff) { (new FileIOPermission( FileIOPermissionAccess.Read, System.IO.Path.GetFullPathInternal( fileName ) )).Demand(); } #pragma warning disable 618 (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert(); #pragma warning restore 618 try { RunParser(fileName); } catch(FileNotFoundException) { throw; // Pass these through unadulterated. } catch(DirectoryNotFoundException) { throw; // Pass these through unadulterated. } catch(UnauthorizedAccessException) { throw; } catch(FileLoadException) { throw; } catch(Exception inner) { String message = GetInvalidSyntaxMessage(); // Neither Exception nor ApplicationException are the "right" exceptions here. // Desktop throws ApplicationException for backwards compatibility. // On Silverlight we don't have ApplicationException, so fall back to Exception. #if FEATURE_CORECLR throw new Exception(message, inner); #else throw new ApplicationException(message, inner); #endif } return rootNode; } public override void NotifyEvent(ConfigEvents nEvent) { BCLDebug.Trace("REMOTE", "NotifyEvent "+((Enum)nEvent).ToString()+"\n"); } public override void BeginChildren(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength) { //Trace("BeginChildren",size,subType,nType,terminal,text,textLength,prefixLength,0); if (!parsing && (!bNoSearchPath && depth == (searchDepth + 1) && String.Compare(text, treeRootPath[searchDepth], StringComparison.Ordinal) == 0)) { searchDepth++; } } public override void EndChildren(int fEmpty, int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)] String text, int textLength, int prefixLength) { lastProcessed = text; lastProcessedEndElement = true; if (parsing) { //Trace("EndChildren",size,subType,nType,terminal,text,textLength,prefixLength,fEmpty); if (currentNode == rootNode) { // End of section of tree which is parsed parsing = false; } currentNode = currentNode.Parent; } else if (nType == ConfigNodeType.Element){ if(depth == searchDepth && String.Compare(text, treeRootPath[searchDepth - 1], StringComparison.Ordinal) == 0) { searchDepth--; depth--; } else depth--; } } public override void Error(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength) { //Trace("Error",size,subType,nType,terminal,text,textLength,prefixLength,0); } public override void CreateNode(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength) { //Trace("CreateNode",size,subType,nType,terminal,text,textLength,prefixLength,0); if (nType == ConfigNodeType.Element) { // New Node lastProcessed = text; lastProcessedEndElement = false; if (parsing || (bNoSearchPath && String.Compare(text, treeRootPath[0], StringComparison.OrdinalIgnoreCase) == 0) || (depth == searchDepth && searchDepth == pathDepth && String.Compare(text, treeRootPath[pathDepth], StringComparison.OrdinalIgnoreCase) == 0 )) { parsing = true; ConfigNode parentNode = currentNode; currentNode = new ConfigNode(text, parentNode); if (rootNode == null) rootNode = currentNode; else parentNode.AddChild(currentNode); } else depth++; } else if (nType == ConfigNodeType.PCData) { // Data node if (currentNode != null) { currentNode.Value = text; } } } public override void CreateAttribute(int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength) { //Trace("CreateAttribute",size,subType,nType,terminal,text,textLength,prefixLength,0); if (parsing) { // if the value of the attribute is null, the parser doesn't come back, so need to store the attribute when the // attribute name is encountered if (nType == ConfigNodeType.Attribute) { attributeEntry = currentNode.AddAttribute(text, ""); key = text; } else if (nType == ConfigNodeType.PCData) { currentNode.ReplaceAttribute(attributeEntry, key, text); } else { String message = GetInvalidSyntaxMessage(); // Neither Exception nor ApplicationException are the "right" exceptions here. // Desktop throws ApplicationException for backwards compatibility. // On Silverlight we don't have ApplicationException, so fall back to Exception. #if FEATURE_CORECLR throw new Exception(message); #else throw new ApplicationException(message); #endif } } } #if _DEBUG [System.Diagnostics.Conditional("_LOGGING")] private void Trace(String name, int size, ConfigNodeSubType subType, ConfigNodeType nType, int terminal, [MarshalAs(UnmanagedType.LPWStr)]String text, int textLength, int prefixLength, int fEmpty) { BCLDebug.Trace("REMOTE","Node "+name); BCLDebug.Trace("REMOTE","text "+text); BCLDebug.Trace("REMOTE","textLength "+textLength); BCLDebug.Trace("REMOTE","size "+size); BCLDebug.Trace("REMOTE","subType "+((Enum)subType).ToString()); BCLDebug.Trace("REMOTE","nType "+((Enum)nType).ToString()); BCLDebug.Trace("REMOTE","terminal "+terminal); BCLDebug.Trace("REMOTE","prefixLength "+prefixLength); BCLDebug.Trace("REMOTE","fEmpty "+fEmpty+"\n"); } #endif private String GetInvalidSyntaxMessage() { String lastProcessedTag = null; if (lastProcessed != null) lastProcessedTag = (lastProcessedEndElement ? "</" : "<") + lastProcessed + ">"; return Environment.GetResourceString("XML_Syntax_InvalidSyntaxInFile", fileName, lastProcessedTag); } } // Node in Tree produced by ConfigTreeParser internal class ConfigNode { String m_name = null; String m_value = null; ConfigNode m_parent = null; List<ConfigNode> m_children = new List<ConfigNode>(5); List<DictionaryEntry> m_attributes = new List<DictionaryEntry>(5); internal ConfigNode(String name, ConfigNode parent) { m_name = name; m_parent = parent; } internal String Name { get {return m_name;} } internal String Value { get {return m_value;} set {m_value = value;} } internal ConfigNode Parent { get {return m_parent;} } internal List<ConfigNode> Children { get {return m_children;} } internal List<DictionaryEntry> Attributes { get {return m_attributes;} } internal void AddChild(ConfigNode child) { child.m_parent = this; m_children.Add(child); } internal int AddAttribute(String key, String value) { m_attributes.Add(new DictionaryEntry(key, value)); return m_attributes.Count-1; } internal void ReplaceAttribute(int index, String key, String value) { m_attributes[index] = new DictionaryEntry(key, value); } #if _DEBUG [System.Diagnostics.Conditional("_LOGGING")] internal void Trace() { BCLDebug.Trace("REMOTE","************ConfigNode************"); BCLDebug.Trace("REMOTE","Name = "+m_name); if (m_value != null) BCLDebug.Trace("REMOTE","Value = "+m_value); if (m_parent != null) BCLDebug.Trace("REMOTE","Parent = "+m_parent.Name); for (int i=0; i<m_attributes.Count; i++) { DictionaryEntry de = (DictionaryEntry)m_attributes[i]; BCLDebug.Trace("REMOTE","Key = "+de.Key+" Value = "+de.Value); } for (int i=0; i<m_children.Count; i++) { ((ConfigNode)m_children[i]).Trace(); } } #endif } }
namespace Economy.scripts.Messages { using System; using System.Linq; using System.Text; using EconConfig; using ProtoBuf; using Sandbox.ModAPI; [ProtoContract] public class MessageMarketManageNpc : MessageBase { [ProtoMember(1)] public NpcMarketManage CommandType; [ProtoMember(2)] public string MarketName; [ProtoMember(3)] public decimal X; [ProtoMember(4)] public decimal Y; [ProtoMember(5)] public decimal Z; [ProtoMember(6)] public decimal Size; [ProtoMember(7)] public MarketZoneType Shape; [ProtoMember(8)] public string OldMarketName; public static void SendAddMessage(string marketName, decimal x, decimal y, decimal z, decimal size, MarketZoneType shape) { ConnectionHelper.SendMessageToServer(new MessageMarketManageNpc { CommandType = NpcMarketManage.Add, MarketName = marketName, X = x, Y = y, Z = z, Size = size, Shape = shape }); } public static void SendDeleteMessage(string marketName) { ConnectionHelper.SendMessageToServer(new MessageMarketManageNpc { CommandType = NpcMarketManage.Delete, MarketName = marketName }); } public static void SendRenameMessage(string oldMarketName, string newMarketName) { ConnectionHelper.SendMessageToServer(new MessageMarketManageNpc { CommandType = NpcMarketManage.Rename, OldMarketName = oldMarketName, MarketName = newMarketName }); } public static void SendMoveMessage(string marketName, decimal x, decimal y, decimal z, decimal size, MarketZoneType shape) { ConnectionHelper.SendMessageToServer(new MessageMarketManageNpc { CommandType = NpcMarketManage.Move, MarketName = marketName, X = x, Y = y, Z = z, Size = size, Shape = shape }); } public static void SendListMessage() { ConnectionHelper.SendMessageToServer(new MessageMarketManageNpc { CommandType = NpcMarketManage.List }); } public override void ProcessClient() { // never processed on client } public override void ProcessServer() { // update our own timestamp here AccountManager.UpdateLastSeen(SenderSteamId, SenderLanguage); EconomyScript.Instance.ServerLogger.WriteVerbose("Manage Npc Market Request for from '{0}'", SenderSteamId); var player = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); if (player == null || !player.IsAdmin()) // hold on there, are we an admin first? return; switch (CommandType) { case NpcMarketManage.Add: { if (string.IsNullOrWhiteSpace(MarketName) || MarketName == "*") { MessageClientTextMessage.SendMessage(SenderSteamId, "NPC ADD", "Invalid name supplied for the market name."); return; } var checkMarket = EconomyScript.Instance.Data.Markets.FirstOrDefault(m => m.DisplayName.Equals(MarketName, StringComparison.InvariantCultureIgnoreCase)); if (checkMarket != null) { MessageClientTextMessage.SendMessage(SenderSteamId, "NPC ADD", "A market of name '{0}' already exists.", checkMarket.DisplayName); return; } // TODO: market inside market check? EconDataManager.CreateNpcMarket(MarketName, X, Y, Z, Size, Shape); MessageClientTextMessage.SendMessage(SenderSteamId, "NPC ADD", "A new market called '{0}' has been created.", MarketName); } break; case NpcMarketManage.Delete: { var market = EconomyScript.Instance.Data.Markets.FirstOrDefault(m => m.DisplayName.Equals(MarketName, StringComparison.InvariantCultureIgnoreCase)); if (market == null) { var markets = EconomyScript.Instance.Data.Markets.Where(m => m.DisplayName.IndexOf(MarketName, StringComparison.InvariantCultureIgnoreCase) >= 0).ToArray(); if (markets.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "NPC DELETE", "The specified market name could not be found."); return; } if (markets.Length > 1) { var str = new StringBuilder(); str.Append("The specified market name could not be found.\r\n Which did you mean?\r\n"); foreach (var m in markets) str.AppendLine(m.DisplayName); MessageClientDialogMessage.SendMessage(SenderSteamId, "NPC DELETE", " ", str.ToString()); return; } market = markets[0]; } EconomyScript.Instance.Data.Markets.Remove(market); MessageClientTextMessage.SendMessage(SenderSteamId, "NPC DELETE", "The market '{0}' has been removed and all inventory.", market.DisplayName); } break; case NpcMarketManage.List: { var str = new StringBuilder(); foreach (var market in EconomyScript.Instance.Data.Markets) { if (market.MarketId != EconomyConsts.NpcMerchantId) continue; str.AppendFormat("Market: {0}\r\n", market.DisplayName); str.AppendFormat("{0}", market.MarketZoneType); if (market.MarketZoneType == MarketZoneType.FixedSphere && market.MarketZoneSphere.HasValue) str.AppendFormat(" Center Position=X:{0:N} | Y:{1:N} | Z:{2:N} Radius={3:N}m\r\n\r\n", market.MarketZoneSphere.Value.Center.X, market.MarketZoneSphere.Value.Center.Y, market.MarketZoneSphere.Value.Center.Z, market.MarketZoneSphere.Value.Radius); else if (market.MarketZoneType == MarketZoneType.FixedBox && market.MarketZoneBox.HasValue) str.AppendFormat(" Center Position=X:{0:N} | Y:{1:N} | Z:{2:N} Size={3:N}m\r\n\r\n", market.MarketZoneBox.Value.Center.X, market.MarketZoneBox.Value.Center.Y, market.MarketZoneBox.Value.Center.Z, market.MarketZoneBox.Value.Size.X); else str.AppendLine("\r\n"); } MessageClientDialogMessage.SendMessage(SenderSteamId, "NPC Market List", " ", str.ToString()); } break; case NpcMarketManage.Rename: { var market = EconomyScript.Instance.Data.Markets.FirstOrDefault(m => m.DisplayName.Equals(OldMarketName, StringComparison.InvariantCultureIgnoreCase)); if (market == null) { var markets = EconomyScript.Instance.Data.Markets.Where(m => m.DisplayName.IndexOf(OldMarketName, StringComparison.InvariantCultureIgnoreCase) >= 0).ToArray(); if (markets.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "NPC RENAME", "The specified market name could not be found."); return; } if (markets.Length > 1) { var str = new StringBuilder(); str.Append("The specified market name could not be found.\r\n Which did you mean?\r\n"); foreach (var m in markets) str.AppendLine(m.DisplayName); MessageClientDialogMessage.SendMessage(SenderSteamId, "NPC RENAME", " ", str.ToString()); return; } market = markets[0]; } if (string.IsNullOrWhiteSpace(MarketName) || MarketName == "*") { MessageClientTextMessage.SendMessage(SenderSteamId, "NPC RENAME", "Invalid name supplied for the market name."); return; } var checkMarket = EconomyScript.Instance.Data.Markets.FirstOrDefault(m => m.DisplayName.Equals(MarketName, StringComparison.InvariantCultureIgnoreCase)); if (checkMarket != null) { MessageClientTextMessage.SendMessage(SenderSteamId, "NPC RENAME", "A market of name '{0}' already exists.", checkMarket.DisplayName); return; } var oldName = market.DisplayName; market.DisplayName = MarketName; MessageClientTextMessage.SendMessage(SenderSteamId, "NPC RENAME", "The market '{0}' has been renamed to '{1}.", oldName, market.DisplayName); } break; case NpcMarketManage.Move: { var market = EconomyScript.Instance.Data.Markets.FirstOrDefault(m => m.DisplayName.Equals(MarketName, StringComparison.InvariantCultureIgnoreCase)); if (market == null) { var markets = EconomyScript.Instance.Data.Markets.Where(m => m.DisplayName.IndexOf(MarketName, StringComparison.InvariantCultureIgnoreCase) >= 0).ToArray(); if (markets.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "NPC MOVE", "The specified market name could not be found."); return; } if (markets.Length > 1) { var str = new StringBuilder(); str.Append("The specified market name could not be found.\r\n Which did you mean?\r\n"); foreach (var m in markets) str.AppendLine(m.DisplayName); MessageClientDialogMessage.SendMessage(SenderSteamId, "NPC MOVE", " ", str.ToString()); return; } market = markets[0]; } EconDataManager.SetMarketShape(market, X, Y, Z, Size, Shape); MessageClientTextMessage.SendMessage(SenderSteamId, "NPC MOVE", "The market '{0}' has been moved and resized.", market.DisplayName); } break; } } } }
//--------------------------------------------------------------------------- // // <copyright file="FocusTracker.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Class that tracks Win32 focus changes // // History: // 06/17/2003 : BrendanM Ported to WCP // //--------------------------------------------------------------------------- using System; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Diagnostics; using MS.Win32; namespace MS.Internal.Automation { // Class that tracks Win32 focus changes internal class FocusTracker : WinEventWrap { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors // Ctor - provide the WinEvent identifiers used to track focus changes internal FocusTracker() : base(_eventIds) { // Intentionally not setting the callback for the base WinEventWrap since the WinEventProc override // in this class calls RaiseEventInThisClientOnly to actually raise the event to the client. } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods // WinEventProc - override to process WinEvents internal override void WinEventProc(int eventId, IntPtr hwnd, int idObject, int idChild, uint eventTime) { if (hwnd != IntPtr.Zero) { switch(eventId) { case NativeMethods.EVENT_OBJECT_FOCUS: OnEventObjectFocus(eventId, hwnd, idObject, idChild, eventTime); break; case NativeMethods.EVENT_SYSTEM_MENUSTART: OnEventSystemMenuStart(eventId, hwnd, idObject, idChild, eventTime); break; case NativeMethods.EVENT_SYSTEM_MENUEND: OnEventSystemMenuEnd(eventId, hwnd, idObject, idChild, eventTime); break; case NativeMethods.EVENT_SYSTEM_SWITCHSTART: OnEventSystemMenuStart(eventId, hwnd, idObject, idChild, eventTime); break; case NativeMethods.EVENT_SYSTEM_SWITCHEND: OnEventSystemMenuEnd(eventId, hwnd, idObject, idChild, eventTime); break; case NativeMethods.EVENT_OBJECT_DESTROY: OnEventObjectDestroy(eventId, hwnd, idObject, idChild, eventTime); break; case NativeMethods.EVENT_SYSTEM_MENUPOPUPSTART: OnEventSystemMenuPopupStart(eventId, hwnd, idObject, idChild, eventTime); break; case NativeMethods.EVENT_SYSTEM_CAPTURESTART: OnEventSystemCaptureStart(eventId, hwnd, idObject, idChild, eventTime); break; case NativeMethods.EVENT_SYSTEM_CAPTUREEND: OnEventSystemCaptureEnd(eventId, hwnd, idObject, idChild, eventTime); break; } } } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // HandleFocusChange - Called when a WinEvent we're listening to indicates the // focus has changed. This is where the callback to the client is queued. private void HandleFocusChange(IntPtr hwnd, Accessible acc, int idObject, int idChild, uint eventTime) { // If there is an hwnd then notify of a focus change if (hwnd != IntPtr.Zero) { Debug.Assert(acc != null, "HandleFocusChange got hwnd and null IAccessible"); // Create an event args and get the source logical element AutomationFocusChangedEventArgs e = new InternalAutomationFocusChangedEventArgs(idObject, idChild, eventTime); AutomationElement srcEl = GetFocusedElementFromWinEvent(hwnd, idObject, idChild); if (srcEl == null) { // Don't raise focus change events for UI that is gone. This has been seen when toolbar menus are // being manipulated (e.g. mnu.SubMenu("File").MenuItems("Close").Click() in MITA). We should be // seeing another focus change soon and with that event we can re-establish focus. return; } // Check that item is actually focused // Don't do this for statics - the controls in the color picker are statics, and // they get focus, but OLEACC assumes statics don't get focus, so never sets the // focus bit. So, for now, assume statics that send focus do actually have focus. if (!Accessible.IsStatic(hwnd) && !Accessible.IsComboDropdown(hwnd)) { // instead of depending on oleacc to see if something has focus ask provider if (!(bool)srcEl.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty)) { return; } } // Do notifies ClientEventManager.RaiseEventInThisClientOnly(AutomationElement.AutomationFocusChangedEvent, srcEl, e); } // Keep track of where we are right now (may be unknown/null) _accCurrent = acc; } // We need to treat MSAA's FOCUS winevents differently depending on the OBJID - // OBJID_CLIENT gets routed to the proxies; _MENU and _SYSMENU get speical treatment. private AutomationElement GetFocusedElementFromWinEvent(IntPtr hwnd, int idObject, int idChild) { try { IRawElementProviderSimple provider = null; // These are the only object types that oleacc proxies allow to take focus. // (Native IAccessibles can send focus for other custom OBJID valus, but those are no use // to us.) // Try and get providers for them ourself - if we don't get anything, then // defer to core to get the element for the HWND itself. if (idObject == UnsafeNativeMethods.OBJID_CLIENT) { // regular focus - pass it off to a proxy... provider = ProxyManager.ProxyProviderFromHwnd(NativeMethods.HWND.Cast(hwnd), idChild, UnsafeNativeMethods.OBJID_CLIENT); } else if (idObject == UnsafeNativeMethods.OBJID_MENU) { // menubar focus - see if there's a menubar pseudo-proxy registered... ClientSideProviderFactoryCallback factory = ProxyManager.NonClientMenuBarProxyFactory; if (factory != null) { provider = factory(hwnd, idChild, idObject); } } else if (idObject == UnsafeNativeMethods.OBJID_SYSMENU) { // system menu box focus - see if there's a sysmenu pseudo-proxy registered... ClientSideProviderFactoryCallback factory = ProxyManager.NonClientSysMenuProxyFactory; if (factory != null) { provider = factory(hwnd, idChild, idObject); } } else if (idObject <= 0) { return null; } else { // This covers OBJID_CLIENT and custom OBJID cases. // Pass it to the proxy manager: most proxies will just handle OBJID_CLIENT, // but the MSAA proxy can potentally handle other OBJID values. provider = ProxyManager.ProxyProviderFromHwnd(NativeMethods.HWND.Cast(hwnd), idChild, idObject); } if(provider != null) { // Ask the fragment root if any of its children really have the focus IRawElementProviderFragmentRoot fragment = provider as IRawElementProviderFragmentRoot; if (fragment != null) { // if we get back something that is different than what we started with and its not null // use that instead. This is here to get the subset link in the listview but could be usefull // for listview subitems as well. IRawElementProviderSimple realFocus = fragment.GetFocus(); if(realFocus != null && !Object.ReferenceEquals(realFocus, provider)) { provider = realFocus; } } SafeNodeHandle hnode = UiaCoreApi.UiaNodeFromProvider(provider); return AutomationElement.Wrap(hnode); } else { // Didn't find a proxy to handle this hwnd - pass off to core... return AutomationElement.FromHandle(hwnd); } } catch( Exception e ) { if( Misc.IsCriticalException( e ) ) throw; return null; } } // OnEventObjectFocus - process an EventObjectFocus WinEvent. private void OnEventObjectFocus(int eventId, IntPtr hwnd, int idObject, int idChild, uint eventTime) { Accessible acc = Accessible.Create(hwnd, idObject, idChild); if (acc == null) { return; } // Keep track of last focused non-menu item, so we can restore focus when we leave menu mode if (!_fInMenu) { _accLastBeforeMenu = acc; _hwndLastBeforeMenu = hwnd; _idLastObject = idObject; _idLastChild = idChild; } HandleFocusChange(hwnd, acc, idObject, idChild, eventTime); } // OnEventSystemMenuStart - process an EventSystemMenuStart WinEvent. private void OnEventSystemMenuStart(int eventId, IntPtr hwnd, int idObject, int idChild, uint eventTime) { // No immediate effect on focus - we expect to get a FOCUS event after this. _fInMenu = true; } // OnEventSystemMenuEnd - process an EventSystemMenuEnd WinEvent. private void OnEventSystemMenuEnd(int eventId, IntPtr hwnd, int idObject, int idChild, uint eventTime) { // Restore focus to where it was before the menu appeared if (_fInMenu) { _fInMenu = false; if (_accLastBeforeMenu != null) { HandleFocusChange(_hwndLastBeforeMenu, _accLastBeforeMenu, _idLastObject, _idLastChild, eventTime); } } } // OnEventObjectDestroy - process an EventObjectDestroy WinEvent. private void OnEventObjectDestroy(int eventId, IntPtr hwnd, int idObject, int idChild, uint eventTime) { // Check if still alive. Ignore caret destroys - we're only interesed in 'real' objects here... if (idObject != UnsafeNativeMethods.OBJID_CARET && _accCurrent != null) { bool fDead = false; try { int dwState = _accCurrent.State; IntPtr hwndCur = _accCurrent.Window; if (hwndCur == IntPtr.Zero || !SafeNativeMethods.IsWindow(NativeMethods.HWND.Cast(hwndCur))) { fDead = true; } } catch( Exception e ) { if( Misc.IsCriticalException( e ) ) throw; fDead = true; } if (fDead) { // It's dead... HandleFocusChange(IntPtr.Zero, null, 0, 0, eventTime); } } } // OnEventSystemMenuPopupStart - process an EventSystemMenuPopupStart WinEvent. private void OnEventSystemMenuPopupStart(int eventId, IntPtr hwnd, int idObject, int idChild, uint eventTime) { Accessible acc = Accessible.Create(hwnd, idObject, idChild); if( acc == null ) return; HandleFocusChange(hwnd, acc, idObject, idChild, eventTime); } // OnEventSystemCaptureStart - process an EventSystemCaptureStart WinEvent. private void OnEventSystemCaptureStart(int eventId, IntPtr hwnd, int idObject, int idChild, uint eventTime) { // Deal only with Combolbox dropdowns... if (Accessible.IsComboDropdown(hwnd)) { // Need to get id of focused item... try { IntPtr i = Misc.SendMessageTimeout(NativeMethods.HWND.Cast(hwnd), UnsafeNativeMethods.LB_GETCURSEL, IntPtr.Zero, IntPtr.Zero); Accessible acc = Accessible.Create(hwnd, UnsafeNativeMethods.OBJID_CLIENT, i.ToInt32() + 1); if (acc == null) return; HandleFocusChange(hwnd, acc, idObject, idChild, eventTime); } catch (TimeoutException) { // Ignore } } } // OnEventSystemCaptureEnd - process an EventSystemCaptureEnd WinEvent. private void OnEventSystemCaptureEnd(int eventId, IntPtr hwnd, int idObject, int idChild, uint eventTime) { // Deal only with Combolbox dropdowns... if (Accessible.IsComboDropdown(hwnd)) { SafeNativeMethods.GUITHREADINFO guiThreadInfo = new SafeNativeMethods.GUITHREADINFO(); if (!Misc.GetGUIThreadInfo(0, ref guiThreadInfo)) { return; } Accessible acc = Accessible.Create(guiThreadInfo.hwndFocus, UnsafeNativeMethods.OBJID_CLIENT, 0); if (acc == null) return; HandleFocusChange(hwnd, acc, idObject, idChild, eventTime); } } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private static int [] _eventIds = new int [] { NativeMethods.EVENT_OBJECT_FOCUS, NativeMethods.EVENT_SYSTEM_MENUSTART, NativeMethods.EVENT_SYSTEM_MENUPOPUPSTART, NativeMethods.EVENT_SYSTEM_MENUEND, NativeMethods.EVENT_OBJECT_DESTROY, NativeMethods.EVENT_SYSTEM_CAPTURESTART, NativeMethods.EVENT_SYSTEM_CAPTUREEND, NativeMethods.EVENT_SYSTEM_SWITCHSTART, NativeMethods.EVENT_SYSTEM_SWITCHEND }; private Accessible _accCurrent; // the IAccessible currently being handled private Accessible _accLastBeforeMenu; // the last IAccessible before a menu got focus private IntPtr _hwndLastBeforeMenu; // the last hwnd before a menu got focus private int _idLastObject; // the last idObject before a menu got focus private int _idLastChild; // the last idChild before a menu got focus private bool _fInMenu; // true if there's a menu up #endregion Private Fields } }
using Newtonsoft.Json; 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; namespace Posh.Socrata.Service.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using FluentAssertions.Execution; #if !OLD_MSTEST && !NUNIT using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #elif NUNIT using TestClassAttribute = NUnit.Framework.TestFixtureAttribute; using TestMethodAttribute = NUnit.Framework.TestCaseAttribute; using AssertFailedException = NUnit.Framework.AssertionException; using TestInitializeAttribute = NUnit.Framework.SetUpAttribute; using Assert = NUnit.Framework.Assert; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace FluentAssertions.Specs { [TestClass] public class NullableBooleanAssertionSpecs { [TestMethod] public void When_asserting_nullable_boolean_value_with_a_value_to_have_a_value_it_should_succeed() { bool? nullableBoolean = true; nullableBoolean.Should().HaveValue(); } [TestMethod] public void When_asserting_nullable_boolean_value_without_a_value_to_have_a_value_it_should_fail() { bool? nullableBoolean = null; Action act = () => nullableBoolean.Should().HaveValue(); act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void When_asserting_nullable_boolean_value_without_a_value_to_have_a_value_it_should_fail_with_descriptive_message() { bool? nullableBoolean = null; var assertions = nullableBoolean.Should(); assertions.Invoking(x => x.HaveValue("because we want to test the failure {0}", "message")) .ShouldThrow<AssertFailedException>() .WithMessage("Expected a value because we want to test the failure message."); } [TestMethod] public void When_asserting_nullable_boolean_value_without_a_value_to_be_null_it_should_succeed() { bool? nullableBoolean = null; nullableBoolean.Should().NotHaveValue(); } [TestMethod] public void When_asserting_nullable_boolean_value_with_a_value_to_be_null_it_should_fail() { bool? nullableBoolean = true; Action act = () => nullableBoolean.Should().NotHaveValue(); act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void When_asserting_nullable_boolean_value_with_a_value_to_be_null_it_should_fail_with_descriptive_message() { bool? nullableBoolean = true; var assertions = nullableBoolean.Should(); assertions.Invoking(x => x.NotHaveValue("because we want to test the failure {0}", "message")) .ShouldThrow<AssertFailedException>() .WithMessage("Did not expect a value because we want to test the failure message, but found True."); } [TestMethod] public void When_asserting_boolean_null_value_is_false_it_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- bool? nullableBoolean = null; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableBoolean.Should().BeFalse("we want to test the failure {0}", "message"); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- action.ShouldThrow<AssertFailedException>() .WithMessage("Expected False because we want to test the failure message, but found <null>."); } [TestMethod] public void When_asserting_boolean_null_value_is_true_it_sShould_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- bool? nullableBoolean = null; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableBoolean.Should().BeTrue("we want to test the failure {0}", "message"); //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- action.ShouldThrow<AssertFailedException>() .WithMessage("Expected True because we want to test the failure message, but found <null>."); } [TestMethod] public void When_asserting_boolean_null_value_to_be_equal_to_different_nullable_boolean_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- bool? nullableBoolean = null; bool? differentNullableBoolean = false; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableBoolean.Should().Be(differentNullableBoolean, "we want to test the failure {0}", "message"); //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- action.ShouldThrow<AssertFailedException>() .WithMessage("Expected False because we want to test the failure message, but found <null>."); } [TestMethod] public void When_asserting_boolean_null_value_to_be_equal_to_null_it_sShould_succeed() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- bool? nullableBoolean = null; bool? otherNullableBoolean = null; //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- Action action = () => nullableBoolean.Should().Be(otherNullableBoolean); //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [TestMethod] public void When_asserting_true_is_not_false_it_should_succeed() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? trueBoolean = true; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => trueBoolean.Should().NotBeFalse(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [TestMethod] public void When_asserting_null_is_not_false_it_should_succeed() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? nullValue = null; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => nullValue.Should().NotBeFalse(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [TestMethod] public void When_asserting_false_is_not_false_it_should_fail_with_descriptive_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? falseBoolean = false; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => falseBoolean.Should().NotBeFalse("we want to test the failure message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldThrow<AssertFailedException>() .WithMessage("Expected*nullable*boolean*not*False*because we want to test the failure message, but found False."); } [TestMethod] public void When_asserting_false_is_not_true_it_should_succeed() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? trueBoolean = false; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => trueBoolean.Should().NotBeTrue(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [TestMethod] public void When_asserting_null_is_not_true_it_should_succeed() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? nullValue = null; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => nullValue.Should().NotBeTrue(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldNotThrow(); } [TestMethod] public void When_asserting_true_is_not_true_it_should_fail_with_descriptive_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- bool? falseBoolean = true; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action action = () => falseBoolean.Should().NotBeTrue("we want to test the failure message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- action.ShouldThrow<AssertFailedException>() .WithMessage("Expected*nullable*boolean*not*True*because we want to test the failure message, but found True."); } [TestMethod] public void Should_support_chaining_constraints_with_and() { bool? nullableBoolean = true; nullableBoolean.Should() .HaveValue() .And .BeTrue(); } } }
// Copyright 2017 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 GoogleCloudExtension; using GoogleCloudExtension.CloudExplorer; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Collections.Generic; using System.Threading.Tasks; namespace GoogleCloudExtensionUnitTests.CloudExplorer { [TestClass] public class SourceRootViewModelBaseTests : ExtensionTestBase { private const string MockExceptionMessage = "MockException"; private const string MockRootCaption = "MockRootCaption"; private const string MockErrorPlaceholderCaption = "MockErrorPlaceholder"; private const string MockNoItemsPlaceholderCaption = "MockNoItemsPlaceholder"; private const string MockLoadingPlaceholderCaption = "LoadingPlaceholder"; private const string ChildCaption = "ChildCaption"; private static readonly TreeLeaf s_loadingPlaceholder = new TreeLeaf { Caption = MockLoadingPlaceholderCaption, IsLoading = true }; private static readonly TreeLeaf s_noItemsPlaceholder = new TreeLeaf { Caption = MockNoItemsPlaceholderCaption, IsWarning = true }; private static readonly TreeLeaf s_errorPlaceholder = new TreeLeaf { Caption = MockErrorPlaceholderCaption, IsError = true }; private static readonly TreeNode s_childNode = new TreeNode { Caption = ChildCaption }; private ICloudSourceContext _mockedContext; private TestableSourceRootViewModelBase _objectUnderTest; [TestInitialize] public void BeforeEach() { _mockedContext = Mock.Of<ICloudSourceContext>(); _objectUnderTest = new TestableSourceRootViewModelBase(); } private class TestableSourceRootViewModelBase : SourceRootViewModelBase { public TaskCompletionSource<IList<TreeNode>> LoadDataSource = new TaskCompletionSource<IList<TreeNode>>(); /// <summary> /// Returns the caption to use for the root node for this data source. /// </summary> public override string RootCaption { get; } = MockRootCaption; /// <summary> /// Returns the tree node to use when there's an error loading data. /// </summary> public override TreeLeaf ErrorPlaceholder { get; } = s_errorPlaceholder; /// <summary> /// Returns the tree node to use when there's no data returned by this data source. /// </summary> public override TreeLeaf NoItemsPlaceholder { get; } = s_noItemsPlaceholder; /// <summary> /// Returns the tree node to use while loading data. /// </summary> public override TreeLeaf LoadingPlaceholder { get; } = s_loadingPlaceholder; /// <summary> /// Returns the tree node to use when we detect that the necessary APIs are not enabled. /// </summary> public override TreeLeaf ApiNotEnabledPlaceholder { get; } /// <summary> /// Returns the names of the required APIs for the source. /// </summary> public override IList<string> RequiredApis { get; } /// <summary> /// Override this function to load and display the data in the control. /// </summary> protected override async Task LoadDataOverrideAsync() { LoadDataOverrideCallCount++; IList<TreeNode> children; try { children = await LoadDataSource.Task; } finally { LoadDataSource = new TaskCompletionSource<IList<TreeNode>>(); } Children.Clear(); foreach (TreeNode child in children) { Children.Add(child); } } public int LoadDataOverrideCallCount { get; private set; } } [TestMethod] public void TestInitialConditions() { Assert.AreEqual(0, _objectUnderTest.LoadDataOverrideCallCount); Assert.IsNull(_objectUnderTest.Context); Assert.IsNull(_objectUnderTest.Icon); Assert.IsNull(_objectUnderTest.Caption); Assert.AreEqual(0, _objectUnderTest.Children.Count); } [TestMethod] public void TestInitialize() { _objectUnderTest.Initialize(_mockedContext); Assert.AreEqual(0, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(_mockedContext, _objectUnderTest.Context); Assert.AreEqual(_objectUnderTest.RootIcon, _objectUnderTest.Icon); Assert.AreEqual(_objectUnderTest.RootCaption, _objectUnderTest.Caption); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_loadingPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestNotExpanded() { _objectUnderTest.IsExpanded = false; await _objectUnderTest.LoadingTask; Assert.AreEqual(0, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(0, _objectUnderTest.Children.Count); } [TestMethod] public async Task TestLoadingNoCredentials() { CredentialStoreMock.SetupGet(cs => cs.CurrentAccount).Returns(() => null); _objectUnderTest.IsExpanded = true; await _objectUnderTest.LoadingTask; Assert.AreEqual(0, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); var child = _objectUnderTest.Children[0] as TreeLeaf; Assert.IsNotNull(child); Assert.AreEqual(Resources.CloudExplorerNoLoggedInMessage, child.Caption); Assert.IsFalse(child.IsLoading); Assert.IsFalse(child.IsWarning); Assert.IsTrue(child.IsError); } [TestMethod] public async Task TestLoadingNoProject() { CredentialStoreMock.SetupGet(cs => cs.CurrentProjectId).Returns(() => null); _objectUnderTest.IsExpanded = true; await _objectUnderTest.LoadingTask; Assert.AreEqual(0, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); var child = _objectUnderTest.Children[0] as TreeLeaf; Assert.IsNotNull(child); Assert.AreEqual(Resources.CloudExplorerNoProjectSelectedMessage, child.Caption); Assert.IsFalse(child.IsLoading); Assert.IsFalse(child.IsWarning); Assert.IsTrue(child.IsError); } [TestMethod] public void TestLoading() { _objectUnderTest.Initialize(_mockedContext); _objectUnderTest.IsExpanded = true; Assert.AreEqual(1, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_loadingPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestLoadingError() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; Assert.AreEqual(1, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_errorPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestLoadingNoItems() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode>()); await _objectUnderTest.LoadingTask; Assert.AreEqual(1, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_noItemsPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestLoadingSuccess() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode> { s_childNode }); await _objectUnderTest.LoadingTask; Assert.AreEqual(1, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_childNode, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestDoubleLoading() { _objectUnderTest.Initialize(_mockedContext); _objectUnderTest.IsExpanded = true; _objectUnderTest.IsExpanded = false; _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode>()); await _objectUnderTest.LoadingTask; _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; Assert.AreEqual(1, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_noItemsPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestReloading() { _objectUnderTest.Initialize(_mockedContext); _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode>()); await _objectUnderTest.LoadingTask; _objectUnderTest.IsExpanded = false; _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; Assert.AreEqual(1, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_noItemsPlaceholder.Caption, _objectUnderTest.Children[0].Caption); } [TestMethod] public async Task TestRefreshingUninitialized() { _objectUnderTest.Refresh(); await _objectUnderTest.LoadingTask; Assert.AreEqual(0, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(0, _objectUnderTest.Children.Count); } [TestMethod] public async Task TestRefreshingUnloaded() { _objectUnderTest.Initialize(_mockedContext); _objectUnderTest.Refresh(); await _objectUnderTest.LoadingTask; Assert.AreEqual(0, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_loadingPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestRefreshOnLoading() { _objectUnderTest.Initialize(_mockedContext); _objectUnderTest.IsExpanded = true; _objectUnderTest.Refresh(); _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode>()); await _objectUnderTest.LoadingTask; _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; Assert.AreEqual(1, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_noItemsPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestRefreshLoading() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode>()); await _objectUnderTest.LoadingTask; _objectUnderTest.Refresh(); Assert.AreEqual(2, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_loadingPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestRefreshLoadError() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode>()); await _objectUnderTest.LoadingTask; _objectUnderTest.Refresh(); _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; Assert.AreEqual(2, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_errorPlaceholder, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestRefreshLoadNoItems() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; _objectUnderTest.Refresh(); _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode> { s_childNode }); await _objectUnderTest.LoadingTask; Assert.AreEqual(2, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_childNode, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestRefreshLoadSuccess() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; _objectUnderTest.Refresh(); _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode> { s_childNode }); await _objectUnderTest.LoadingTask; Assert.AreEqual(2, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_childNode, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestDoubleRefresh() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode>()); await _objectUnderTest.LoadingTask; _objectUnderTest.Refresh(); _objectUnderTest.Refresh(); _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode> { s_childNode }); await _objectUnderTest.LoadingTask; _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; Assert.AreEqual(2, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_childNode, _objectUnderTest.Children[0]); } [TestMethod] public async Task TestRefreshAgain() { _objectUnderTest.IsExpanded = true; _objectUnderTest.LoadDataSource.SetException(new CloudExplorerSourceException(MockExceptionMessage)); await _objectUnderTest.LoadingTask; _objectUnderTest.Refresh(); _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode>()); await _objectUnderTest.LoadingTask; _objectUnderTest.Refresh(); _objectUnderTest.LoadDataSource.SetResult(new List<TreeNode> { s_childNode }); await _objectUnderTest.LoadingTask; Assert.AreEqual(3, _objectUnderTest.LoadDataOverrideCallCount); Assert.AreEqual(1, _objectUnderTest.Children.Count); Assert.AreEqual(s_childNode, _objectUnderTest.Children[0]); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.Cx.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedEntityTypesClientTest { [xunit::FactAttribute] public void GetEntityTypeRequestObject() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); GetEntityTypeRequest request = new GetEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), LanguageCode = "language_code2f6c7160", }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.GetEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType response = client.GetEntityType(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetEntityTypeRequestObjectAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); GetEntityTypeRequest request = new GetEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), LanguageCode = "language_code2f6c7160", }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.GetEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType responseCallSettings = await client.GetEntityTypeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); EntityType responseCancellationToken = await client.GetEntityTypeAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetEntityType() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); GetEntityTypeRequest request = new GetEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.GetEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType response = client.GetEntityType(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetEntityTypeAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); GetEntityTypeRequest request = new GetEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.GetEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType responseCallSettings = await client.GetEntityTypeAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); EntityType responseCancellationToken = await client.GetEntityTypeAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetEntityTypeResourceNames() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); GetEntityTypeRequest request = new GetEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.GetEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType response = client.GetEntityType(request.EntityTypeName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetEntityTypeResourceNamesAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); GetEntityTypeRequest request = new GetEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.GetEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType responseCallSettings = await client.GetEntityTypeAsync(request.EntityTypeName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); EntityType responseCancellationToken = await client.GetEntityTypeAsync(request.EntityTypeName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateEntityTypeRequestObject() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); CreateEntityTypeRequest request = new CreateEntityTypeRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), EntityType = new EntityType(), LanguageCode = "language_code2f6c7160", }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.CreateEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType response = client.CreateEntityType(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateEntityTypeRequestObjectAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); CreateEntityTypeRequest request = new CreateEntityTypeRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), EntityType = new EntityType(), LanguageCode = "language_code2f6c7160", }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.CreateEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType responseCallSettings = await client.CreateEntityTypeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); EntityType responseCancellationToken = await client.CreateEntityTypeAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateEntityType() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); CreateEntityTypeRequest request = new CreateEntityTypeRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), EntityType = new EntityType(), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.CreateEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType response = client.CreateEntityType(request.Parent, request.EntityType); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateEntityTypeAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); CreateEntityTypeRequest request = new CreateEntityTypeRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), EntityType = new EntityType(), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.CreateEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType responseCallSettings = await client.CreateEntityTypeAsync(request.Parent, request.EntityType, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); EntityType responseCancellationToken = await client.CreateEntityTypeAsync(request.Parent, request.EntityType, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateEntityTypeResourceNames() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); CreateEntityTypeRequest request = new CreateEntityTypeRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), EntityType = new EntityType(), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.CreateEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType response = client.CreateEntityType(request.ParentAsAgentName, request.EntityType); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateEntityTypeResourceNamesAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); CreateEntityTypeRequest request = new CreateEntityTypeRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), EntityType = new EntityType(), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.CreateEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType responseCallSettings = await client.CreateEntityTypeAsync(request.ParentAsAgentName, request.EntityType, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); EntityType responseCancellationToken = await client.CreateEntityTypeAsync(request.ParentAsAgentName, request.EntityType, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateEntityTypeRequestObject() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); UpdateEntityTypeRequest request = new UpdateEntityTypeRequest { EntityType = new EntityType(), LanguageCode = "language_code2f6c7160", UpdateMask = new wkt::FieldMask(), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.UpdateEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType response = client.UpdateEntityType(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateEntityTypeRequestObjectAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); UpdateEntityTypeRequest request = new UpdateEntityTypeRequest { EntityType = new EntityType(), LanguageCode = "language_code2f6c7160", UpdateMask = new wkt::FieldMask(), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.UpdateEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType responseCallSettings = await client.UpdateEntityTypeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); EntityType responseCancellationToken = await client.UpdateEntityTypeAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateEntityType() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); UpdateEntityTypeRequest request = new UpdateEntityTypeRequest { EntityType = new EntityType(), UpdateMask = new wkt::FieldMask(), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.UpdateEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType response = client.UpdateEntityType(request.EntityType, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateEntityTypeAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); UpdateEntityTypeRequest request = new UpdateEntityTypeRequest { EntityType = new EntityType(), UpdateMask = new wkt::FieldMask(), }; EntityType expectedResponse = new EntityType { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), DisplayName = "display_name137f65c2", Kind = EntityType.Types.Kind.Regexp, AutoExpansionMode = EntityType.Types.AutoExpansionMode.Default, Entities = { new EntityType.Types.Entity(), }, ExcludedPhrases = { new EntityType.Types.ExcludedPhrase(), }, EnableFuzzyExtraction = false, Redact = true, }; mockGrpcClient.Setup(x => x.UpdateEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<EntityType>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); EntityType responseCallSettings = await client.UpdateEntityTypeAsync(request.EntityType, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); EntityType responseCancellationToken = await client.UpdateEntityTypeAsync(request.EntityType, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteEntityTypeRequestObject() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); DeleteEntityTypeRequest request = new DeleteEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), Force = true, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); client.DeleteEntityType(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteEntityTypeRequestObjectAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); DeleteEntityTypeRequest request = new DeleteEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), Force = true, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); await client.DeleteEntityTypeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteEntityTypeAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteEntityType() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); DeleteEntityTypeRequest request = new DeleteEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); client.DeleteEntityType(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteEntityTypeAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); DeleteEntityTypeRequest request = new DeleteEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); await client.DeleteEntityTypeAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteEntityTypeAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteEntityTypeResourceNames() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); DeleteEntityTypeRequest request = new DeleteEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteEntityType(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); client.DeleteEntityType(request.EntityTypeName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteEntityTypeResourceNamesAsync() { moq::Mock<EntityTypes.EntityTypesClient> mockGrpcClient = new moq::Mock<EntityTypes.EntityTypesClient>(moq::MockBehavior.Strict); DeleteEntityTypeRequest request = new DeleteEntityTypeRequest { EntityTypeName = EntityTypeName.FromProjectLocationAgentEntityType("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENTITY_TYPE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteEntityTypeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); EntityTypesClient client = new EntityTypesClientImpl(mockGrpcClient.Object, null); await client.DeleteEntityTypeAsync(request.EntityTypeName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteEntityTypeAsync(request.EntityTypeName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// 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.ServiceModel.Syndication { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Runtime.CompilerServices; using System.ServiceModel.Channels; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; [XmlRoot(ElementName = Atom10Constants.FeedTag, Namespace = Atom10Constants.Atom10Namespace)] public class Atom10FeedFormatter : SyndicationFeedFormatter, IXmlSerializable { internal static readonly TimeSpan zeroOffset = new TimeSpan(0, 0, 0); internal const string XmlNs = "http://www.w3.org/XML/1998/namespace"; internal const string XmlNsNs = "http://www.w3.org/2000/xmlns/"; private static readonly XmlQualifiedName s_atom10Href = new XmlQualifiedName(Atom10Constants.HrefTag, string.Empty); private static readonly XmlQualifiedName s_atom10Label = new XmlQualifiedName(Atom10Constants.LabelTag, string.Empty); private static readonly XmlQualifiedName s_atom10Length = new XmlQualifiedName(Atom10Constants.LengthTag, string.Empty); private static readonly XmlQualifiedName s_atom10Relative = new XmlQualifiedName(Atom10Constants.RelativeTag, string.Empty); private static readonly XmlQualifiedName s_atom10Scheme = new XmlQualifiedName(Atom10Constants.SchemeTag, string.Empty); private static readonly XmlQualifiedName s_atom10Term = new XmlQualifiedName(Atom10Constants.TermTag, string.Empty); private static readonly XmlQualifiedName s_atom10Title = new XmlQualifiedName(Atom10Constants.TitleTag, string.Empty); private static readonly XmlQualifiedName s_atom10Type = new XmlQualifiedName(Atom10Constants.TypeTag, string.Empty); private static readonly UriGenerator s_idGenerator = new UriGenerator(); private const string Rfc3339LocalDateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz"; private const string Rfc3339UTCDateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ"; private Type _feedType; private int _maxExtensionSize; private bool _preserveAttributeExtensions; private bool _preserveElementExtensions; public Atom10FeedFormatter() : this(typeof(SyndicationFeed)) { } public Atom10FeedFormatter(Type feedTypeToCreate) : base() { if (feedTypeToCreate == null) { throw new ArgumentNullException(nameof(feedTypeToCreate)); } if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(feedTypeToCreate), nameof(SyndicationFeed))); } _maxExtensionSize = int.MaxValue; _preserveAttributeExtensions = _preserveElementExtensions = true; _feedType = feedTypeToCreate; DateTimeParser = DateTimeHelper.CreateAtom10DateTimeParser(); } public Atom10FeedFormatter(SyndicationFeed feedToWrite) : base(feedToWrite) { // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class _maxExtensionSize = int.MaxValue; _preserveAttributeExtensions = _preserveElementExtensions = true; _feedType = feedToWrite.GetType(); DateTimeParser = DateTimeHelper.CreateAtom10DateTimeParser(); } public bool PreserveAttributeExtensions { get { return _preserveAttributeExtensions; } set { _preserveAttributeExtensions = value; } } public bool PreserveElementExtensions { get { return _preserveElementExtensions; } set { _preserveElementExtensions = value; } } public override string Version { get { return SyndicationVersions.Atom10; } } protected Type FeedType { get { return _feedType; } } public override bool CanRead(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return reader.IsStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } ReadFromAsync(reader, CancellationToken.None).GetAwaiter().GetResult(); } void IXmlSerializable.WriteXml(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } WriteFeedAsync(writer).GetAwaiter().GetResult(); } public override void ReadFrom(XmlReader reader) { ReadFromAsync(reader, CancellationToken.None).GetAwaiter().GetResult(); } public override void WriteTo(XmlWriter writer) { WriteToAsync(writer, CancellationToken.None).GetAwaiter().GetResult(); } public override async Task ReadFromAsync(XmlReader reader, CancellationToken ct) { if (!CanRead(reader)) { throw new XmlException(SR.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI)); } SetFeed(CreateFeedInstance()); await ReadFeedFromAsync(XmlReaderWrapper.CreateFromReader(reader), Feed, false); } public override async Task WriteToAsync(XmlWriter writer, CancellationToken ct) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } writer = XmlWriterWrapper.CreateFromWriter(writer); await writer.WriteStartElementAsync(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); await WriteFeedAsync(writer); await writer.WriteEndElementAsync(); } internal static async Task<SyndicationCategory> ReadCategoryAsync(XmlReader reader, SyndicationCategory category, string version, bool preserveAttributeExtensions, bool preserveElementExtensions, int _maxExtensionSize) { await MoveToStartElementAsync(reader); bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string value = await reader.GetValueAsync(); bool notHandled = false; if (reader.NamespaceURI == string.Empty) { switch (reader.LocalName) { case Atom10Constants.TermTag: category.Name = value; break; case Atom10Constants.SchemeTag: category.Scheme = value; break; case Atom10Constants.LabelTag: category.Label = value; break; default: notHandled = true; break; } } else { notHandled = true; } if (notHandled) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } if (!TryParseAttribute(name, ns, value, category, version)) { if (preserveAttributeExtensions) { category.AttributeExtensions.Add(new XmlQualifiedName(name, ns), value); } } } } } if (!isEmpty) { await reader.ReadStartElementAsync(); XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (await reader.IsStartElementAsync()) { if (TryParseElement(reader, category, version)) { continue; } else if (!preserveElementExtensions) { await reader.SkipAsync(); } else { var tuple = await CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize); buffer = tuple.Item1; extWriter = tuple.Item2; } } LoadElementExtensions(buffer, extWriter, category); } finally { if (extWriter != null) { ((IDisposable)extWriter).Dispose(); } } await reader.ReadEndElementAsync(); } else { await reader.ReadStartElementAsync(); } return category; } internal Task<TextSyndicationContent> ReadTextContentFromAsync(XmlReader reader, string context, bool preserveAttributeExtensions) { string type = reader.GetAttribute(Atom10Constants.TypeTag); return ReadTextContentFromHelperAsync(reader, type, context, preserveAttributeExtensions); } internal static async Task WriteCategoryAsync(XmlWriter writer, SyndicationCategory category, string version) { await writer.WriteStartElementAsync(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace); await WriteAttributeExtensionsAsync(writer, category, version); string categoryName = category.Name ?? string.Empty; if (!category.AttributeExtensions.ContainsKey(s_atom10Term)) { await writer.WriteAttributeStringAsync(Atom10Constants.TermTag, categoryName); } if (!string.IsNullOrEmpty(category.Label) && !category.AttributeExtensions.ContainsKey(s_atom10Label)) { await writer.WriteAttributeStringAsync(Atom10Constants.LabelTag, category.Label); } if (!string.IsNullOrEmpty(category.Scheme) && !category.AttributeExtensions.ContainsKey(s_atom10Scheme)) { await writer.WriteAttributeStringAsync(Atom10Constants.SchemeTag, category.Scheme); } await WriteElementExtensionsAsync(writer, category, version); await writer.WriteEndElementAsync(); } internal async Task ReadItemFromAsync(XmlReader reader, SyndicationItem result) { await ReadItemFromAsync(reader, result, null); } internal async Task<bool> TryParseFeedElementFromAsync(XmlReader reader, SyndicationFeed result) { if (await reader.MoveToContentAsync() != XmlNodeType.Element) { return false; } string name = reader.LocalName; string ns = reader.NamespaceURI; if (ns == Atom10Constants.Atom10Namespace) { switch (name) { case Atom10Constants.AuthorTag: result.Authors.Add(await ReadPersonFromAsync(reader, result)); break; case Atom10Constants.CategoryTag: result.Categories.Add(await ReadCategoryFromAsync(reader, result)); break; case Atom10Constants.ContributorTag: result.Contributors.Add(await ReadPersonFromAsync(reader, result)); break; case Atom10Constants.GeneratorTag: result.Generator = StringParser(await reader.ReadElementStringAsync(), Atom10Constants.GeneratorTag,ns); break; case Atom10Constants.IdTag: result.Id = StringParser(await reader.ReadElementStringAsync(), Atom10Constants.IdTag,ns); break; case Atom10Constants.LinkTag: result.Links.Add(await ReadLinkFromAsync(reader, result)); break; case Atom10Constants.LogoTag: result.ImageUrl = UriParser(await reader.ReadElementStringAsync(), UriKind.RelativeOrAbsolute, Atom10Constants.LogoTag, ns); break; case Atom10Constants.RightsTag: result.Copyright = await ReadTextContentFromAsync(reader, "//atom:feed/atom:rights[@type]"); break; case Atom10Constants.SubtitleTag: result.Description = await ReadTextContentFromAsync(reader, "//atom:feed/atom:subtitle[@type]"); break; case Atom10Constants.TitleTag: result.Title = await ReadTextContentFromAsync(reader, "//atom:feed/atom:title[@type]"); break; case Atom10Constants.UpdatedTag: await reader.ReadStartElementAsync(); result.LastUpdatedTime = DateTimeParser(await reader.ReadStringAsync(), Atom10Constants.UpdatedTag, ns); await reader.ReadEndElementAsync(); break; case Atom10Constants.IconTag: result.IconImage = UriParser(await reader.ReadElementStringAsync(), UriKind.RelativeOrAbsolute, Atom10Constants.IconTag, ns); break; default: return false; } return true; } return false; } internal async Task<bool> TryParseItemElementFromAsync(XmlReader reader, SyndicationItem result) { if (await reader.MoveToContentAsync() != XmlNodeType.Element) { return false; } string name = reader.LocalName; string ns = reader.NamespaceURI; if (ns == Atom10Constants.Atom10Namespace) { switch (name) { case Atom10Constants.AuthorTag: result.Authors.Add(await ReadPersonFromAsync(reader, result)); break; case Atom10Constants.CategoryTag: result.Categories.Add(await ReadCategoryFromAsync(reader, result)); break; case Atom10Constants.ContentTag: result.Content = await ReadContentFromAsync(reader, result); break; case Atom10Constants.ContributorTag: result.Contributors.Add(await ReadPersonFromAsync(reader, result)); break; case Atom10Constants.IdTag: result.Id = StringParser(await reader.ReadElementStringAsync(), Atom10Constants.IdTag, ns); break; case Atom10Constants.LinkTag: result.Links.Add(await ReadLinkFromAsync(reader, result)); break; case Atom10Constants.PublishedTag: await reader.ReadStartElementAsync(); result.PublishDate = DateTimeParser(await reader.ReadStringAsync(), Atom10Constants.UpdatedTag, ns); await reader.ReadEndElementAsync(); break; case Atom10Constants.RightsTag: result.Copyright = await ReadTextContentFromAsync(reader, "//atom:feed/atom:entry/atom:rights[@type]"); break; case Atom10Constants.SourceFeedTag: await reader.ReadStartElementAsync(); result.SourceFeed = await ReadFeedFromAsync(reader, new SyndicationFeed(), true); // isSourceFeed await reader.ReadEndElementAsync(); break; case Atom10Constants.SummaryTag: result.Summary = await ReadTextContentFromAsync(reader, "//atom:feed/atom:entry/atom:summary[@type]"); break; case Atom10Constants.TitleTag: result.Title = await ReadTextContentFromAsync(reader, "//atom:feed/atom:entry/atom:title[@type]"); break; case Atom10Constants.UpdatedTag: await reader.ReadStartElementAsync(); result.LastUpdatedTime = DateTimeParser(await reader.ReadStringAsync(), Atom10Constants.UpdatedTag, ns); await reader.ReadEndElementAsync(); break; default: return false; } return true; } return false; } internal Task WriteContentToAsync(XmlWriter writer, string elementName, SyndicationContent content) { if (content != null) { return content.WriteToAsync(writer, elementName, Atom10Constants.Atom10Namespace); } return Task.CompletedTask; } internal async Task WriteElementAsync(XmlWriter writer, string elementName, string value) { if (value != null) { await writer.WriteElementStringAsync(elementName, Atom10Constants.Atom10Namespace, value); } } internal async Task WriteFeedAuthorsToAsync(XmlWriter writer, Collection<SyndicationPerson> authors) { writer = XmlWriterWrapper.CreateFromWriter(writer); for (int i = 0; i < authors.Count; ++i) { SyndicationPerson p = authors[i]; await WritePersonToAsync(writer, p, Atom10Constants.AuthorTag); } } internal async Task WriteFeedContributorsToAsync(XmlWriter writer, Collection<SyndicationPerson> contributors) { writer = XmlWriterWrapper.CreateFromWriter(writer); for (int i = 0; i < contributors.Count; ++i) { SyndicationPerson p = contributors[i]; await WritePersonToAsync(writer, p, Atom10Constants.ContributorTag); } } internal Task WriteFeedLastUpdatedTimeToAsync(XmlWriter writer, DateTimeOffset lastUpdatedTime, bool isRequired) { if (lastUpdatedTime == DateTimeOffset.MinValue && isRequired) { lastUpdatedTime = DateTimeOffset.UtcNow; } if (lastUpdatedTime != DateTimeOffset.MinValue) { return WriteElementAsync(writer, Atom10Constants.UpdatedTag, AsString(lastUpdatedTime)); } return Task.CompletedTask; } internal async Task WriteItemAuthorsToAsync(XmlWriter writer, Collection<SyndicationPerson> authors) { writer = XmlWriterWrapper.CreateFromWriter(writer); for (int i = 0; i < authors.Count; ++i) { SyndicationPerson p = authors[i]; await WritePersonToAsync(writer, p, Atom10Constants.AuthorTag); } } internal Task WriteItemContentsAsync(XmlWriter dictWriter, SyndicationItem item) { return WriteItemContentsAsync(dictWriter, item, null); } internal async Task WriteItemContributorsToAsync(XmlWriter writer, Collection<SyndicationPerson> contributors) { writer = XmlWriterWrapper.CreateFromWriter(writer); for (int i = 0; i < contributors.Count; ++i) { SyndicationPerson p = contributors[i]; await WritePersonToAsync(writer, p, Atom10Constants.ContributorTag); } } internal Task WriteItemLastUpdatedTimeToAsync(XmlWriter writer, DateTimeOffset lastUpdatedTime) { if (lastUpdatedTime == DateTimeOffset.MinValue) { lastUpdatedTime = DateTimeOffset.UtcNow; } return writer.WriteElementStringAsync(Atom10Constants.UpdatedTag, Atom10Constants.Atom10Namespace, AsString(lastUpdatedTime)); } internal async Task WriteLinkAsync(XmlWriter writer, SyndicationLink link, Uri baseUri) { await writer.WriteStartElementAsync(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); if (baseUriToWrite != null) { await writer.WriteAttributeStringAsync("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } await link.WriteAttributeExtensionsAsync(writer, SyndicationVersions.Atom10); if (!string.IsNullOrEmpty(link.RelationshipType) && !link.AttributeExtensions.ContainsKey(s_atom10Relative)) { await writer.WriteAttributeStringAsync(Atom10Constants.RelativeTag, link.RelationshipType); } if (!string.IsNullOrEmpty(link.MediaType) && !link.AttributeExtensions.ContainsKey(s_atom10Type)) { await writer.WriteAttributeStringAsync(Atom10Constants.TypeTag, link.MediaType); } if (!string.IsNullOrEmpty(link.Title) && !link.AttributeExtensions.ContainsKey(s_atom10Title)) { await writer.WriteAttributeStringAsync(Atom10Constants.TitleTag, link.Title); } if (link.Length != 0 && !link.AttributeExtensions.ContainsKey(s_atom10Length)) { await writer.WriteAttributeStringAsync(Atom10Constants.LengthTag, Convert.ToString(link.Length, CultureInfo.InvariantCulture)); } if (!link.AttributeExtensions.ContainsKey(s_atom10Href)) { await writer.WriteAttributeStringAsync(Atom10Constants.HrefTag, FeedUtils.GetUriString(link.Uri)); } await link.WriteElementExtensionsAsync(writer, SyndicationVersions.Atom10); await writer.WriteEndElementAsync(); } protected override SyndicationFeed CreateFeedInstance() { return SyndicationFeedFormatter.CreateFeedInstance(_feedType); } protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) { return ReadItemAsync(reader, feed).GetAwaiter().GetResult(); } protected virtual IEnumerable<SyndicationItem> ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead) { IEnumerable<SyndicationItem> result = ReadItemsAsync(reader, feed).GetAwaiter().GetResult(); areAllItemsRead = true; return result; } protected virtual async Task<SyndicationItem> ReadItemAsync(XmlReader reader, SyndicationFeed feed) { if (feed == null) { throw new ArgumentNullException(nameof(feed)); } if (reader == null) { throw new ArgumentNullException(nameof(reader)); } SyndicationItem item = CreateItem(feed); reader = XmlReaderWrapper.CreateFromReader(reader); await ReadItemFromAsync(reader, item, feed.BaseUri); return item; } //not referenced anymore protected virtual async Task<IEnumerable<SyndicationItem>> ReadItemsAsync(XmlReader reader, SyndicationFeed feed) { if (feed == null) { throw new ArgumentNullException(nameof(feed)); } if (reader == null) { throw new ArgumentNullException(nameof(reader)); } NullNotAllowedCollection<SyndicationItem> items = new NullNotAllowedCollection<SyndicationItem>(); reader = XmlReaderWrapper.CreateFromReader(reader); while (await reader.IsStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace)) { items.Add(await ReadItemAsync(reader, feed)); } return items; } protected virtual void WriteItem(XmlWriter writer, SyndicationItem item, Uri feedBaseUri) { WriteItemAsync(writer, item, feedBaseUri).GetAwaiter().GetResult(); } protected virtual void WriteItems(XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri) { WriteItemsAsync(writer, items, feedBaseUri).GetAwaiter().GetResult(); } protected virtual async Task WriteItemAsync(XmlWriter writer, SyndicationItem item, Uri feedBaseUri) { writer = XmlWriterWrapper.CreateFromWriter(writer); await writer.WriteStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace); await WriteItemContentsAsync(writer, item, feedBaseUri); await writer.WriteEndElementAsync(); } protected virtual async Task WriteItemsAsync(XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri) { if (items == null) { return; } foreach (SyndicationItem item in items) { await WriteItemAsync(writer, item, feedBaseUri); } } private async Task<TextSyndicationContent> ReadTextContentFromHelperAsync(XmlReader reader, string type, string context, bool preserveAttributeExtensions) { if (string.IsNullOrEmpty(type)) { type = Atom10Constants.PlaintextType; } TextSyndicationContentKind kind = new TextSyndicationContentKind(); switch (type) { case Atom10Constants.PlaintextType: kind = TextSyndicationContentKind.Plaintext; break; case Atom10Constants.HtmlType: kind = TextSyndicationContentKind.Html; break; case Atom10Constants.XHtmlType: kind = TextSyndicationContentKind.XHtml; break; throw new XmlException(SR.Format(SR.Atom10SpecRequiresTextConstruct, context, type)); } Dictionary<XmlQualifiedName, string> attrs = null; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty) { continue; } string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } if (preserveAttributeExtensions) { string value = await reader.GetValueAsync(); if (attrs == null) { attrs = new Dictionary<XmlQualifiedName, string>(); } attrs.Add(new XmlQualifiedName(name, ns), value); } } } reader.MoveToElement(); string localName = reader.LocalName; string nameSpace = reader.NamespaceURI; string val = (kind == TextSyndicationContentKind.XHtml) ? await reader.ReadInnerXmlAsync() : StringParser(await reader.ReadElementStringAsync(), localName, nameSpace); // cant custom parse because its static TextSyndicationContent result = new TextSyndicationContent(val, kind); if (attrs != null) { foreach (XmlQualifiedName attr in attrs.Keys) { if (!FeedUtils.IsXmlns(attr.Name, attr.Namespace)) { result.AttributeExtensions.Add(attr, attrs[attr]); } } } return result; } private string AsString(DateTimeOffset dateTime) { if (dateTime.Offset == zeroOffset) { return dateTime.ToUniversalTime().ToString(Rfc3339UTCDateTimeFormat, CultureInfo.InvariantCulture); } else { return dateTime.ToString(Rfc3339LocalDateTimeFormat, CultureInfo.InvariantCulture); } } private Task<SyndicationCategory> ReadCategoryAsync(XmlReader reader, SyndicationCategory category) { return ReadCategoryAsync(reader, category, Version, PreserveAttributeExtensions, PreserveElementExtensions, _maxExtensionSize); } private Task<SyndicationCategory> ReadCategoryFromAsync(XmlReader reader, SyndicationFeed feed) { SyndicationCategory result = CreateCategory(feed); return ReadCategoryAsync(reader, result); } private async Task<SyndicationCategory> ReadCategoryFromAsync(XmlReader reader, SyndicationItem item) { SyndicationCategory result = CreateCategory(item); await ReadCategoryAsync(reader, result); return result; } private async Task<SyndicationContent> ReadContentFromAsync(XmlReader reader, SyndicationItem item) { await MoveToStartElementAsync(reader); string type = reader.GetAttribute(Atom10Constants.TypeTag, string.Empty); SyndicationContent result; if (TryParseContent(reader, item, type, Version, out result)) { return result; } if (string.IsNullOrEmpty(type)) { type = Atom10Constants.PlaintextType; } string src = reader.GetAttribute(Atom10Constants.SourceTag, string.Empty); if (string.IsNullOrEmpty(src) && type != Atom10Constants.PlaintextType && type != Atom10Constants.HtmlType && type != Atom10Constants.XHtmlType) { return new XmlSyndicationContent(reader); } if (!string.IsNullOrEmpty(src)) { result = new UrlSyndicationContent(new Uri(src, UriKind.RelativeOrAbsolute), type); bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty) { continue; } else if (reader.LocalName == Atom10Constants.SourceTag && reader.NamespaceURI == string.Empty) { continue; } else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI)) { if (_preserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync()); } else { //result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync()); } } } } await reader.ReadStartElementAsync(); if (!isEmpty) { await reader.ReadEndElementAsync(); } return result; } else { return await ReadTextContentFromHelperAsync(reader, type, "//atom:feed/atom:entry/atom:content[@type]", _preserveAttributeExtensions); } } private async Task<SyndicationFeed> ReadFeedFromAsync(XmlReader reader, SyndicationFeed result, bool isSourceFeed) { await reader.MoveToContentAsync(); //fix to accept non contiguous items NullNotAllowedCollection<SyndicationItem> feedItems = new NullNotAllowedCollection<SyndicationItem>(); bool elementIsEmpty = false; if (!isSourceFeed) { await MoveToStartElementAsync(reader); elementIsEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "lang" && reader.NamespaceURI == XmlNs) { result.Language = await reader.GetValueAsync(); } else if (reader.LocalName == "base" && reader.NamespaceURI == XmlNs) { result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, await reader.GetValueAsync()); } else { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (!TryParseAttribute(name, ns, val, result, Version)) { if (_preserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), val); } } } } } await reader.ReadStartElementAsync(); } XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; if (!elementIsEmpty) { try { while (await reader.IsStartElementAsync()) { if (await TryParseFeedElementFromAsync(reader, result)) { // nothing, we parsed something, great } else if (await reader.IsStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace) && !isSourceFeed) { while (await reader.IsStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace)) { feedItems.Add(await ReadItemAsync(reader, result)); } } else { if (!TryParseElement(reader, result, Version)) { if (_preserveElementExtensions) { var tuple = await SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize); buffer = tuple.Item1; extWriter = tuple.Item2; } else { await reader.SkipAsync(); } } } } //Add all read items to the feed result.Items = feedItems; LoadElementExtensions(buffer, extWriter, result); } catch (FormatException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e); } catch (ArgumentException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e); } finally { if (extWriter != null) { ((IDisposable)extWriter).Dispose(); } } } if (!isSourceFeed) { await reader.ReadEndElementAsync(); // feed } return result; } private async Task ReadItemFromAsync(XmlReader reader, SyndicationItem result, Uri feedBaseUri) { try { result.BaseUri = feedBaseUri; await MoveToStartElementAsync(reader); bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (name == "base" && ns == XmlNs) { result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, await reader.GetValueAsync()); continue; } if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (!TryParseAttribute(name, ns, val, result, Version)) { if (_preserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } await reader.ReadStartElementAsync(); if (!isEmpty) { XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (await reader.IsStartElementAsync()) { if (await TryParseItemElementFromAsync(reader, result)) { // nothing, we parsed something, great } else { if (!TryParseElement(reader, result, Version)) { if (_preserveElementExtensions) { var tuple = await CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize); buffer = tuple.Item1; extWriter = tuple.Item2; } else { await reader.SkipAsync(); } } } } LoadElementExtensions(buffer, extWriter, result); } finally { if (extWriter != null) { ((IDisposable)extWriter).Dispose(); } } await reader.ReadEndElementAsync(); // item } } catch (FormatException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingItem), e); } catch (ArgumentException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingItem), e); } } private async Task ReadLinkAsync(XmlReader reader, SyndicationLink link, Uri baseUri) { bool isEmpty = reader.IsEmptyElement; string mediaType = null; string relationship = null; string title = null; string lengthStr = null; string val = null; string ns = null; link.BaseUri = baseUri; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { bool notHandled = false; if (reader.LocalName == "base" && reader.NamespaceURI == XmlNs) { link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, await reader.GetValueAsync()); } else if (reader.NamespaceURI == string.Empty) { switch (reader.LocalName) { case Atom10Constants.TypeTag: mediaType = await reader.GetValueAsync(); break; case Atom10Constants.RelativeTag: relationship = await reader.GetValueAsync(); break; case Atom10Constants.TitleTag: title = await reader.GetValueAsync(); break; case Atom10Constants.LengthTag: lengthStr = await reader.GetValueAsync(); break; case Atom10Constants.HrefTag: val = await reader.GetValueAsync(); ns = reader.NamespaceURI; break; default: notHandled = true; break; } } else { notHandled = true; } if (notHandled && !FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI)) { if (_preserveAttributeExtensions) { link.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync()); } } } } long length = 0; if (!string.IsNullOrEmpty(lengthStr)) { length = Convert.ToInt64(lengthStr, CultureInfo.InvariantCulture.NumberFormat); } await reader.ReadStartElementAsync(); if (!isEmpty) { XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (await reader.IsStartElementAsync()) { if (TryParseElement(reader, link, Version)) { continue; } else if (!_preserveElementExtensions) { await reader.SkipAsync(); } else { var tuple = await SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize); buffer = tuple.Item1; extWriter = tuple.Item2; } } LoadElementExtensions(buffer, extWriter, link); } finally { if (extWriter != null) { ((IDisposable)extWriter).Dispose(); } } await reader.ReadEndElementAsync(); } link.Length = length; link.MediaType = mediaType; link.RelationshipType = relationship; link.Title = title; link.Uri = (val != null) ? UriParser(val, UriKind.RelativeOrAbsolute, Atom10Constants.LinkTag, ns) : null; } private async Task<SyndicationLink> ReadLinkFromAsync(XmlReader reader, SyndicationFeed feed) { SyndicationLink result = CreateLink(feed); await ReadLinkAsync(reader, result, feed.BaseUri); return result; } private async Task<SyndicationLink> ReadLinkFromAsync(XmlReader reader, SyndicationItem item) { SyndicationLink result = CreateLink(item); await ReadLinkAsync(reader, result, item.BaseUri); return result; } private async Task<SyndicationPerson> ReadPersonFromAsync(XmlReader reader, SyndicationFeed feed) { SyndicationPerson result = CreatePerson(feed); await ReadPersonFromAsync(reader, result); return result; } private async Task<SyndicationPerson> ReadPersonFromAsync(XmlReader reader, SyndicationItem item) { SyndicationPerson result = CreatePerson(item); await ReadPersonFromAsync(reader, result); return result; } private async Task ReadPersonFromAsync(XmlReader reader, SyndicationPerson result) { bool isEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns)) { continue; } string val = await reader.GetValueAsync(); if (!TryParseAttribute(name, ns, val, result, Version)) { if (_preserveAttributeExtensions) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync()); } } } } await reader.ReadStartElementAsync(); if (!isEmpty) { XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (await reader.IsStartElementAsync()) { string name = reader.LocalName; string ns = reader.NamespaceURI; bool notHandled = false; switch (name) { case Atom10Constants.NameTag: result.Name = StringParser(await reader.ReadElementStringAsync(), Atom10Constants.NameTag, ns); break; case Atom10Constants.UriTag: result.Uri = StringParser(await reader.ReadElementStringAsync(), Atom10Constants.UriTag, ns); break; case Atom10Constants.EmailTag: result.Email = StringParser(await reader.ReadElementStringAsync(), Atom10Constants.EmailTag, ns); break; default: notHandled = true; break; } if (notHandled && !TryParseElement(reader, result, Version)) { if (_preserveElementExtensions) { var tuple = await SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize); buffer = tuple.Item1; extWriter = tuple.Item2; } else { await reader.SkipAsync(); } } } LoadElementExtensions(buffer, extWriter, result); } finally { if (extWriter != null) { ((IDisposable)extWriter).Dispose(); } } await reader.ReadEndElementAsync(); } } private Task<TextSyndicationContent> ReadTextContentFromAsync(XmlReader reader, string context) { return ReadTextContentFromAsync(reader, context, PreserveAttributeExtensions); } private async Task WriteCategoriesToAsync(XmlWriter writer, Collection<SyndicationCategory> categories) { writer = XmlWriterWrapper.CreateFromWriter(writer); for (int i = 0; i < categories.Count; ++i) { await WriteCategoryAsync(writer, categories[i], Version); } } private Task WriteFeedAsync(XmlWriter writer) { if (Feed == null) { throw new InvalidOperationException(SR.FeedFormatterDoesNotHaveFeed); } return WriteFeedToAsync(writer, Feed, false); // isSourceFeed } private async Task WriteFeedToAsync(XmlWriter writer, SyndicationFeed feed, bool isSourceFeed) { if (!isSourceFeed) { if (!string.IsNullOrEmpty(feed.Language)) { await writer.WriteAttributeStringAsync("xml", "lang", XmlNs, feed.Language); } if (feed.BaseUri != null) { await writer.WriteAttributeStringAsync("xml", "base", XmlNs, FeedUtils.GetUriString(feed.BaseUri)); } await WriteAttributeExtensionsAsync(writer, feed, Version); } bool isElementRequired = !isSourceFeed; TextSyndicationContent title = feed.Title; if (isElementRequired) { title = title ?? new TextSyndicationContent(string.Empty); } await WriteContentToAsync(writer, Atom10Constants.TitleTag, title); await WriteContentToAsync(writer, Atom10Constants.SubtitleTag, feed.Description); string id = feed.Id; if (isElementRequired) { id = id ?? s_idGenerator.Next(); } await WriteElementAsync(writer, Atom10Constants.IdTag, id); await WriteContentToAsync(writer, Atom10Constants.RightsTag, feed.Copyright); await WriteFeedLastUpdatedTimeToAsync(writer, feed.LastUpdatedTime, isElementRequired); await WriteCategoriesToAsync(writer, feed.Categories); if (feed.ImageUrl != null) { await WriteElementAsync(writer, Atom10Constants.LogoTag, feed.ImageUrl.ToString()); } await WriteFeedAuthorsToAsync(writer, feed.Authors); await WriteFeedContributorsToAsync(writer, feed.Contributors); await WriteElementAsync(writer, Atom10Constants.GeneratorTag, feed.Generator); if (feed.IconImage != null) { await WriteElementAsync(writer, Atom10Constants.IconTag, feed.IconImage.AbsoluteUri); } for (int i = 0; i < feed.Links.Count; ++i) { await WriteLinkAsync(writer, feed.Links[i], feed.BaseUri); } await WriteElementExtensionsAsync(writer, feed, Version); if (!isSourceFeed) { await WriteItemsAsync(writer, feed.Items, feed.BaseUri); } } private async Task WriteItemContentsAsync(XmlWriter dictWriter, SyndicationItem item, Uri feedBaseUri) { Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri); if (baseUriToWrite != null) { await dictWriter.WriteAttributeStringAsync("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite)); } await WriteAttributeExtensionsAsync(dictWriter, item, Version); string id = item.Id ?? s_idGenerator.Next(); await WriteElementAsync(dictWriter, Atom10Constants.IdTag, id); TextSyndicationContent title = item.Title ?? new TextSyndicationContent(string.Empty); await WriteContentToAsync(dictWriter, Atom10Constants.TitleTag, title); await WriteContentToAsync(dictWriter, Atom10Constants.SummaryTag, item.Summary); if (item.PublishDate != DateTimeOffset.MinValue) { await dictWriter.WriteElementStringAsync(Atom10Constants.PublishedTag, Atom10Constants.Atom10Namespace, AsString(item.PublishDate)); } await WriteItemLastUpdatedTimeToAsync(dictWriter, item.LastUpdatedTime); await WriteItemAuthorsToAsync(dictWriter, item.Authors); await WriteItemContributorsToAsync(dictWriter, item.Contributors); for (int i = 0; i < item.Links.Count; ++i) { await WriteLinkAsync(dictWriter, item.Links[i], item.BaseUri); } await WriteCategoriesToAsync(dictWriter, item.Categories); await WriteContentToAsync(dictWriter, Atom10Constants.ContentTag, item.Content); await WriteContentToAsync(dictWriter, Atom10Constants.RightsTag, item.Copyright); if (item.SourceFeed != null) { await dictWriter.WriteStartElementAsync(Atom10Constants.SourceFeedTag, Atom10Constants.Atom10Namespace); await WriteFeedToAsync(dictWriter, item.SourceFeed, true); // isSourceFeed await dictWriter.WriteEndElementAsync(); } await WriteElementExtensionsAsync(dictWriter, item, Version); } private async Task WritePersonToAsync(XmlWriter writer, SyndicationPerson p, string elementName) { await writer.WriteStartElementAsync(elementName, Atom10Constants.Atom10Namespace); await WriteAttributeExtensionsAsync(writer, p, Version); await WriteElementAsync(writer, Atom10Constants.NameTag, p.Name); if (!string.IsNullOrEmpty(p.Uri)) { await writer.WriteElementStringAsync(Atom10Constants.UriTag, Atom10Constants.Atom10Namespace, p.Uri); } if (!string.IsNullOrEmpty(p.Email)) { await writer.WriteElementStringAsync(Atom10Constants.EmailTag, Atom10Constants.Atom10Namespace, p.Email); } await WriteElementExtensionsAsync(writer, p, Version); await writer.WriteEndElementAsync(); } } [XmlRoot(ElementName = Atom10Constants.FeedTag, Namespace = Atom10Constants.Atom10Namespace)] public class Atom10FeedFormatter<TSyndicationFeed> : Atom10FeedFormatter where TSyndicationFeed : SyndicationFeed, new() { // constructors public Atom10FeedFormatter() : base(typeof(TSyndicationFeed)) { } public Atom10FeedFormatter(TSyndicationFeed feedToWrite) : base(feedToWrite) { } protected override SyndicationFeed CreateFeedInstance() { return new TSyndicationFeed(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Web; using System.Web.Security; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models; using umbraco; using umbraco.cms.businesslogic.web; using RenderingEngine = Umbraco.Core.RenderingEngine; namespace Umbraco.Web.Routing { /// <summary> /// Represents a request for one specified Umbraco IPublishedContent to be rendered /// by one specified template, using one specified Culture and RenderingEngine. /// </summary> public class PublishedContentRequest { private bool _readonly; private bool _readonlyUri; /// <summary> /// Triggers before the published content request is prepared. /// </summary> /// <remarks>When the event triggers, no preparation has been done. It is still possible to /// modify the request's Uri property, for example to restore its original, public-facing value /// that might have been modified by an in-between equipement such as a load-balancer.</remarks> public static event EventHandler<EventArgs> Preparing; /// <summary> /// Triggers once the published content request has been prepared, but before it is processed. /// </summary> /// <remarks>When the event triggers, preparation is done ie domain, culture, document, template, /// rendering engine, etc. have been setup. It is then possible to change anything, before /// the request is actually processed and rendered by Umbraco.</remarks> public static event EventHandler<EventArgs> Prepared; // the engine that does all the processing // because in order to keep things clean and separated, // the content request is just a data holder private readonly PublishedContentRequestEngine _engine; // the cleaned up uri // the cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc. private Uri _uri; /// <summary> /// Initializes a new instance of the <see cref="PublishedContentRequest"/> class with a specific Uri and routing context. /// </summary> /// <param name="uri">The request <c>Uri</c>.</param> /// <param name="routingContext">A routing context.</param> /// <param name="getRolesForLogin">A callback method to return the roles for the provided login name when required</param> /// <param name="routingConfig"></param> public PublishedContentRequest(Uri uri, RoutingContext routingContext, IWebRoutingSection routingConfig, Func<string, IEnumerable<string>> getRolesForLogin) { if (uri == null) throw new ArgumentNullException("uri"); if (routingContext == null) throw new ArgumentNullException("routingContext"); Uri = uri; RoutingContext = routingContext; _getRolesForLoginCallback = getRolesForLogin; _engine = new PublishedContentRequestEngine( routingConfig, this); RenderingEngine = RenderingEngine.Unknown; } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the constructor specifying all dependencies instead")] public PublishedContentRequest(Uri uri, RoutingContext routingContext) : this(uri, routingContext, UmbracoConfig.For.UmbracoSettings().WebRouting, s => Roles.Provider.GetRolesForUser(s)) { } /// <summary> /// Gets the engine associated to the request. /// </summary> internal PublishedContentRequestEngine Engine { get { return _engine; } } /// <summary> /// Prepares the request. /// </summary> public void Prepare() { _engine.PrepareRequest(); } /// <summary> /// Called to configure the request /// </summary> /// <remarks> /// This public method is legacy, Prepare() has been made public now which should be used and ensures the domains are assigned and /// if a public content item is already assigned Prepare() now ensures that the finders are not executed. /// </remarks> [Obsolete("Use Prepare() instead which configures the request and wires up everything correctly")] public void ConfigureRequest() { _engine.ConfigureRequest(); } /// <summary> /// Updates the request when there is no template to render the content. /// </summary> internal void UpdateOnMissingTemplate() { var __readonly = _readonly; _readonly = false; _engine.UpdateRequestOnMissingTemplate(); _readonly = __readonly; } /// <summary> /// Triggers the Preparing event. /// </summary> internal void OnPreparing() { var handler = Preparing; if (handler != null) handler(this, EventArgs.Empty); _readonlyUri = true; } /// <summary> /// Triggers the Prepared event. /// </summary> internal void OnPrepared() { var handler = Prepared; if (handler != null) handler(this, EventArgs.Empty); if (HasPublishedContent == false) Is404 = true; // safety _readonly = true; } /// <summary> /// Gets or sets the cleaned up Uri used for routing. /// </summary> /// <remarks>The cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc.</remarks> public Uri Uri { get { return _uri; } set { if (_readonlyUri) throw new InvalidOperationException("Cannot modify Uri after Preparing has triggered."); _uri = value; } } private void EnsureWriteable() { if (_readonly) throw new InvalidOperationException("Cannot modify a PublishedContentRequest once it is read-only."); } #region PublishedContent /// <summary> /// The requested IPublishedContent, if any, else <c>null</c>. /// </summary> private IPublishedContent _publishedContent; /// <summary> /// The initial requested IPublishedContent, if any, else <c>null</c>. /// </summary> /// <remarks>The initial requested content is the content that was found by the finders, /// before anything such as 404, redirect... took place.</remarks> private IPublishedContent _initialPublishedContent; /// <summary> /// Gets or sets the requested content. /// </summary> /// <remarks>Setting the requested content clears <c>Template</c>.</remarks> public IPublishedContent PublishedContent { get { return _publishedContent; } set { EnsureWriteable(); _publishedContent = value; IsInternalRedirectPublishedContent = false; TemplateModel = null; } } /// <summary> /// Sets the requested content, following an internal redirect. /// </summary> /// <param name="content">The requested content.</param> /// <remarks>Depending on <c>UmbracoSettings.InternalRedirectPreservesTemplate</c>, will /// preserve or reset the template, if any.</remarks> public void SetInternalRedirectPublishedContent(IPublishedContent content) { if (content == null) throw new ArgumentNullException("content"); EnsureWriteable(); // unless a template has been set already by the finder, // template should be null at that point. // IsInternalRedirect if IsInitial, or already IsInternalRedirect var isInternalRedirect = IsInitialPublishedContent || IsInternalRedirectPublishedContent; // redirecting to self if (content.Id == PublishedContent.Id) // neither can be null { // no need to set PublishedContent, we're done IsInternalRedirectPublishedContent = isInternalRedirect; return; } // else // save var template = _template; var renderingEngine = RenderingEngine; // set published content - this resets the template, and sets IsInternalRedirect to false PublishedContent = content; IsInternalRedirectPublishedContent = isInternalRedirect; // must restore the template if it's an internal redirect & the config option is set if (isInternalRedirect && UmbracoConfig.For.UmbracoSettings().WebRouting.InternalRedirectPreservesTemplate) { // restore _template = template; RenderingEngine = renderingEngine; } } /// <summary> /// Gets the initial requested content. /// </summary> /// <remarks>The initial requested content is the content that was found by the finders, /// before anything such as 404, redirect... took place.</remarks> public IPublishedContent InitialPublishedContent { get { return _initialPublishedContent; } } /// <summary> /// Gets value indicating whether the current published content is the initial one. /// </summary> public bool IsInitialPublishedContent { get { return _initialPublishedContent != null && _initialPublishedContent == _publishedContent; } } /// <summary> /// Indicates that the current PublishedContent is the initial one. /// </summary> public void SetIsInitialPublishedContent() { EnsureWriteable(); // note: it can very well be null if the initial content was not found _initialPublishedContent = _publishedContent; IsInternalRedirectPublishedContent = false; } /// <summary> /// Gets or sets a value indicating whether the current published content has been obtained /// from the initial published content following internal redirections exclusively. /// </summary> /// <remarks>Used by PublishedContentRequestEngine.FindTemplate() to figure out whether to /// apply the internal redirect or not, when content is not the initial content.</remarks> public bool IsInternalRedirectPublishedContent { get; private set; } /// <summary> /// Gets a value indicating whether the content request has a content. /// </summary> public bool HasPublishedContent { get { return PublishedContent != null; } } #endregion #region Template /// <summary> /// The template model, if any, else <c>null</c>. /// </summary> private ITemplate _template; /// <summary> /// Gets or sets the template model to use to display the requested content. /// </summary> internal ITemplate TemplateModel { get { return _template; } set { _template = value; RenderingEngine = RenderingEngine.Unknown; // reset if (_template != null) RenderingEngine = _engine.FindTemplateRenderingEngine(_template.Alias); } } /// <summary> /// Gets the alias of the template to use to display the requested content. /// </summary> public string TemplateAlias { get { return _template == null ? null : _template.Alias; } } /// <summary> /// Tries to set the template to use to display the requested content. /// </summary> /// <param name="alias">The alias of the template.</param> /// <returns>A value indicating whether a valid template with the specified alias was found.</returns> /// <remarks> /// <para>Successfully setting the template does refresh <c>RenderingEngine</c>.</para> /// <para>If setting the template fails, then the previous template (if any) remains in place.</para> /// </remarks> public bool TrySetTemplate(string alias) { EnsureWriteable(); if (string.IsNullOrWhiteSpace(alias)) { TemplateModel = null; return true; } // NOTE - can we stil get it with whitespaces in it due to old legacy bugs? alias = alias.Replace(" ", ""); var model = ApplicationContext.Current.Services.FileService.GetTemplate(alias); if (model == null) return false; TemplateModel = model; return true; } /// <summary> /// Sets the template to use to display the requested content. /// </summary> /// <param name="template">The template.</param> /// <remarks>Setting the template does refresh <c>RenderingEngine</c>.</remarks> public void SetTemplate(ITemplate template) { EnsureWriteable(); TemplateModel = template; } /// <summary> /// Resets the template. /// </summary> /// <remarks>The <c>RenderingEngine</c> becomes unknown.</remarks> public void ResetTemplate() { EnsureWriteable(); TemplateModel = null; } /// <summary> /// Gets a value indicating whether the content request has a template. /// </summary> public bool HasTemplate { get { return _template != null; } } #endregion #region Domain and Culture [Obsolete("Do not use this property, use the non-legacy UmbracoDomain property instead")] public Domain Domain { get { return new Domain(UmbracoDomain); } } //TODO: Should we publicize the setter now that we are using a non-legacy entity?? /// <summary> /// Gets or sets the content request's domain. /// </summary> public IDomain UmbracoDomain { get; internal set; } /// <summary> /// Gets or sets the content request's domain Uri. /// </summary> /// <remarks>The <c>Domain</c> may contain "example.com" whereas the <c>Uri</c> will be fully qualified eg "http://example.com/".</remarks> public Uri DomainUri { get; internal set; } /// <summary> /// Gets a value indicating whether the content request has a domain. /// </summary> public bool HasDomain { get { return UmbracoDomain != null; } } private CultureInfo _culture; /// <summary> /// Gets or sets the content request's culture. /// </summary> public CultureInfo Culture { get { return _culture; } set { EnsureWriteable(); _culture = value; } } // note: do we want to have an ordered list of alternate cultures, // to allow for fallbacks when doing dictionnary lookup and such? #endregion #region Rendering /// <summary> /// Gets or sets whether the rendering engine is MVC or WebForms. /// </summary> public RenderingEngine RenderingEngine { get; internal set; } #endregion /// <summary> /// Gets or sets the current RoutingContext. /// </summary> public RoutingContext RoutingContext { get; private set; } /// <summary> /// Returns the current members roles if a member is logged in /// </summary> /// <param name="username"></param> /// <returns></returns> /// <remarks> /// This ensures that the callback is only executed once in case this method is accessed a few times /// </remarks> public IEnumerable<string> GetRolesForLogin(string username) { string[] roles; if (_rolesForLogin.TryGetValue(username, out roles)) return roles; roles = _getRolesForLoginCallback(username).ToArray(); _rolesForLogin[username] = roles; return roles; } private readonly IDictionary<string, string[]> _rolesForLogin = new Dictionary<string, string[]>(); private readonly Func<string, IEnumerable<string>> _getRolesForLoginCallback; /// <summary> /// The "umbraco page" object. /// </summary> private page _umbracoPage; /// <summary> /// Gets or sets the "umbraco page" object. /// </summary> /// <remarks> /// This value is only used for legacy/webforms code. /// </remarks> internal page UmbracoPage { get { if (_umbracoPage == null) throw new InvalidOperationException("The UmbracoPage object has not been initialized yet."); return _umbracoPage; } set { _umbracoPage = value; } } #region Status /// <summary> /// Gets or sets a value indicating whether the requested content could not be found. /// </summary> /// <remarks>This is set in the <c>PublishedContentRequestBuilder</c>.</remarks> public bool Is404 { get; internal set; } /// <summary> /// Indicates that the requested content could not be found. /// </summary> /// <remarks>This is for public access, in custom content finders or <c>Prepared</c> event handlers, /// where we want to allow developers to indicate a request is 404 but not to cancel it.</remarks> public void SetIs404() { EnsureWriteable(); Is404 = true; } /// <summary> /// Gets a value indicating whether the content request triggers a redirect (permanent or not). /// </summary> public bool IsRedirect { get { return string.IsNullOrWhiteSpace(RedirectUrl) == false; } } /// <summary> /// Gets or sets a value indicating whether the redirect is permanent. /// </summary> public bool IsRedirectPermanent { get; private set; } /// <summary> /// Gets or sets the url to redirect to, when the content request triggers a redirect. /// </summary> public string RedirectUrl { get; private set; } /// <summary> /// Indicates that the content request should trigger a redirect (302). /// </summary> /// <param name="url">The url to redirect to.</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirect(string url) { EnsureWriteable(); RedirectUrl = url; IsRedirectPermanent = false; } /// <summary> /// Indicates that the content request should trigger a permanent redirect (301). /// </summary> /// <param name="url">The url to redirect to.</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirectPermanent(string url) { EnsureWriteable(); RedirectUrl = url; IsRedirectPermanent = true; } /// <summary> /// Indicates that the content requet should trigger a redirect, with a specified status code. /// </summary> /// <param name="url">The url to redirect to.</param> /// <param name="status">The status code (300-308).</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirect(string url, int status) { EnsureWriteable(); if (status < 300 || status > 308) throw new ArgumentOutOfRangeException("status", "Valid redirection status codes 300-308."); RedirectUrl = url; IsRedirectPermanent = (status == 301 || status == 308); if (status != 301 && status != 302) // default redirect statuses ResponseStatusCode = status; } /// <summary> /// Gets or sets the content request http response status code. /// </summary> /// <remarks>Does not actually set the http response status code, only registers that the response /// should use the specified code. The code will or will not be used, in due time.</remarks> public int ResponseStatusCode { get; private set; } /// <summary> /// Gets or sets the content request http response status description. /// </summary> /// <remarks>Does not actually set the http response status description, only registers that the response /// should use the specified description. The description will or will not be used, in due time.</remarks> public string ResponseStatusDescription { get; private set; } /// <summary> /// Sets the http response status code, along with an optional associated description. /// </summary> /// <param name="code">The http status code.</param> /// <param name="description">The description.</param> /// <remarks>Does not actually set the http response status code and description, only registers that /// the response should use the specified code and description. The code and description will or will /// not be used, in due time.</remarks> public void SetResponseStatus(int code, string description = null) { EnsureWriteable(); // .Status is deprecated // .SubStatusCode is IIS 7+ internal, ignore ResponseStatusCode = code; ResponseStatusDescription = description; } #endregion /// <summary> /// Gets or sets the <c>System.Web.HttpCacheability</c> /// </summary> // Note: we used to set a default value here but that would then be the default // for ALL requests, we shouldn't overwrite it though if people are using [OutputCache] for example // see: https://our.umbraco.org/forum/using-umbraco-and-getting-started/79715-output-cache-in-umbraco-752 internal HttpCacheability Cacheability { get; set; } /// <summary> /// Gets or sets a list of Extensions to append to the Response.Cache object /// </summary> private List<string> _cacheExtensions = new List<string>(); internal List<string> CacheExtensions { get { return _cacheExtensions; } set { _cacheExtensions = value; } } /// <summary> /// Gets or sets a dictionary of Headers to append to the Response object /// </summary> private Dictionary<string, string> _headers = new Dictionary<string, string>(); internal Dictionary<string, string> Headers { get { return _headers; } set { _headers = value; } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is1 distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.HSSF.Record { using System; using System.Web; using System.IO; using NPOI.Util; using NPOI.HSSF.Record; using NPOI.HSSF.Util; using NUnit.Framework; /** * Test HyperlinkRecord * * @author Nick Burch * @author Yegor Kozlov */ [TestFixture] public class TestHyperlinkRecord { /// <summary> /// Some of the tests are depending on the american culture. /// </summary> [SetUp] public void InitializeCultere() { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); } //link to http://www.lakings.com/ byte[] data1 = { 0x02, 0x00, //First row of the hyperlink 0x02, 0x00, //Last row of the hyperlink 0x00, 0x00, //First column of the hyperlink 0x00, 0x00, //Last column of the hyperlink //16-byte GUID. Seems to be always the same. Does not depend on the hyperlink type (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00, 0x00, 0x00, //integer, always 2 // flags. Define the type of the hyperlink: // HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL 0x17, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, //length of the label including the trailing '\0' //label: 0x4D, 0x00, 0x79, 0x00, 0x20, 0x00, 0x4C, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x6B, 0x00, 0x00, 0x00, //16-byte link moniker: HyperlinkRecord.URL_MONIKER (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, //count of bytes in the address including the tail 0x48, 0x00, 0x00, 0x00, //integer //the actual link, terminated by '\u0000' 0x68, 0x00, 0x74, 0x00, 0x74, 0x00, 0x70, 0x00, 0x3A, 0x00, 0x2F, 0x00, 0x2F, 0x00, 0x77, 0x00, 0x77, 0x00, 0x77, 0x00, 0x2E, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x6B, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x73, 0x00, 0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x2F, 0x00, 0x00, 0x00, //standard 24-byte tail of a URL link. Seems to always be the same for all URL HLINKs 0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, 0x2C, (byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00, 0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00}; //link to a file in the current directory: link1.xls byte[] data2 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00, 0x00, 0x00, //integer, always 2 0x15, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL 0x05, 0x00, 0x00, 0x00, //length of the label //label 0x66, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x65, 0x00, 0x00, 0x00, //16-byte link moniker: HyperlinkRecord.FILE_MONIKER 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, //level 0x0A, 0x00, 0x00, 0x00, //length of the path ) //path to the file (plain ISO-8859 bytes, NOT UTF-16LE!) 0x6C, 0x69, 0x6E, 0x6B, 0x31, 0x2E, 0x78, 0x6C, 0x73, 0x00, //standard 28-byte tail of a file link (byte)0xFF, (byte)0xFF, (byte)0xAD, (byte)0xDE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // mailto:[email protected]?subject=Hello,%20Ebgans! byte[] data3 = {0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00, 0x00, 0x00, //integer, always 2 0x17, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL 0x06, 0x00, 0x00, 0x00, //length of the label 0x65, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x00, 0x00, //label //16-byte link moniker: HyperlinkRecord.URL_MONIKER (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, //length of the address including the tail. 0x76, 0x00, 0x00, 0x00, //the address is terminated by '\u0000' 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x74, 0x00, 0x6F, 0x00, 0x3A, 0x00, 0x65, 0x00, 0x62, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6E, 0x00, 0x73, 0x00, 0x40, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x2E, 0x00, 0x72, 0x00, 0x75, 0x00, 0x3F, 0x00, 0x73, 0x00, 0x75, 0x00, 0x62, 0x00, 0x6A, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x3D, 0x00, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x2C, 0x00, 0x25, 0x00, 0x32, 0x00, 0x30, 0x00, 0x45, 0x00, 0x62, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6E, 0x00, 0x73, 0x00, 0x21, 0x00, 0x00, 0x00, //standard 24-byte tail of a URL link 0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, (byte)0x2C, (byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00, 0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00 }; //link to a place in worksheet: Sheet1!A1 byte[] data4 = {0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00, 0x00, 0x00, //integer, always 2 0x1C, 0x00, 0x00, 0x00, //flags: HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE 0x06, 0x00, 0x00, 0x00, //length of the label 0x70, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x00, 0x00, //label 0x0A, 0x00, 0x00, 0x00, //length of the document link including trailing zero //link: Sheet1!A1 0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x65, 0x00, 0x74, 0x00, 0x31, 0x00, 0x21, 0x00, 0x41, 0x00, 0x31, 0x00, 0x00, 0x00}; private static byte[] dataLinkToWorkbook = HexRead.ReadFromString("01 00 01 00 01 00 01 00 " + "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + "02 00 00 00 " + "1D 00 00 00 " + // options: LABEL | PLACE | FILE_OR_URL // label: "My Label" "09 00 00 00 " + "4D 00 79 00 20 00 4C 00 61 00 62 00 65 00 6C 00 00 00 " + "03 03 00 00 00 00 00 00 C0 00 00 00 00 00 00 46 " + // file GUID "00 00 " + // file options // shortFileName: "YEARFR~1.XLS" "0D 00 00 00 " + "59 45 41 52 46 52 7E 31 2E 58 4C 53 00 " + // FILE_TAIL - unknown byte sequence "FF FF AD DE 00 00 00 00 " + "00 00 00 00 00 00 00 00 " + "00 00 00 00 00 00 00 00 " + // field len, char data len "2E 00 00 00 " + "28 00 00 00 " + "03 00 " + // unknown ushort // _address: "yearfracExamples.xls" "79 00 65 00 61 00 72 00 66 00 72 00 61 00 63 00 " + "45 00 78 00 61 00 6D 00 70 00 6C 00 65 00 73 00 " + "2E 00 78 00 6C 00 73 00 " + // textMark: "Sheet1!B6" "0A 00 00 00 " + "53 00 68 00 65 00 65 00 74 00 31 00 21 00 42 00 " + "36 00 00 00"); private static byte[] dataTargetFrame = HexRead.ReadFromString("0E 00 0E 00 00 00 00 00 " + "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + "02 00 00 00 " + "83 00 00 00 " + // options: TARGET_FRAME | ABS | FILE_OR_URL // targetFrame: "_blank" "07 00 00 00 " + "5F 00 62 00 6C 00 61 00 6E 00 6B 00 00 00 " + // url GUID "E0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + // address: "http://www.regnow.com/softsell/nph-softsell.cgi?currency=USD&item=7924-37" "94 00 00 00 " + "68 00 74 00 74 00 70 00 3A 00 2F 00 2F 00 77 00 " + "77 00 77 00 2E 00 72 00 65 00 67 00 6E 00 6F 00 " + "77 00 2E 00 63 00 6F 00 6D 00 2F 00 73 00 6F 00 " + "66 00 74 00 73 00 65 00 6C 00 6C 00 2F 00 6E 00 " + "70 00 68 00 2D 00 73 00 6F 00 66 00 74 00 73 00 " + "65 00 6C 00 6C 00 2E 00 63 00 67 00 69 00 3F 00 " + "63 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 " + "3D 00 55 00 53 00 44 00 26 00 69 00 74 00 65 00 " + "6D 00 3D 00 37 00 39 00 32 00 34 00 2D 00 33 00 " + "37 00 00 00"); private static byte[] dataUNC = HexRead.ReadFromString("01 00 01 00 01 00 01 00 " + "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + "02 00 00 00 " + "1F 01 00 00 " + // options: UNC_PATH | LABEL | TEXT_MARK | ABS | FILE_OR_URL "09 00 00 00 " + // label: "My Label" "4D 00 79 00 20 00 6C 00 61 00 62 00 65 00 6C 00 00 00 " + // note - no moniker GUID "27 00 00 00 " + // "\\\\MyServer\\my-share\\myDir\\PRODNAME.xls" "5C 00 5C 00 4D 00 79 00 53 00 65 00 72 00 76 00 " + "65 00 72 00 5C 00 6D 00 79 00 2D 00 73 00 68 00 " + "61 00 72 00 65 00 5C 00 6D 00 79 00 44 00 69 00 " + "72 00 5C 00 50 00 52 00 4F 00 44 00 4E 00 41 00 " + "4D 00 45 00 2E 00 78 00 6C 00 73 00 00 00 " + "0C 00 00 00 " + // textMark: PRODNAME!C2 "50 00 52 00 4F 00 44 00 4E 00 41 00 4D 00 45 00 21 00 " + "43 00 32 00 00 00"); /** * From Bugzilla 47498 */ private static byte[] data_47498 = { 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x50, 0x00, 0x44, 0x00, 0x46, 0x00, 0x00, 0x00, (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, (byte)0x11, (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x28, 0x00, 0x00, 0x00, 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x66, 0x00, 0x6F, 0x00, 0x6C, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x2E, 0x00, 0x50, 0x00, 0x44, 0x00, 0x46, 0x00, 0x00, 0x00}; private void ConfirmGUID(GUID expectedGuid, GUID actualGuid) { Assert.AreEqual(expectedGuid, actualGuid); } [Test] public void TestReadURLLink() { RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data1); HyperlinkRecord link = new HyperlinkRecord(is1); Assert.AreEqual(2, link.FirstRow); Assert.AreEqual(2, link.LastRow); Assert.AreEqual(0, link.FirstColumn); Assert.AreEqual(0, link.LastColumn); ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid); ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker); Assert.AreEqual(2, link.LabelOptions); int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL; Assert.AreEqual(0x17, opts); Assert.AreEqual(opts, link.LinkOptions); Assert.AreEqual(0, link.FileOptions); Assert.AreEqual("My Link", link.Label); Assert.AreEqual("http://www.lakings.com/", link.Address); } [Test] public void TestReadFileLink() { RecordInputStream is1 = TestcaseRecordInputStream.Create((short)HyperlinkRecord.sid, data2); HyperlinkRecord link = new HyperlinkRecord(is1); Assert.AreEqual(0, link.FirstRow); Assert.AreEqual(0, link.LastRow); Assert.AreEqual(0, link.FirstColumn); Assert.AreEqual(0, link.LastColumn); ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid); ConfirmGUID(HyperlinkRecord.FILE_MONIKER, link.Moniker); Assert.AreEqual(2, link.LabelOptions); int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL; Assert.AreEqual(0x15, opts); Assert.AreEqual(opts, link.LinkOptions); Assert.AreEqual("file", link.Label); Assert.AreEqual("link1.xls", link.ShortFilename); } [Test] public void TestReadEmailLink() { RecordInputStream is1 = TestcaseRecordInputStream.Create((short)HyperlinkRecord.sid, data3); HyperlinkRecord link = new HyperlinkRecord(is1); Assert.AreEqual(1, link.FirstRow); Assert.AreEqual(1, link.LastRow); Assert.AreEqual(0, link.FirstColumn); Assert.AreEqual(0, link.LastColumn); ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid); ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker); Assert.AreEqual(2, link.LabelOptions); int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL; Assert.AreEqual(0x17, opts); Assert.AreEqual(opts, link.LinkOptions); Assert.AreEqual("email", link.Label); Assert.AreEqual("mailto:[email protected]?subject=Hello,%20Ebgans!", link.Address); } [Test] public void TestReadDocumentLink() { RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data4); HyperlinkRecord link = new HyperlinkRecord(is1); Assert.AreEqual(3, link.FirstRow); Assert.AreEqual(3, link.LastRow); Assert.AreEqual(0, link.FirstColumn); Assert.AreEqual(0, link.LastColumn); ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid); Assert.AreEqual(2, link.LabelOptions); int opts = HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE; Assert.AreEqual(0x1C, opts); Assert.AreEqual(opts, link.LinkOptions); Assert.AreEqual("place", link.Label); Assert.AreEqual("Sheet1!A1", link.TextMark); Assert.AreEqual("Sheet1!A1", link.Address); } private void Serialize(byte[] data) { RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data); HyperlinkRecord link = new HyperlinkRecord(is1); byte[] bytes1 = link.Serialize(); is1 = TestcaseRecordInputStream.Create(bytes1); link = new HyperlinkRecord(is1); byte[] bytes2 = link.Serialize(); Assert.AreEqual(bytes1.Length, bytes2.Length); Assert.IsTrue(Arrays.Equals(bytes1, bytes2)); } [Test] public void TestSerialize() { Serialize(data1); Serialize(data2); Serialize(data3); Serialize(data4); } [Test] public void TestCreateURLRecord() { HyperlinkRecord link = new HyperlinkRecord(); link.CreateUrlLink(); link.FirstRow = 2; link.LastRow = 2; link.Label = "My Link"; link.Address = "http://www.lakings.com/"; byte[] tmp = link.Serialize(); byte[] ser = new byte[tmp.Length - 4]; Array.Copy(tmp, 4, ser, 0, ser.Length); Assert.AreEqual(data1.Length, ser.Length); Assert.IsTrue(Arrays.Equals(data1, ser)); } [Test] public void TestCreateFileRecord() { HyperlinkRecord link = new HyperlinkRecord(); link.CreateFileLink(); link.FirstRow = 0; link.LastRow = 0; link.Label = "file"; link.ShortFilename = "link1.xls"; byte[] tmp = link.Serialize(); byte[] ser = new byte[tmp.Length - 4]; Array.Copy(tmp, 4, ser, 0, ser.Length); Assert.AreEqual(data2.Length, ser.Length); Assert.IsTrue(Arrays.Equals(data2, ser)); } [Test] public void TestCreateDocumentRecord() { HyperlinkRecord link = new HyperlinkRecord(); link.CreateDocumentLink(); link.FirstRow = 3; link.LastRow = 3; link.Label = "place"; link.TextMark = "Sheet1!A1"; byte[] tmp = link.Serialize(); byte[] ser = new byte[tmp.Length - 4]; Array.Copy(tmp, 4, ser, 0, ser.Length); //Assert.AreEqual(data4.Length, ser.Length); Assert.IsTrue(Arrays.Equals(data4, ser)); } [Test] public void TestCreateEmailtRecord() { HyperlinkRecord link = new HyperlinkRecord(); link.CreateUrlLink(); link.FirstRow = 1; link.LastRow = 1; link.Label = "email"; link.Address = "mailto:[email protected]?subject=Hello,%20Ebgans!"; byte[] tmp = link.Serialize(); byte[] ser = new byte[tmp.Length - 4]; Array.Copy(tmp, 4, ser, 0, ser.Length); Assert.AreEqual(data3.Length, ser.Length); Assert.IsTrue(Arrays.Equals(data3, ser)); } [Test] public void TestClone() { byte[][] data = { data1, data2, data3, data4 }; for (int i = 0; i < data.Length; i++) { RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data[i]); HyperlinkRecord link = new HyperlinkRecord(is1); HyperlinkRecord clone = (HyperlinkRecord)link.Clone(); Assert.IsTrue(Arrays.Equals(link.Serialize(), clone.Serialize())); } } [Test] public void TestReserializeTargetFrame() { RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataTargetFrame); HyperlinkRecord hr = new HyperlinkRecord(in1); byte[] ser = hr.Serialize(); TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataTargetFrame, ser); } [Test] public void TestReserializeLinkToWorkbook() { RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataLinkToWorkbook); HyperlinkRecord hr = new HyperlinkRecord(in1); byte[] ser = hr.Serialize(); TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataLinkToWorkbook, ser); if ("YEARFR~1.XLS".Equals(hr.Address)) { throw new AssertionException("Identified bug in reading workbook link"); } Assert.AreEqual("yearfracExamples.xls", hr.Address); } [Test] public void TestReserializeUNC() { RecordInputStream in1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, dataUNC); HyperlinkRecord hr = new HyperlinkRecord(in1); byte[] ser = hr.Serialize(); TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, dataUNC, ser); try { hr.ToString(); } catch (NullReferenceException) { throw new AssertionException("Identified bug with option URL and UNC set at same time"); } } [Test] public void TestGUID() { GUID g; g = GUID.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301"); ConfirmGUID(g, 0x3F2504E0, 0x4F89, 0x11D3, unchecked((long)0x9A0C0305E82C3301L)); Assert.AreEqual("3F2504E0-4F89-11D3-9A0C-0305E82C3301", g.FormatAsString()); g = GUID.Parse("13579BDF-0246-8ACE-0123-456789ABCDEF"); ConfirmGUID(g, 0x13579BDF, 0x0246, 0x8ACE, unchecked((long)0x0123456789ABCDEFL)); Assert.AreEqual("13579BDF-0246-8ACE-0123-456789ABCDEF", g.FormatAsString()); byte[] buf = new byte[16]; g.Serialize(new LittleEndianByteArrayOutputStream(buf, 0)); String expectedDump = "[DF, 9B, 57, 13, 46, 02, CE, 8A, 01, 23, 45, 67, 89, AB, CD, EF]"; Assert.AreEqual(expectedDump, HexDump.ToHex(buf)); // STD Moniker g = CreateFromStreamDump("[D0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]"); Assert.AreEqual("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B", g.FormatAsString()); // URL Moniker g = CreateFromStreamDump("[E0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]"); Assert.AreEqual("79EAC9E0-BAF9-11CE-8C82-00AA004BA90B", g.FormatAsString()); // File Moniker g = CreateFromStreamDump("[03, 03, 00, 00, 00, 00, 00, 00, C0, 00, 00, 00, 00, 00, 00, 46]"); Assert.AreEqual("00000303-0000-0000-C000-000000000046", g.FormatAsString()); } private static GUID CreateFromStreamDump(String s) { return new GUID(new LittleEndianByteArrayInputStream(HexRead.ReadFromString(s))); } private void ConfirmGUID(GUID g, int d1, int d2, int d3, long d4) { Assert.AreEqual(new String(HexDump.IntToHex(d1)), new String(HexDump.IntToHex(g.D1))); Assert.AreEqual(new String(HexDump.ShortToHex(d2)), new String(HexDump.ShortToHex(g.D2))); Assert.AreEqual(new String(HexDump.ShortToHex(d3)), new String(HexDump.ShortToHex(g.D3))); Assert.AreEqual(new String(HexDump.LongToHex(d4)), new String(HexDump.LongToHex(g.D4))); } [Test] public void Test47498() { RecordInputStream is1 = TestcaseRecordInputStream.Create(HyperlinkRecord.sid, data_47498); HyperlinkRecord link = new HyperlinkRecord(is1); Assert.AreEqual(2, link.FirstRow); Assert.AreEqual(2, link.LastRow); Assert.AreEqual(0, link.FirstColumn); Assert.AreEqual(0, link.LastColumn); ConfirmGUID(HyperlinkRecord.STD_MONIKER, link.Guid); ConfirmGUID(HyperlinkRecord.URL_MONIKER, link.Moniker); Assert.AreEqual(2, link.LabelOptions); int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL; Assert.AreEqual(opts, link.LinkOptions); Assert.AreEqual(0, link.FileOptions); Assert.AreEqual("PDF", link.Label); Assert.AreEqual("testfolder/test.PDF", link.Address); byte[] ser = link.Serialize(); TestcaseRecordInputStream.ConfirmRecordEncoding(HyperlinkRecord.sid, data_47498, ser); } } }
//------------------------------------------------------------------------------ // <copyright file="DefaultSpatialServices.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner willa // @backupOwner [....] //------------------------------------------------------------------------------ using System.Data.Common.Internal; using System.Diagnostics; using System.Data.Spatial.Internal; namespace System.Data.Spatial { [Serializable] internal sealed class DefaultSpatialServices : DbSpatialServices { #region Provider Value Type [Serializable] private sealed class ReadOnlySpatialValues { private readonly int srid; private readonly byte[] wkb; private readonly string wkt; private readonly string gml; internal ReadOnlySpatialValues(int spatialRefSysId, string textValue, byte[] binaryValue, string gmlValue) { this.srid = spatialRefSysId; this.wkb = (binaryValue == null ? null : (byte[])binaryValue.Clone()); this.wkt = textValue; this.gml = gmlValue; } internal int CoordinateSystemId { get { return this.srid; } } internal byte[] CloneBinary() { return (this.wkb == null ? null : (byte[])this.wkb.Clone()); } internal string Text { get { return this.wkt; } } internal string GML { get { return this.gml; } } } #endregion internal static readonly DefaultSpatialServices Instance = new DefaultSpatialServices(); private DefaultSpatialServices() : base() { } private static Exception SpatialServicesUnavailable() { // return new NotImplementedException(); } private static ReadOnlySpatialValues CheckProviderValue(object providerValue) { ReadOnlySpatialValues expectedValue = providerValue as ReadOnlySpatialValues; if (expectedValue == null) { throw SpatialExceptions.ProviderValueNotCompatibleWithSpatialServices(); } return expectedValue; } private static ReadOnlySpatialValues CheckCompatible(DbGeography geographyValue) { Debug.Assert(geographyValue != null, "Validate geographyValue is non-null before calling CheckCompatible"); if (geographyValue != null) { ReadOnlySpatialValues expectedValue = geographyValue.ProviderValue as ReadOnlySpatialValues; if (expectedValue != null) { return expectedValue; } } throw SpatialExceptions.GeographyValueNotCompatibleWithSpatialServices("geographyValue"); } private static ReadOnlySpatialValues CheckCompatible(DbGeometry geometryValue) { Debug.Assert(geometryValue != null, "Validate geometryValue is non-null before calling CheckCompatible"); if (geometryValue != null) { ReadOnlySpatialValues expectedValue = geometryValue.ProviderValue as ReadOnlySpatialValues; if (expectedValue != null) { return expectedValue; } } throw SpatialExceptions.GeometryValueNotCompatibleWithSpatialServices("geometryValue"); } #region Geography API public override DbGeography GeographyFromProviderValue(object providerValue) { providerValue.CheckNull("providerValue"); ReadOnlySpatialValues expectedValue = CheckProviderValue(providerValue); return CreateGeography(this, expectedValue); } public override object CreateProviderValue(DbGeographyWellKnownValue wellKnownValue) { wellKnownValue.CheckNull("wellKnownValue"); return new ReadOnlySpatialValues(wellKnownValue.CoordinateSystemId, wellKnownValue.WellKnownText, wellKnownValue.WellKnownBinary, gmlValue: null); } public override DbGeographyWellKnownValue CreateWellKnownValue(DbGeography geographyValue) { geographyValue.CheckNull("geographyValue"); ReadOnlySpatialValues backingValue = CheckCompatible(geographyValue); return new DbGeographyWellKnownValue() { CoordinateSystemId = backingValue.CoordinateSystemId, WellKnownBinary = backingValue.CloneBinary(), WellKnownText = backingValue.Text }; } #region Static Constructors - Well Known Binary (WKB) public override DbGeography GeographyFromBinary(byte[] geographyBinary) { geographyBinary.CheckNull("geographyBinary"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(DbGeography.DefaultCoordinateSystemId, textValue: null, binaryValue: geographyBinary, gmlValue: null); return DbSpatialServices.CreateGeography(this, backingValue); } public override DbGeography GeographyFromBinary(byte[] geographyBinary, int spatialReferenceSystemId) { geographyBinary.CheckNull("geographyBinary"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(spatialReferenceSystemId, textValue: null, binaryValue: geographyBinary, gmlValue: null); return DbSpatialServices.CreateGeography(this, backingValue); } public override DbGeography GeographyLineFromBinary(byte[] geographyBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyPointFromBinary(byte[] geographyBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyPolygonFromBinary(byte[] geographyBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyMultiLineFromBinary(byte[] geographyBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyMultiPointFromBinary(byte[] geographyBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "MultiPolygon", Justification = "Match MultiPoint, MultiLine")] public override DbGeography GeographyMultiPolygonFromBinary(byte[] geographyBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyCollectionFromBinary(byte[] geographyBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } #endregion #region Static Constructors - Well Known Text (WKT) public override DbGeography GeographyFromText(string geographyText) { geographyText.CheckNull("geographyText"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(DbGeography.DefaultCoordinateSystemId, textValue: geographyText, binaryValue: null, gmlValue: null); return DbSpatialServices.CreateGeography(this, backingValue); } public override DbGeography GeographyFromText(string geographyText, int spatialReferenceSystemId) { geographyText.CheckNull("geographyText"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(spatialReferenceSystemId, textValue: geographyText, binaryValue: null, gmlValue: null); return DbSpatialServices.CreateGeography(this, backingValue); } public override DbGeography GeographyLineFromText(string geographyText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyPointFromText(string geographyText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyPolygonFromText(string geographyText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyMultiLineFromText(string geographyText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyMultiPointFromText(string geographyText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "MultiPolygon", Justification = "Match MultiPoint, MultiLine")] public override DbGeography GeographyMultiPolygonFromText(string geographyText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeography GeographyCollectionFromText(string geographyText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } #endregion #region Static Constructors - GML public override DbGeography GeographyFromGml(string geographyMarkup) { geographyMarkup.CheckNull("geographyMarkup"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(DbGeography.DefaultCoordinateSystemId, textValue: null, binaryValue: null, gmlValue: geographyMarkup); return DbSpatialServices.CreateGeography(this, backingValue); } public override DbGeography GeographyFromGml(string geographyMarkup, int spatialReferenceSystemId) { geographyMarkup.CheckNull("geographyMarkup"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(spatialReferenceSystemId, textValue: null, binaryValue: null, gmlValue: geographyMarkup); return DbSpatialServices.CreateGeography(this, backingValue); } #endregion #region Geography Instance Property Accessors public override int GetCoordinateSystemId(DbGeography geographyValue) { geographyValue.CheckNull("geographyValue"); ReadOnlySpatialValues backingValue = CheckCompatible(geographyValue); return backingValue.CoordinateSystemId; } public override int GetDimension(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override string GetSpatialTypeName(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override bool GetIsEmpty(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } #endregion #region Geography Well Known Format Conversion public override string AsText(DbGeography geographyValue) { geographyValue.CheckNull("geographyValue"); ReadOnlySpatialValues expectedValue = CheckCompatible(geographyValue); return expectedValue.Text; } public override byte[] AsBinary(DbGeography geographyValue) { geographyValue.CheckNull("geographyValue"); ReadOnlySpatialValues expectedValue = CheckCompatible(geographyValue); return expectedValue.CloneBinary(); } public override string AsGml(DbGeography geographyValue) { geographyValue.CheckNull("geographyValue"); ReadOnlySpatialValues expectedValue = CheckCompatible(geographyValue); return expectedValue.GML; } #endregion #region Geography Instance Methods - Spatial Relation public override bool SpatialEquals(DbGeography geographyValue, DbGeography otherGeography) { throw SpatialServicesUnavailable(); } public override bool Disjoint(DbGeography geographyValue, DbGeography otherGeography) { throw SpatialServicesUnavailable(); } public override bool Intersects(DbGeography geographyValue, DbGeography otherGeography) { throw SpatialServicesUnavailable(); } #endregion #region Geography Instance Methods - Spatial Analysis public override DbGeography Buffer(DbGeography geographyValue, double distance) { throw SpatialServicesUnavailable(); } public override double Distance(DbGeography geographyValue, DbGeography otherGeography) { throw SpatialServicesUnavailable(); } public override DbGeography Intersection(DbGeography geographyValue, DbGeography otherGeography) { throw SpatialServicesUnavailable(); } public override DbGeography Union(DbGeography geographyValue, DbGeography otherGeography) { throw SpatialServicesUnavailable(); } public override DbGeography Difference(DbGeography geographyValue, DbGeography otherGeography) { throw SpatialServicesUnavailable(); } public override DbGeography SymmetricDifference(DbGeography geographyValue, DbGeography otherGeography) { throw SpatialServicesUnavailable(); } #endregion #region Geography Collection public override int? GetElementCount(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override DbGeography ElementAt(DbGeography geographyValue, int index) { throw SpatialServicesUnavailable(); } #endregion #region Point public override double? GetLatitude(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override double? GetLongitude(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override double? GetElevation(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override double? GetMeasure(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } #endregion #region Curve public override double? GetLength(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override DbGeography GetEndPoint(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override DbGeography GetStartPoint(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override bool? GetIsClosed(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } #endregion #region LineString, Line, LinearRing public override int? GetPointCount(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } public override DbGeography PointAt(DbGeography geographyValue, int index) { throw SpatialServicesUnavailable(); } #endregion #region Surface public override double? GetArea(DbGeography geographyValue) { throw SpatialServicesUnavailable(); } #endregion #endregion #region Geometry API public override object CreateProviderValue(DbGeometryWellKnownValue wellKnownValue) { wellKnownValue.CheckNull("wellKnownValue"); return new ReadOnlySpatialValues(wellKnownValue.CoordinateSystemId, wellKnownValue.WellKnownText, wellKnownValue.WellKnownBinary, gmlValue: null); } public override DbGeometryWellKnownValue CreateWellKnownValue(DbGeometry geometryValue) { geometryValue.CheckNull("geometryValue"); ReadOnlySpatialValues backingValue = CheckCompatible(geometryValue); return new DbGeometryWellKnownValue() { CoordinateSystemId = backingValue.CoordinateSystemId, WellKnownBinary = backingValue.CloneBinary(), WellKnownText = backingValue.Text }; } public override DbGeometry GeometryFromProviderValue(object providerValue) { providerValue.CheckNull("providerValue"); ReadOnlySpatialValues expectedValue = CheckProviderValue(providerValue); return CreateGeometry(this, expectedValue); } #region Static Constructors - Well Known Binary (WKB) public override DbGeometry GeometryFromBinary(byte[] geometryBinary) { geometryBinary.CheckNull("geometryBinary"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(DbGeometry.DefaultCoordinateSystemId, textValue: null, binaryValue: geometryBinary, gmlValue: null); return DbSpatialServices.CreateGeometry(this, backingValue); } public override DbGeometry GeometryFromBinary(byte[] geometryBinary, int spatialReferenceSystemId) { geometryBinary.CheckNull("geometryBinary"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(spatialReferenceSystemId, textValue: null, binaryValue: geometryBinary, gmlValue: null); return DbSpatialServices.CreateGeometry(this, backingValue); } public override DbGeometry GeometryLineFromBinary(byte[] geometryBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryPointFromBinary(byte[] geometryBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryPolygonFromBinary(byte[] geometryBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryMultiLineFromBinary(byte[] geometryBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryMultiPointFromBinary(byte[] geometryBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "MultiPolygon", Justification = "Match MultiPoint, MultiLine")] public override DbGeometry GeometryMultiPolygonFromBinary(byte[] geometryBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryCollectionFromBinary(byte[] geometryBinary, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } #endregion #region Static Constructors - Well Known Text (WKT) public override DbGeometry GeometryFromText(string geometryText) { geometryText.CheckNull("geometryText"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(DbGeometry.DefaultCoordinateSystemId, textValue: geometryText, binaryValue: null, gmlValue: null); return DbSpatialServices.CreateGeometry(this, backingValue); } public override DbGeometry GeometryFromText(string geometryText, int spatialReferenceSystemId) { geometryText.CheckNull("geometryText"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(spatialReferenceSystemId, textValue: geometryText, binaryValue: null, gmlValue: null); return DbSpatialServices.CreateGeometry(this, backingValue); } public override DbGeometry GeometryLineFromText(string geometryText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryPointFromText(string geometryText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryPolygonFromText(string geometryText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryMultiLineFromText(string geometryText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryMultiPointFromText(string geometryText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "MultiPolygon", Justification = "Match MultiPoint, MultiLine")] public override DbGeometry GeometryMultiPolygonFromText(string geometryText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } public override DbGeometry GeometryCollectionFromText(string geometryText, int spatialReferenceSystemId) { // Without a backing implementation, this method cannot enforce the requirement that the result be of the specified geometry type throw SpatialServicesUnavailable(); } #endregion #region Static Constructors - GML public override DbGeometry GeometryFromGml(string geometryMarkup) { geometryMarkup.CheckNull("geometryMarkup"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(DbGeometry.DefaultCoordinateSystemId, textValue: null, binaryValue: null, gmlValue: geometryMarkup); return DbSpatialServices.CreateGeometry(this, backingValue); } public override DbGeometry GeometryFromGml(string geometryMarkup, int spatialReferenceSystemId) { geometryMarkup.CheckNull("geometryMarkup"); ReadOnlySpatialValues backingValue = new ReadOnlySpatialValues(spatialReferenceSystemId, textValue: null, binaryValue: null, gmlValue: geometryMarkup); return DbSpatialServices.CreateGeometry(this, backingValue); } #endregion #region Geometry Instance Property Accessors public override int GetCoordinateSystemId(DbGeometry geometryValue) { geometryValue.CheckNull("geometryValue"); ReadOnlySpatialValues backingValue = CheckCompatible(geometryValue); return backingValue.CoordinateSystemId; } public override DbGeometry GetBoundary(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override int GetDimension(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry GetEnvelope(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override string GetSpatialTypeName(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override bool GetIsEmpty(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override bool GetIsSimple(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override bool GetIsValid(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } #endregion #region Geometry Well Known Format Conversion public override string AsText(DbGeometry geometryValue) { geometryValue.CheckNull("geometryValue"); ReadOnlySpatialValues expectedValue = CheckCompatible(geometryValue); return expectedValue.Text; } public override byte[] AsBinary(DbGeometry geometryValue) { geometryValue.CheckNull("geometryValue"); ReadOnlySpatialValues expectedValue = CheckCompatible(geometryValue); return expectedValue.CloneBinary(); } public override string AsGml(DbGeometry geometryValue) { geometryValue.CheckNull("geometryValue"); ReadOnlySpatialValues expectedValue = CheckCompatible(geometryValue); return expectedValue.GML; } #endregion #region Geometry Instance Methods - Spatial Relation public override bool SpatialEquals(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override bool Disjoint(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override bool Intersects(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override bool Touches(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override bool Crosses(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override bool Within(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override bool Contains(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override bool Overlaps(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override bool Relate(DbGeometry geometryValue, DbGeometry otherGeometry, string matrix) { throw SpatialServicesUnavailable(); } #endregion #region Geometry Instance Methods - Spatial Analysis public override DbGeometry Buffer(DbGeometry geometryValue, double distance) { throw SpatialServicesUnavailable(); } public override double Distance(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override DbGeometry GetConvexHull(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry Intersection(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override DbGeometry Union(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override DbGeometry Difference(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } public override DbGeometry SymmetricDifference(DbGeometry geometryValue, DbGeometry otherGeometry) { throw SpatialServicesUnavailable(); } #endregion #region Geometry Instance Methods - Geometry Collection public override int? GetElementCount(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry ElementAt(DbGeometry geometryValue, int index) { throw SpatialServicesUnavailable(); } #endregion #region Geometry Instance Methods - Geometry Collection public override double? GetXCoordinate(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override double? GetYCoordinate(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override double? GetElevation(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override double? GetMeasure(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } #endregion #region Curve public override double? GetLength(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry GetEndPoint(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry GetStartPoint(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override bool? GetIsClosed(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override bool? GetIsRing(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } #endregion #region LineString, Line, LinearRing public override int? GetPointCount(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry PointAt(DbGeometry geometryValue, int index) { throw SpatialServicesUnavailable(); } #endregion #region Surface public override double? GetArea(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry GetCentroid(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry GetPointOnSurface(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } #endregion #region Polygon public override DbGeometry GetExteriorRing(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override int? GetInteriorRingCount(DbGeometry geometryValue) { throw SpatialServicesUnavailable(); } public override DbGeometry InteriorRingAt(DbGeometry geometryValue, int index) { throw SpatialServicesUnavailable(); } #endregion #endregion } }
using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.ServiceProcess; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.Win32; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { [ServiceLocator(Default = typeof(NativeWindowsServiceHelper))] public interface INativeWindowsServiceHelper : IAgentService { string GetUniqueBuildGroupName(); bool LocalGroupExists(string groupName); void CreateLocalGroup(string groupName); void AddMemberToLocalGroup(string accountName, string groupName); void GrantFullControlToGroup(string path, string groupName); bool CheckUserHasLogonAsServicePrivilege(string domain, string userName); bool GrantUserLogonAsServicePrivilage(string domain, string userName); bool IsValidCredential(string domain, string userName, string logonPassword); NTAccount GetDefaultServiceAccount(); void SetPermissionForAccount(string path, string accountName); ServiceController TryGetServiceController(string serviceName); void InstallService(string serviceName, string serviceDisplayName, string logonAccount, string logonPassword); void CreateVstsAgentRegistryKey(); void DeleteVstsAgentRegistryKey(); } public class NativeWindowsServiceHelper : AgentService, INativeWindowsServiceHelper { // TODO: Change it to VSTS_AgentService_G? private const string AgentServiceLocalGroupPrefix = "TFS_BuildService_G"; private ITerminal _term; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _term = hostContext.GetService<ITerminal>(); } public string GetUniqueBuildGroupName() { return AgentServiceLocalGroupPrefix + IOUtil.GetBinPathHash().Substring(0, 5); } public ServiceController TryGetServiceController(string serviceName) { Trace.Entering(); return ServiceController.GetServices() .FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); } // TODO: Make sure to remove Old agent's group and registry changes made during auto upgrade to vsts-agent. public bool LocalGroupExists(string groupName) { Trace.Entering(); bool exists = false; IntPtr bufptr; int returnCode = NetLocalGroupGetInfo(null, groupName, 1, out bufptr); try { switch (returnCode) { case ReturnCode.S_OK: exists = true; break; case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: exists = false; break; case ReturnCode.ERROR_ACCESS_DENIED: // NOTE: None of the exception thrown here are userName facing. The caller logs this exception and prints a more understandable error throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupGetInfo), returnCode)); } } finally { // we don't need to actually read the info to determine whether it exists int bufferFreeError = NetApiBufferFree(bufptr); if (bufferFreeError != 0) { Trace.Error(StringUtil.Format("Buffer free error, could not free buffer allocated, error code: {0}", bufferFreeError)); } } return exists; } public void CreateLocalGroup(string groupName) { Trace.Entering(); LocalGroupInfo groupInfo = new LocalGroupInfo(); groupInfo.Name = groupName; groupInfo.Comment = StringUtil.Format("Built-in group used by Team Foundation Server."); int returnCode = NetLocalGroupAdd(null, 1, ref groupInfo, 0); // return on success if (returnCode == ReturnCode.S_OK) { return; } // Error Cases switch (returnCode) { case ReturnCode.NERR_GroupExists: case ReturnCode.ERROR_ALIAS_EXISTS: Trace.Info(StringUtil.Format("Group {0} already exists", groupName)); break; case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); case ReturnCode.ERROR_INVALID_PARAMETER: throw new ArgumentException(StringUtil.Loc("InvalidGroupName", groupName)); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupAdd), returnCode)); } } public void AddMemberToLocalGroup(string accountName, string groupName) { Trace.Entering(); LocalGroupMemberInfo memberInfo = new LocalGroupMemberInfo(); memberInfo.FullName = accountName; int returnCode = NetLocalGroupAddMembers(null, groupName, 3, ref memberInfo, 1); // return on success if (returnCode == ReturnCode.S_OK) { return; } // Error Cases switch (returnCode) { case ReturnCode.ERROR_MEMBER_IN_ALIAS: Trace.Info(StringUtil.Format("Account {0} is already member of group {1}", accountName, groupName)); break; case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: throw new ArgumentException(StringUtil.Loc("GroupDoesNotExists", groupName)); case ReturnCode.ERROR_NO_SUCH_MEMBER: throw new ArgumentException(StringUtil.Loc("MemberDoesNotExists", accountName)); case ReturnCode.ERROR_INVALID_MEMBER: throw new ArgumentException(StringUtil.Loc("InvalidMember")); case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupAddMembers), returnCode)); } } public void GrantFullControlToGroup(string path, string groupName) { Trace.Entering(); DirectoryInfo dInfo = new DirectoryInfo(path); DirectorySecurity dSecurity = dInfo.GetAccessControl(); if (!dSecurity.AreAccessRulesCanonical) { Trace.Warning("Acls are not canonical, this may cause failure"); } dSecurity.AddAccessRule( new FileSystemAccessRule( groupName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); dInfo.SetAccessControl(dSecurity); } public bool CheckUserHasLogonAsServicePrivilege(string domain, string userName) { Trace.Entering(); ArgUtil.NotNullOrEmpty(userName, nameof(userName)); bool userHasPermission = false; using (LsaPolicy lsaPolicy = new LsaPolicy()) { IntPtr rightsPtr; uint count; uint result = LsaEnumerateAccountRights(lsaPolicy.Handle, GetSidBinaryFromWindows(domain, userName), out rightsPtr, out count); try { if (result == 0) { IntPtr incrementPtr = rightsPtr; for (int i = 0; i < count; i++) { LSA_UNICODE_STRING nativeRightString = Marshal.PtrToStructure<LSA_UNICODE_STRING>(incrementPtr); string rightString = Marshal.PtrToStringAnsi(nativeRightString.Buffer); if (string.Equals(rightString, s_logonAsServiceName, StringComparison.OrdinalIgnoreCase)) { userHasPermission = true; } incrementPtr += Marshal.SizeOf(nativeRightString); } } } finally { result = LsaFreeMemory(rightsPtr); if (result != 0) { Trace.Error(StringUtil.Format("Failed to free memory from LsaEnumerateAccountRights. Return code : {0} ", result)); } } } return userHasPermission; } public bool GrantUserLogonAsServicePrivilage(string domain, string userName) { Trace.Entering(); IntPtr lsaPolicyHandle = IntPtr.Zero; ArgUtil.NotNullOrEmpty(userName, nameof(userName)); try { LSA_UNICODE_STRING system = new LSA_UNICODE_STRING(); LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES() { Length = 0, RootDirectory = IntPtr.Zero, Attributes = 0, SecurityDescriptor = IntPtr.Zero, SecurityQualityOfService = IntPtr.Zero, }; uint result = LsaOpenPolicy(ref system, ref attrib, LSA_POLICY_ALL_ACCESS, out lsaPolicyHandle); if (result != 0 || lsaPolicyHandle == IntPtr.Zero) { if (result == ReturnCode.STATUS_ACCESS_DENIED) { throw new Exception(StringUtil.Loc("ShouldBeAdmin")); } throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), result)); } result = LsaAddAccountRights(lsaPolicyHandle, GetSidBinaryFromWindows(domain, userName), LogonAsServiceRights, 1); Trace.Info("LsaAddAccountRights return with error code {0} ", result); return result == 0; } finally { int result = LsaClose(lsaPolicyHandle); if (result != 0) { Trace.Error(StringUtil.Format("Can not close LasPolicy handler. LsaClose failed with error code {0}", result)); } } } public static void GetAccountSegments(string account, out string domain, out string user) { string[] segments = account.Split('\\'); domain = string.Empty; user = account; if (segments.Length == 2) { domain = segments[0]; user = segments[1]; } } public static bool IsWellKnownIdentity(String accountName) { NTAccount ntaccount = new NTAccount(accountName); SecurityIdentifier sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); SecurityIdentifier networkServiceSid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); SecurityIdentifier localServiceSid = new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null); SecurityIdentifier localSystemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); return sid.Equals(networkServiceSid) || sid.Equals(localServiceSid) || sid.Equals(localSystemSid); } public bool IsValidCredential(string domain, string userName, string logonPassword) { Trace.Entering(); IntPtr tokenHandle = IntPtr.Zero; ArgUtil.NotNullOrEmpty(userName, nameof(userName)); Trace.Verbose(StringUtil.Format("Received domain {0} and username {1} from logonaccount", domain, userName)); int result = LogonUser(userName, domain, logonPassword, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, out tokenHandle); if (tokenHandle.ToInt32() != 0) { if (!CloseHandle(tokenHandle)) { Trace.Error("Failed during CloseHandle on token from LogonUser"); throw new InvalidOperationException(StringUtil.Loc("CanNotVerifyLogonAccountPassword")); } } Trace.Verbose(StringUtil.Format("LogonUser returned with result {0}", result)); return result != 0; } public NTAccount GetDefaultServiceAccount() { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, domainSid: null); NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; if (account == null) { throw new InvalidOperationException(StringUtil.Loc("NetworkServiceNotFound")); } return account; } public void SetPermissionForAccount(string path, string accountName) { Trace.Entering(); string groupName = GetUniqueBuildGroupName(); Trace.Info(StringUtil.Format("Calculated unique group name {0}", groupName)); if (!LocalGroupExists(groupName)) { Trace.Info(StringUtil.Format("Trying to create group {0}", groupName)); CreateLocalGroup(groupName); } Trace.Info(StringUtil.Format("Trying to add userName {0} to the group {0}", accountName, groupName)); AddMemberToLocalGroup(accountName, groupName); Trace.Info(StringUtil.Format("Set full access control to group for the folder {0}", path)); // TODO Check if permission exists GrantFullControlToGroup(path, groupName); } public void InstallService(string serviceName, string serviceDisplayName, string logonAccount, string logonPassword) { Trace.Entering(); string agentServiceExecutable = Path.Combine(IOUtil.GetBinPath(), WindowsServiceControlManager.WindowsServiceControllerName); IntPtr scmHndl = OpenSCManager(null, null, ServiceManagerRights.AllAccess); if (scmHndl.ToInt64() <= 0) { throw new Exception("Failed to Open Service Control Manager"); } try { Trace.Verbose(StringUtil.Format("Opened SCManager. Trying to create service {0}", serviceName)); IntPtr serviceHndl = CreateService( scmHndl, serviceName, serviceDisplayName, ServiceRights.QueryStatus | ServiceRights.Start, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, agentServiceExecutable, null, IntPtr.Zero, null, logonAccount, logonPassword); if (serviceHndl.ToInt64() <= 0) { throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(CreateService), GetLastError())); } //invoke the service with special argument, that tells it to register an event log trace source (need to run as an admin) using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.ExecuteAsync(string.Empty, agentServiceExecutable, "init", null, default(System.Threading.CancellationToken)).GetAwaiter().GetResult(); } _term.WriteLine(StringUtil.Loc("ServiceConfigured", serviceName)); CloseServiceHandle(serviceHndl); } finally { CloseServiceHandle(scmHndl); } } public void CreateVstsAgentRegistryKey() { RegistryKey tfsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0", true); if (tfsKey == null) { //We could be on a machine that doesn't have TFS installed on it, create the key tfsKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0"); } if (tfsKey == null) { throw new ArgumentNullException("Unable to create regiestry key: 'HKLM\\SOFTWARE\\Microsoft\\TeamFoundationServer\\15.0'"); } try { using (RegistryKey vstsAgentsKey = tfsKey.CreateSubKey("VstsAgents")) { String hash = IOUtil.GetBinPathHash(); using (RegistryKey agentKey = vstsAgentsKey.CreateSubKey(hash)) { agentKey.SetValue("InstallPath", Path.Combine(IOUtil.GetBinPath(), "Agent.Listener.exe")); } } } finally { tfsKey.Dispose(); } } public void DeleteVstsAgentRegistryKey() { RegistryKey tfsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0", true); if (tfsKey != null) { try { RegistryKey vstsAgentsKey = tfsKey.OpenSubKey("VstsAgents", true); if (vstsAgentsKey != null) { try { String hash = IOUtil.GetBinPathHash(); vstsAgentsKey.DeleteSubKeyTree(hash); } finally { vstsAgentsKey.Dispose(); } } } finally { tfsKey.Dispose(); } } } private byte[] GetSidBinaryFromWindows(string domain, string user) { try { SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(StringUtil.Format("{0}\\{1}", domain, user).TrimStart('\\')).Translate(typeof(SecurityIdentifier)); byte[] binaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(binaryForm, 0); return binaryForm; } catch (Exception exception) { Trace.Error(exception); return null; } } // Helper class not to repeat whenever we deal with LSA* api internal class LsaPolicy : IDisposable { public IntPtr Handle { get; set; } public LsaPolicy() { LSA_UNICODE_STRING system = new LSA_UNICODE_STRING(); LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES() { Length = 0, RootDirectory = IntPtr.Zero, Attributes = 0, SecurityDescriptor = IntPtr.Zero, SecurityQualityOfService = IntPtr.Zero, }; IntPtr handle = IntPtr.Zero; uint result = LsaOpenPolicy(ref system, ref attrib, LSA_POLICY_ALL_ACCESS, out handle); if (result != 0 || handle == IntPtr.Zero) { if (result == ReturnCode.STATUS_ACCESS_DENIED) { throw new Exception(StringUtil.Loc("ShouldBeAdmin")); } throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), result)); } Handle = handle; } void IDisposable.Dispose() { int result = LsaClose(Handle); if (result != 0) { throw new Exception(StringUtil.Format("OperationFailed", nameof(LsaClose), result)); } GC.SuppressFinalize(this); } } // Declaration of external pinvoke functions private static readonly uint LSA_POLICY_ALL_ACCESS = 0x1FFF; private static readonly string s_logonAsServiceName = "SeServiceLogonRight"; private const UInt32 LOGON32_LOGON_NETWORK = 3; private const UInt32 LOGON32_PROVIDER_DEFAULT = 0; private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010; public const int SERVICE_NO_CHANGE = -1; // TODO Fix this. This is not yet available in coreclr (newer version?) private const int UnicodeCharSize = 2; private static LSA_UNICODE_STRING[] LogonAsServiceRights { get { return new[] { new LSA_UNICODE_STRING() { Buffer = Marshal.StringToHGlobalUni(s_logonAsServiceName), Length = (UInt16)(s_logonAsServiceName.Length * UnicodeCharSize), MaximumLength = (UInt16) ((s_logonAsServiceName.Length + 1) * UnicodeCharSize) } }; } } public struct ReturnCode { public const int S_OK = 0; public const int ERROR_ACCESS_DENIED = 5; public const int ERROR_INVALID_PARAMETER = 87; public const int ERROR_MEMBER_NOT_IN_ALIAS = 1377; // member not in a group public const int ERROR_MEMBER_IN_ALIAS = 1378; // member already exists public const int ERROR_ALIAS_EXISTS = 1379; // group already exists public const int ERROR_NO_SUCH_ALIAS = 1376; public const int ERROR_NO_SUCH_MEMBER = 1387; public const int ERROR_INVALID_MEMBER = 1388; public const int NERR_GroupNotFound = 2220; public const int NERR_GroupExists = 2223; public const int NERR_UserInGroup = 2236; public const uint STATUS_ACCESS_DENIED = 0XC0000022; //NTSTATUS error code: Access Denied } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LocalGroupInfo { [MarshalAs(UnmanagedType.LPWStr)] public string Name; [MarshalAs(UnmanagedType.LPWStr)] public string Comment; } [StructLayout(LayoutKind.Sequential)] public struct LSA_UNICODE_STRING { public UInt16 Length; public UInt16 MaximumLength; // We need to use an IntPtr because if we wrap the Buffer with a SafeHandle-derived class, we get a failure during LsaAddAccountRights public IntPtr Buffer; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LocalGroupMemberInfo { [MarshalAs(UnmanagedType.LPWStr)] public string FullName; } [StructLayout(LayoutKind.Sequential)] public struct LSA_OBJECT_ATTRIBUTES { public UInt32 Length; public IntPtr RootDirectory; public LSA_UNICODE_STRING ObjectName; public UInt32 Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; } [Flags] public enum ServiceManagerRights { Connect = 0x0001, CreateService = 0x0002, EnumerateService = 0x0004, Lock = 0x0008, QueryLockStatus = 0x0010, ModifyBootConfig = 0x0020, StandardRightsRequired = 0xF0000, AllAccess = (StandardRightsRequired | Connect | CreateService | EnumerateService | Lock | QueryLockStatus | ModifyBootConfig) } [Flags] public enum ServiceRights { QueryConfig = 0x1, ChangeConfig = 0x2, QueryStatus = 0x4, EnumerateDependants = 0x8, Start = 0x10, Stop = 0x20, PauseContinue = 0x40, Interrogate = 0x80, UserDefinedControl = 0x100, Delete = 0x00010000, StandardRightsRequired = 0xF0000, AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig | QueryStatus | EnumerateDependants | Start | Stop | PauseContinue | Interrogate | UserDefinedControl) } public enum ServiceError { Ignore = 0x00000000, Normal = 0x00000001, Severe = 0x00000002, Critical = 0x00000003 } public enum ServiceBootFlag { Start = 0x00000000, SystemStart = 0x00000001, AutoStart = 0x00000002, DemandStart = 0x00000003, Disabled = 0x00000004 } [DllImport("Netapi32.dll")] private extern static int NetLocalGroupGetInfo(string servername, string groupname, int level, out IntPtr bufptr); [DllImport("Netapi32.dll")] private extern static int NetApiBufferFree(IntPtr Buffer); [DllImport("Netapi32.dll")] private extern static int NetLocalGroupAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref LocalGroupInfo buf, int parm_err); [DllImport("Netapi32.dll")] private extern static int NetLocalGroupAddMembers([MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string groupName, int level, ref LocalGroupMemberInfo buf, int totalEntries); [DllImport("advapi32.dll")] private static extern Int32 LsaClose(IntPtr ObjectHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaOpenPolicy( ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaAddAccountRights( IntPtr PolicyHandle, byte[] AccountSid, LSA_UNICODE_STRING[] UserRights, uint CountOfRights); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaEnumerateAccountRights( IntPtr PolicyHandle, byte[] AccountSid, out IntPtr UserRights, out uint CountOfRights); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaFreeMemory(IntPtr pBuffer); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int LogonUser(string userName, string domain, string password, uint logonType, uint logonProvider, out IntPtr tokenHandle); [DllImport("kernel32", SetLastError = true)] public static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", EntryPoint = "CreateServiceA")] private static extern IntPtr CreateService( IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword); [DllImport("advapi32.dll")] public static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerRights dwDesiredAccess); [DllImport("advapi32.dll", SetLastError = true)] public static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess); [DllImport("advapi32.dll", SetLastError = true)] public static extern int DeleteService(IntPtr hService); [DllImport("advapi32.dll")] public static extern int CloseServiceHandle(IntPtr hSCObject); [DllImport("kernel32.dll")] static extern uint GetLastError(); } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Branding.InjectResponsiveCSS { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; namespace Orleans.Streams { internal class StreamConsumer<T> : IInternalAsyncObservable<T> { internal bool IsRewindable { get; private set; } private readonly StreamImpl<T> stream; private readonly string streamProviderName; [NonSerialized] private readonly IStreamProviderRuntime providerRuntime; [NonSerialized] private readonly IStreamPubSub pubSub; private StreamConsumerExtension myExtension; private IStreamConsumerExtension myGrainReference; [NonSerialized] private readonly AsyncLock bindExtLock; [NonSerialized] private readonly TraceLogger logger; public StreamConsumer(StreamImpl<T> stream, string streamProviderName, IStreamProviderRuntime providerUtilities, IStreamPubSub pubSub, bool isRewindable) { if (stream == null) throw new ArgumentNullException("stream"); if (providerUtilities == null) throw new ArgumentNullException("providerUtilities"); if (pubSub == null) throw new ArgumentNullException("pubSub"); logger = TraceLogger.GetLogger(string.Format("StreamConsumer<{0}>-{1}", typeof(T).Name, stream), TraceLogger.LoggerType.Runtime); this.stream = stream; this.streamProviderName = streamProviderName; providerRuntime = providerUtilities; this.pubSub = pubSub; IsRewindable = isRewindable; myExtension = null; myGrainReference = null; bindExtLock = new AsyncLock(); } public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer) { return SubscribeAsync(observer, null); } public async Task<StreamSubscriptionHandle<T>> SubscribeAsync( IAsyncObserver<T> observer, StreamSequenceToken token, StreamFilterPredicate filterFunc = null, object filterData = null) { if (token != null && !IsRewindable) throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable."); if (logger.IsVerbose) logger.Verbose("Subscribe Observer={0} Token={1}", observer, token); await BindExtensionLazy(); IStreamFilterPredicateWrapper filterWrapper = null; if (filterFunc != null) filterWrapper = new FilterPredicateWrapperData(filterData, filterFunc); if (logger.IsVerbose) logger.Verbose("Subscribe - Connecting to Rendezvous {0} My GrainRef={1} Token={2}", pubSub, myGrainReference, token); GuidId subscriptionId = pubSub.CreateSubscriptionId(myGrainReference, stream.StreamId); await pubSub.RegisterConsumer(subscriptionId, stream.StreamId, streamProviderName, myGrainReference, token, filterWrapper); return myExtension.SetObserver(subscriptionId, stream, observer, filterWrapper); } public async Task<StreamSubscriptionHandle<T>> ResumeAsync( StreamSubscriptionHandle<T> handle, IAsyncObserver<T> observer, StreamSequenceToken token = null) { StreamSubscriptionHandleImpl<T> oldHandleImpl = CheckHandleValidity(handle); if (token != null && !IsRewindable) throw new ArgumentNullException("token", "Passing a non-null token to a non-rewindable IAsyncObservable."); if (logger.IsVerbose) logger.Verbose("Resume Observer={0} Token={1}", observer, token); await BindExtensionLazy(); if (logger.IsVerbose) logger.Verbose("Resume - Connecting to Rendezvous {0} My GrainRef={1} Token={2}", pubSub, myGrainReference, token); GuidId subscriptionId; if (token != null) { subscriptionId = pubSub.CreateSubscriptionId(myGrainReference, stream.StreamId); // otherwise generate a new subscriptionId await pubSub.RegisterConsumer(subscriptionId, stream.StreamId, streamProviderName, myGrainReference, token, null); try { await UnsubscribeAsync(handle); } catch (Exception exc) { // best effort cleanup of newly established subscription pubSub.UnregisterConsumer(subscriptionId, stream.StreamId, streamProviderName) .LogException(logger, ErrorCode.StreamProvider_FailedToUnsubscribeFromPubSub, String.Format("Stream consumer could not clean up subscription {0} while recovering from errors renewing subscription {1} on stream {2}.", subscriptionId, oldHandleImpl.SubscriptionId, stream.StreamId)) .Ignore(); logger.Error(ErrorCode.StreamProvider_FailedToUnsubscribeFromPubSub, String.Format("Stream consumer failed to unsubscrive from subscription {0} while renewing subscription on stream {1}.", oldHandleImpl.SubscriptionId, stream.StreamId), exc); throw; } } else { subscriptionId = oldHandleImpl.SubscriptionId; } StreamSubscriptionHandle<T> newHandle = myExtension.SetObserver(subscriptionId, stream, observer, null); // On failure caller should be able to retry using the original handle, so invalidate old handle only if everything succeeded. oldHandleImpl.Invalidate(); return newHandle; } public async Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle) { await BindExtensionLazy(); StreamSubscriptionHandleImpl<T> handleImpl = CheckHandleValidity(handle); if (logger.IsVerbose) logger.Verbose("Unsubscribe StreamSubscriptionHandle={0}", handle); bool shouldUnsubscribe = myExtension.RemoveObserver(handle); if (!shouldUnsubscribe) return; if (logger.IsVerbose) logger.Verbose("Unsubscribe - Disconnecting from Rendezvous {0} My GrainRef={1}", pubSub, myGrainReference); await pubSub.UnregisterConsumer(handleImpl.SubscriptionId, stream.StreamId, streamProviderName); handleImpl.Invalidate(); } public async Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptions() { await BindExtensionLazy(); List<GuidId> subscriptionIds = await pubSub.GetAllSubscriptions(stream.StreamId, myGrainReference); return subscriptionIds.Select(id => new StreamSubscriptionHandleImpl<T>(id, stream)) .ToList<StreamSubscriptionHandle<T>>(); } public async Task Cleanup() { if (logger.IsVerbose) logger.Verbose("Cleanup() called"); if (myExtension == null) return; var allHandles = myExtension.GetAllStreamHandles<T>(); var tasks = new List<Task>(); foreach (var handle in allHandles) { myExtension.RemoveObserver(handle); tasks.Add(pubSub.UnregisterConsumer(handle.SubscriptionId, stream.StreamId, streamProviderName)); } try { await Task.WhenAll(tasks); } catch (Exception exc) { logger.Warn((int)ErrorCode.StreamProvider_ConsumerFailedToUnregister, "Ignoring unhandled exception during PubSub.UnregisterConsumer", exc); } myExtension = null; } // Used in test. internal bool InternalRemoveObserver(StreamSubscriptionHandle<T> handle) { return myExtension != null && myExtension.RemoveObserver(handle); } internal Task<int> DiagGetConsumerObserversCount() { return Task.FromResult(myExtension.DiagCountStreamObservers<T>(stream.StreamId)); } private async Task BindExtensionLazy() { if (myExtension == null) { using (await bindExtLock.LockAsync()) { if (myExtension == null) { if (logger.IsVerbose) logger.Verbose("BindExtensionLazy - Binding local extension to stream runtime={0}", providerRuntime); var tup = await providerRuntime.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>( () => new StreamConsumerExtension(providerRuntime)); myExtension = tup.Item1; myGrainReference = tup.Item2; if (logger.IsVerbose) logger.Verbose("BindExtensionLazy - Connected Extension={0} GrainRef={1}", myExtension, myGrainReference); } } } } private StreamSubscriptionHandleImpl<T> CheckHandleValidity(StreamSubscriptionHandle<T> handle) { if (handle == null) throw new ArgumentNullException("handle"); if (!handle.StreamIdentity.Equals(stream)) throw new ArgumentException("Handle is not for this stream.", "handle"); var handleImpl = handle as StreamSubscriptionHandleImpl<T>; if (handleImpl == null) throw new ArgumentException("Handle type not supported.", "handle"); if (!handleImpl.IsValid) throw new ArgumentException("Handle is no longer valid. It has been used to unsubscribe or resume.", "handle"); return handleImpl; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; public class RelativisticParent : MonoBehaviour { //Keep track of our own Mesh Filter private MeshFilter meshFilter; //Store this object's velocity here. public Vector3 viw; private GameState state; //When was this object created? use for moving objects private float startTime = 0; //When should we die? again, for moving objects private float deathTime = 0; // Get the start time of our object, so that we know where not to draw it public void SetStartTime() { startTime = (float) GameObject.FindGameObjectWithTag(Tags.player).GetComponent<GameState>().TotalTimeWorld; } //Set the death time, so that we know at what point to destroy the object in the player's view point. public void SetDeathTime() { deathTime = (float)state.TotalTimeWorld; } //This is a function that just ensures we're slower than our maximum speed. The VIW that Unity sets SHOULD (it's creator-chosen) be smaller than the maximum speed. private void checkSpeed() { if (viw.magnitude > state.MaxSpeed-.01) { viw = viw.normalized * (float)(state.MaxSpeed-.01f); } } // Use this for initialization void Start() { if (GetComponent<ObjectMeshDensity>()) { GetComponent<ObjectMeshDensity>().enabled = false; } int vertCount = 0, triangleCount = 0; checkSpeed (); Matrix4x4 worldLocalMatrix = transform.worldToLocalMatrix; //This code combines the meshes of children of parent objects //This increases our FPS by a ton //Get an array of the meshfilters MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>(); //Count submeshes int[] subMeshCount = new int[meshFilters.Length]; //Get all the meshrenderers MeshRenderer[] meshRenderers = GetComponentsInChildren<MeshRenderer>(); //Length of our original array int meshFilterLength = meshFilters.Length; //And a counter int subMeshCounts = 0; //For every meshfilter, for (int y = 0; y < meshFilterLength; y++) { //If it's null, ignore it. if (meshFilters[y] == null) continue; if (meshFilters[y].sharedMesh == null) continue; //else add its vertices to the vertcount vertCount += meshFilters[y].sharedMesh.vertices.Length; //Add its triangles to the count triangleCount += meshFilters[y].sharedMesh.triangles.Length; //Add the number of submeshes to its spot in the array subMeshCount[y] = meshFilters[y].mesh.subMeshCount; //And add up the total number of submeshes subMeshCounts += meshFilters[y].mesh.subMeshCount; } // Get a temporary array of EVERY vertex Vector3[] tempVerts = new Vector3[vertCount]; //And make a triangle array for every submesh int[][] tempTriangles = new int[subMeshCounts][]; for (int u = 0; u < subMeshCounts; u++) { //Make every array the correct length of triangles tempTriangles[u] = new int[triangleCount]; } //Also grab our UV texture coordinates Vector2[] tempUVs = new Vector2[vertCount]; //And store a number of materials equal to the number of submeshes. Material[] tempMaterials = new Material[subMeshCounts]; int vertIndex = 0; Mesh MFs; int subMeshIndex = 0; //For all meshfilters for (int i = 0; i < meshFilterLength; i++) { //just doublecheck that the mesh isn't null MFs = meshFilters[i].sharedMesh; if (MFs == null) continue; //Otherwise, for all submeshes in the current mesh for (int q = 0; q < subMeshCount[i]; q++) { //grab its material tempMaterials[subMeshIndex] = meshRenderers[i].materials[q]; //Grab its triangles int[] tempSubTriangles = MFs.GetTriangles(q); //And put them into the submesh's triangle array for (int k = 0; k < tempSubTriangles.Length; k++) { tempTriangles[subMeshIndex][k] = tempSubTriangles[k] + vertIndex; } //Increment the submesh index subMeshIndex++; } Matrix4x4 cTrans = worldLocalMatrix * meshFilters[i].transform.localToWorldMatrix; //For all the vertices in the mesh for (int v = 0; v < MFs.vertices.Length; v++) { //Get the vertex and the UV coordinate tempVerts[vertIndex] = cTrans.MultiplyPoint3x4(MFs.vertices[v]); tempUVs[vertIndex] = MFs.uv[v]; vertIndex++; } //And delete that gameobject. meshFilters[i].gameObject.SetActive(false); } //Put it all together now. Mesh myMesh = new Mesh(); //Make the mesh have as many submeshes as you need myMesh.subMeshCount = subMeshCounts; //Set its vertices to tempverts myMesh.vertices = tempVerts; //start at the first submesh subMeshIndex = 0; //For every submesh in each meshfilter for (int l = 0; l < meshFilterLength; l++) { for (int g = 0; g < subMeshCount[l]; g++) { //Set a new submesh, using the triangle array and its submesh index (built in unity function) myMesh.SetTriangles(tempTriangles[subMeshIndex], subMeshIndex); //increment the submesh index subMeshIndex++; } } //Just shunt in the UV coordinates, we don't need to change them myMesh.uv = tempUVs; //THEN totally replace our object's mesh with this new, combined mesh GetComponent<MeshFilter>().mesh = myMesh; GetComponent<MeshRenderer>().enabled = true; GetComponent<MeshFilter>().mesh.RecalculateNormals(); GetComponent<MeshFilter>().GetComponent<Renderer>().materials = tempMaterials; transform.gameObject.SetActive(true); //End section of combining meshes state = GameObject.FindGameObjectWithTag(Tags.player).GetComponent<GameState>(); meshFilter = GetComponent<MeshFilter>(); MeshRenderer tempRenderer = GetComponent<MeshRenderer>(); //Then the standard RelativisticObject startup if (tempRenderer.materials[0].mainTexture != null) { //So that we can set unique values to every moving object, we have to instantiate a material //It's the same as our old one, but now it's not connected to every other object with the same material Material quickSwapMaterial = Instantiate((tempRenderer as Renderer).materials[0]) as Material; //Then, set the value that we want quickSwapMaterial.SetFloat("_viw", 0); //And stick it back into our renderer. We'll do the SetVector thing every frame. tempRenderer.materials[0] = quickSwapMaterial; //set our start time and start position in the shader. tempRenderer.materials[0].SetFloat("_strtTime", (float)startTime); tempRenderer.materials[0].SetVector("_strtPos", new Vector4(transform.position.x, transform.position.y, transform.position.z, 0)); } //This code is a hack to ensure that frustrum culling does not take place //It changes the render bounds so that everything is contained within them Transform camTransform = Camera.main.transform; float distToCenter = (Camera.main.farClipPlane - Camera.main.nearClipPlane) / 2.0f; Vector3 center = camTransform.position + camTransform.forward * distToCenter; float extremeBound = 500000.0f; meshFilter.sharedMesh.bounds = new Bounds(center, Vector3.one * extremeBound); if (GetComponent<ObjectMeshDensity>()) { GetComponent<ObjectMeshDensity>().enabled = true; } } // Update is called once per frame void Update() { //Grab our renderer. MeshRenderer tempRenderer = GetComponent<MeshRenderer>(); if (meshFilter != null && !state.MovementFrozen) { //Send our object's v/c (Velocity over the Speed of Light) to the shader if (tempRenderer != null) { Vector3 tempViw = viw / (float)state.SpeedOfLight; tempRenderer.materials[0].SetVector("_viw", new Vector4(tempViw.x, tempViw.y, tempViw.z, 0)); } //As long as our object is actually alive, perform these calculations if (transform!=null && deathTime != 0) { //Here I take the angle that the player's velocity vector makes with the z axis float rotationAroundZ = 57.2957795f * Mathf.Acos(Vector3.Dot(state.PlayerVelocityVector, Vector3.forward) / state.PlayerVelocityVector.magnitude); if (state.PlayerVelocityVector.sqrMagnitude == 0) { rotationAroundZ = 0; } //Now we turn that rotation into a quaternion Quaternion rotateZ = Quaternion.AngleAxis(-rotationAroundZ, Vector3.Cross(state.PlayerVelocityVector,Vector3.forward)); //****************************************************************** //Place the vertex to be changed in a new Vector3 Vector3 riw = new Vector3(transform.position.x, transform.position.y, transform.position.z); riw -= state.playerTransform.position; //And we rotate our point that much to make it as if our magnitude of velocity is in the Z direction riw = rotateZ * riw; //Here begins the original code, made by the guys behind the Relativity game /**************************** * Start Part 6 Bullet 1 */ //Rotate that velocity! Vector3 storedViw = rotateZ * viw; float c = -Vector3.Dot(riw, riw); //first get position squared (position doted with position) float b = -(2 * Vector3.Dot(riw, storedViw)); //next get position doted with velocity, should be only in the Z direction float a = (float)state.SpeedOfLightSqrd - Vector3.Dot(storedViw, storedViw); /**************************** * Start Part 6 Bullet 2 * **************************/ float tisw = (float)(((-b - (Math.Sqrt((b * b) - 4f * a * c))) / (2f * a))); //If we're past our death time (in the player's view, as seen by tisw) if (state.TotalTimeWorld + tisw > deathTime) { Destroy(this.gameObject); } } //make our rigidbody's velocity viw if (GetComponent<Rigidbody>()!=null) { if (!double.IsNaN((double)state.SqrtOneMinusVSquaredCWDividedByCSquared) && (float)state.SqrtOneMinusVSquaredCWDividedByCSquared != 0) { Vector3 tempViw = viw; //ASK RYAN WHY THESE WERE DIVIDED BY THIS tempViw.x /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared; tempViw.y /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared; tempViw.z /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared; GetComponent<Rigidbody>().velocity = tempViw; } } } } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Data. THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Data. THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.IO; using GME.CSharp; using GME; using System.Windows.Forms; using GME.MGA; using GME.MGA.Core; using System.Linq; using GME.MGA.Meta; using META; namespace CyPhyDecoratorAddon { [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class CyPhyDecoratorAddon : IMgaComponentEx, IGMEVersionInfo, IMgaEventSink { private MgaAddOn addon; private bool componentEnabled = true; bool isXMLImportInProgress { get; set; } bool isProjectInTransation { get; set; } string DecoratorName { get { return "MGA.Decorator.Workflow"; } } // Event handlers for addons #region MgaEventSink members public void GlobalEvent(globalevent_enum @event) { if (@event == globalevent_enum.GLOBALEVENT_CLOSE_PROJECT) { Marshal.FinalReleaseComObject(addon); addon = null; } else if (@event == globalevent_enum.APPEVENT_XML_IMPORT_BEGIN) { isXMLImportInProgress = true; } else if (@event == globalevent_enum.APPEVENT_XML_IMPORT_END) { isXMLImportInProgress = false; } //else if (@event == globalevent_enum.GLOBALEVENT_COMMIT_TRANSACTION) //{ // isProjectInTransation = true; //} //else if (@event == globalevent_enum.GLOBALEVENT_DESTROY_TERRITORY) //{ // isProjectInTransation = false; //} if (!componentEnabled) { return; } // TODO: Handle global events // MessageBox.Show(@event.ToString()); } /// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject"> /// the object the event(s) happened to /// </param> /// <param name="eventMask"> /// objectevent_enum values ORed together /// </param> /// <param name="param"> /// extra information provided for cetertain event types /// </param> public void ObjectEvent( MgaObject subject, uint eventMask, object param) { if (!componentEnabled) { return; } else if (isXMLImportInProgress) { return; } //else if (isProjectInTransation) //{ // return; //} if (subject.HasReadOnlyAccess() || subject.IsLibObject) { return; } uint uOBJEVENT_CREATED = 0; uint uOBJEVENT_COPIED = 0; unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; } unchecked { uOBJEVENT_COPIED = (uint)objectevent_enum.OBJEVENT_COPIED; } if ((eventMask & uOBJEVENT_COPIED) != 0) { isCopied = true; } else if ((eventMask & uOBJEVENT_CREATED) != 0 && subject.Status == 0) // check Status, since object can be created and deleted in same tx { if (isCopied) { // handle copy event isCopied = false; } else { //subject.Project.RootMeta.RootFolder.DefinedFCOByName["Task", //MgaMetaBase task; //if (task.MetaRef == subject.MetaBase.MetaRef) { } // handle new object event if (subject.MetaBase.Name == "Task" || subject.MetaBase.Name == "WorkflowRef") { Type t = Type.GetTypeFromProgID(DecoratorName); if (t != null) { (subject as MgaFCO).RegistryValue["decorator"] = DecoratorName; } } bool isBasicTask = (subject.MetaBase.Name == "Task"); if (subject.MetaBase.Name == "Task" || subject.MetaBase.Name == "ExecutionTask") { using (InterpreterSelectionForm form = new InterpreterSelectionForm()) { form.addon = this; form.Init(); IEnumerable<MgaAtom> taskChildren = subject.ExGetParent(). ChildObjects. OfType<MgaAtom>(). Where(x => x.ExDstFcos().Count() == 0). Where(x => x.ID != subject.ID); form.lbTasks.Items.Clear(); foreach (var currTask in taskChildren) { var atomWrapper = new MgaAtomWrapper(currTask); form.lbTasks.Items.Add(new MgaAtomWrapper(currTask)); form.lbTasks.SelectedItem = atomWrapper; } if (form.lbTasks.Items.Count > 0) { form.lbTasks.SetSelected(0, true); } if (!isBasicTask) // remove interpreter selection and reset positions { form.lbInterpreters.Items.Clear(); form.lbInterpreters.Visible = false; form.lblSelectInterpreter.Visible = false; form.chbAutoConnect.Location = form.label1.Location; form.label1.Location = form.lblSelectInterpreter.Location; form.lbTasks.Location = form.lbInterpreters.Location; } DialogResult dgr = form.ShowDialog(); if (dgr == DialogResult.OK) { if (isBasicTask) { ComComponent c = form.lbInterpreters.SelectedItem as ComComponent; try { if (c != null && c.isValid) { (subject as MgaFCO).StrAttrByName["COMName"] = c.ProgId; } } catch { MessageBox.Show("Cannot save interpreter settings. 'COMName' is not a parameter of 'Task'."); } } //Flow if (form.chbAutoConnect.Checked && (form.lbTasks.SelectedItem != null)) { MgaAtomWrapper selectedTask = form.lbTasks.SelectedItem as MgaAtomWrapper; MgaAtom lastInWorkflow = null; if (selectedTask != null) { lastInWorkflow = selectedTask.Atom; } if (lastInWorkflow != null) { MgaMetaRole role = ((subject.ExGetParent() as MgaModel). Meta as MgaMetaModel).RoleByName["Flow"]; (subject.ExGetParent() as MgaModel).CreateSimplerConnDisp( role, lastInWorkflow as MgaFCO, subject as MgaFCO); } } } } } } } // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask // MessageBox.Show(eventMask.ToString()); } bool isCopied { get; set; } #endregion #region IMgaComponentEx Members public void Initialize(MgaProject p) { // Creating addon p.CreateAddOn(this, out addon); // Setting event mask (see ComponentConfig.eventMask) unchecked { addon.EventMask = (uint)ComponentConfig.eventMask; } } public void InvokeEx( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); // Not called by addon } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = null; public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #endregion } internal class MgaAtomWrapper { protected MgaAtom atom; protected string name; public MgaAtom Atom { get { return atom; } } public MgaAtomWrapper(MgaAtom atom) { this.atom = atom; } public override string ToString() { return atom.Name; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using System.Configuration; using System.IO; using System.ComponentModel; using Csla.Validation; namespace Northwind.CSLA.Library { /// <summary> /// ProductOrderDetails Generated by MyGeneration using the CSLA Object Mapping template /// </summary> [Serializable()] [TypeConverter(typeof(ProductOrderDetailsConverter))] public partial class ProductOrderDetails : BusinessListBase<ProductOrderDetails, ProductOrderDetail>, ICustomTypeDescriptor, IVEHasBrokenRules { #region Business Methods private string _ErrorMessage = string.Empty; public string ErrorMessage { get { return _ErrorMessage; } } // Many To Many public ProductOrderDetail this[Order myOrder] { get { foreach (ProductOrderDetail orderDetail in this) if (orderDetail.OrderID == myOrder.OrderID) return orderDetail; return null; } } public new System.Collections.Generic.IList<ProductOrderDetail> Items { get { return base.Items; } } public ProductOrderDetail GetItem(Order myOrder) { foreach (ProductOrderDetail orderDetail in this) if (orderDetail.OrderID == myOrder.OrderID) return orderDetail; return null; } public ProductOrderDetail Add(Order myOrder)// Many to Many with required fields { if (!Contains(myOrder)) { ProductOrderDetail orderDetail = ProductOrderDetail.New(myOrder); this.Add(orderDetail); return orderDetail; } else throw new InvalidOperationException("orderDetail already exists"); } public void Remove(Order myOrder) { foreach (ProductOrderDetail orderDetail in this) { if (orderDetail.OrderID == myOrder.OrderID) { Remove(orderDetail); break; } } } public bool Contains(Order myOrder) { foreach (ProductOrderDetail orderDetail in this) if (orderDetail.OrderID == myOrder.OrderID) return true; return false; } public bool ContainsDeleted(Order myOrder) { foreach (ProductOrderDetail orderDetail in DeletedList) if (orderDetail.OrderID == myOrder.OrderID) return true; return false; } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules { get { IVEHasBrokenRules hasBrokenRules=null; foreach(ProductOrderDetail productOrderDetail in this) if ((hasBrokenRules = productOrderDetail.HasBrokenRules) != null) return hasBrokenRules; return hasBrokenRules; } } public BrokenRulesCollection BrokenRules { get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); } } #endregion #region Factory Methods internal static ProductOrderDetails New() { return new ProductOrderDetails(); } internal static ProductOrderDetails Get(SafeDataReader dr) { return new ProductOrderDetails(dr); } public static ProductOrderDetails GetByProductID(int productID) { try { return DataPortal.Fetch<ProductOrderDetails>(new ProductIDCriteria(productID)); } catch (Exception ex) { throw new DbCslaException("Error on ProductOrderDetails.GetByProductID", ex); } } private ProductOrderDetails() { MarkAsChild(); } internal ProductOrderDetails(SafeDataReader dr) { MarkAsChild(); Fetch(dr); } #endregion #region Data Access Portal // called to load data from the database private void Fetch(SafeDataReader dr) { this.RaiseListChangedEvents = false; while (dr.Read()) this.Add(ProductOrderDetail.Get(dr)); this.RaiseListChangedEvents = true; } [Serializable()] private class ProductIDCriteria { public ProductIDCriteria(int productID) { _ProductID = productID; } private int _ProductID; public int ProductID { get { return _ProductID; } set { _ProductID = value; } } } private void DataPortal_Fetch(ProductIDCriteria criteria) { this.RaiseListChangedEvents = false; Database.LogInfo("ProductOrderDetails.DataPortal_FetchProductID", GetHashCode()); try { using (SqlConnection cn = Database.Northwind_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "getOrderDetailsByProductID"; cm.Parameters.AddWithValue("@ProductID", criteria.ProductID); using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { while (dr.Read()) this.Add(new ProductOrderDetail(dr)); } } } } catch (Exception ex) { Database.LogException("ProductOrderDetails.DataPortal_FetchProductID", ex); throw new DbCslaException("ProductOrderDetails.DataPortal_Fetch", ex); } this.RaiseListChangedEvents = true; } internal void Update(Product product) { this.RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects foreach (ProductOrderDetail obj in DeletedList) obj.Delete();// TODO: Should this be SQLDelete // now that they are deleted, remove them from memory too DeletedList.Clear(); // add/update any current child objects foreach (ProductOrderDetail obj in this) { if (obj.IsNew) obj.Insert(product); else obj.Update(product); } } finally { this.RaiseListChangedEvents = true; } } #endregion #region ICustomTypeDescriptor impl public String GetClassName() { return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public String GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } /// <summary> /// Called to get the properties of this type. Returns properties with certain /// attributes. this restriction is not implemented here. /// </summary> /// <param name="attributes"></param> /// <returns></returns> public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return GetProperties(); } /// <summary> /// Called to get the properties of this type. /// </summary> /// <returns></returns> public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list for (int i = 0; i < this.Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ProductOrderDetailsPropertyDescriptor pd = new ProductOrderDetailsPropertyDescriptor(this, i); pds.Add(pd); } // return the property descriptor collection return pds; } #endregion } // Class #region Property Descriptor /// <summary> /// Summary description for CollectionPropertyDescriptor. /// </summary> public partial class ProductOrderDetailsPropertyDescriptor : vlnListPropertyDescriptor { private ProductOrderDetail Item { get { return (ProductOrderDetail) _Item;} } public ProductOrderDetailsPropertyDescriptor(ProductOrderDetails collection, int index):base(collection, index){;} } #endregion #region Converter internal class ProductOrderDetailsConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is ProductOrderDetails) { // Return department and department role separated by comma. return ((ProductOrderDetails) value).Items.Count.ToString() + " OrderDetails"; } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace
using BulletMLLib; using BulletMLSample; using FilenameBuddy; using NUnit.Framework; using System; namespace BulletMLTests { [TestFixture()] public class TestAimXml { MoverManager manager; Myship dude; BulletPattern pattern; [SetUp()] public void setupHarness() { Filename.SetCurrentDirectory(@"C:\Projects\BulletMLLib\BulletMLLib\BulletMLLib.Tests\bin\Debug"); dude = new Myship(); manager = new MoverManager(dude.Position); pattern = new BulletPattern(manager); } [Test()] public void CorrectNumberOfBullets() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); Assert.AreEqual(1, manager.movers.Count); } [Test()] public void CorrectNumberOfBullets1() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); manager.Update(); Assert.AreEqual(2, manager.movers.Count); } [Test()] public void CorrectNumberOfBullets2() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); //run the thing ten times for (int i = 2; i < 12; i++) { manager.Update(); Assert.AreEqual(i, manager.movers.Count); } //there should be 11 bullets Assert.AreEqual(11, manager.movers.Count); } [Test()] public void CorrectDirection() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); //run the thing ten times for (int i = 0; i < 10; i++) { manager.Update(); } for (int i = 1; i < manager.movers.Count; i++) { Mover testDude = manager.movers[i]; float direction = testDude.Direction * 180 / (float)Math.PI; Assert.AreEqual(90.0f, direction); } } [Test()] public void SpeedInitializedCorrect() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); //get the fire task FireTask testTask = mover.FindTaskByLabel("testFire") as FireTask; Assert.IsNotNull(testTask); Assert.IsNotNull(testTask.InitialSpeedTask); Assert.IsNotNull(testTask.SequenceSpeedTask); } [Test()] public void SpeedInitializedCorrect1() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); FireTask testTask = mover.FindTaskByLabel("testFire") as FireTask; Assert.IsNotNull(testTask.InitialSpeedTask); Assert.IsNotNull(testTask.SequenceSpeedTask); } [Test()] public void SpeedInitializedCorrect2() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); FireTask testTask = mover.FindTaskByLabel("testFire") as FireTask; Assert.AreEqual(1.0f, testTask.InitialSpeedTask.GetNodeValue(mover)); Assert.AreEqual(1.0f, testTask.SequenceSpeedTask.GetNodeValue(mover)); } [Test()] public void SpeedInitializedCorrect3() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); FireTask testTask = mover.FindTaskByLabel("testFire") as FireTask; Assert.AreEqual(1, testTask.NumTimesInitialized); } [Test()] public void SpeedInitializedCorrect4() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); FireTask testTask = mover.FindTaskByLabel("testFire") as FireTask; Assert.AreEqual(1.0f, testTask.FireSpeed); } [Test()] public void CorrectSpeed() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); //run the thing ten times for (int i = 0; i < 10; i++) { manager.Update(); } //check the top bullet Mover testDude = manager.movers[0]; Assert.AreEqual(0, testDude.Speed); //check the second bullet testDude = manager.movers[1]; Assert.AreEqual(1, testDude.Speed); } [Test()] public void CorrectSpeed1() { dude.pos.X = 100.0f; dude.pos.Y = 0.0f; var filename = new Filename(@"Aim.xml"); pattern.ParseXML(filename.File); Mover mover = (Mover)manager.CreateBullet(); mover.InitTopNode(pattern.RootNode); //run the thing ten times for (int i = 0; i < 10; i++) { manager.Update(); } //check the first bullet //check the second bullet for (int i = 1; i < manager.movers.Count; i++) { Mover testDude = manager.movers[i]; Assert.AreEqual(i, testDude.Speed); } } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using TestExtensions; namespace UnitTests.Serialization { using Orleans.Serialization; using Xunit; [TestCategory("BVT"), TestCategory("Serialization")] public class ILBasedExceptionSerializerTests { private readonly ILSerializerGenerator serializerGenerator = new ILSerializerGenerator(); private readonly SerializationTestEnvironment environment; public ILBasedExceptionSerializerTests() { this.environment = SerializationTestEnvironment.Initialize(null, typeof(ILBasedSerializer).GetTypeInfo()); } /// <summary> /// Tests that <see cref="ILBasedExceptionSerializer"/> supports distinct field selection for serialization /// versus copy operations. /// </summary> [Fact] public void ExceptionSerializer_SimpleException() { // Throw an exception so that is has a stack trace. var expected = GetNewException(); this.TestExceptionSerialization(expected); } private ILExceptionSerializerTestException TestExceptionSerialization(ILExceptionSerializerTestException expected) { var writer = new SerializationContext(this.environment.SerializationManager) { StreamWriter = new BinaryTokenStreamWriter() }; // Deep copies should be reference-equal. Assert.Equal( expected, SerializationManager.DeepCopyInner(expected, new SerializationContext(this.environment.SerializationManager)), ReferenceEqualsComparer.Instance); this.environment.SerializationManager.Serialize(expected, writer.StreamWriter); var reader = new DeserializationContext(this.environment.SerializationManager) { StreamReader = new BinaryTokenStreamReader(writer.StreamWriter.ToByteArray()) }; var actual = (ILExceptionSerializerTestException) this.environment.SerializationManager.Deserialize(null, reader.StreamReader); Assert.Equal(expected.BaseField.Value, actual.BaseField.Value, StringComparer.Ordinal); Assert.Equal(expected.SubClassField, actual.SubClassField, StringComparer.Ordinal); Assert.Equal(expected.OtherField.Value, actual.OtherField.Value, StringComparer.Ordinal); // Check for referential equality in the two fields which happened to be reference-equals. Assert.Equal(actual.BaseField, actual.OtherField, ReferenceEqualsComparer.Instance); return actual; } /// <summary> /// Tests that <see cref="ILBasedExceptionSerializer"/> supports reference cycles. /// </summary> [Fact] public void ExceptionSerializer_ReferenceCycle() { // Throw an exception so that is has a stack trace. var expected = GetNewException(); // Create a reference cycle at the top level. expected.SomeObject = expected; var actual = this.TestExceptionSerialization(expected); Assert.Equal(actual, actual.SomeObject); } /// <summary> /// Tests that <see cref="ILBasedExceptionSerializer"/> supports reference cycles. /// </summary> [Fact] public void ExceptionSerializer_NestedReferenceCycle() { // Throw an exception so that is has a stack trace. var exception = GetNewException(); var expected = new Outer { SomeFunObject = exception.OtherField, Object = exception, }; // Create a reference cycle. exception.SomeObject = expected; var writer = new SerializationContext(this.environment.SerializationManager) { StreamWriter = new BinaryTokenStreamWriter() }; this.environment.SerializationManager.Serialize(expected, writer.StreamWriter); var reader = new DeserializationContext(this.environment.SerializationManager) { StreamReader = new BinaryTokenStreamReader(writer.StreamWriter.ToByteArray()) }; var actual = (Outer)this.environment.SerializationManager.Deserialize(null, reader.StreamReader); Assert.Equal(expected.Object.BaseField.Value, actual.Object.BaseField.Value, StringComparer.Ordinal); Assert.Equal(expected.Object.SubClassField, actual.Object.SubClassField, StringComparer.Ordinal); Assert.Equal(expected.Object.OtherField.Value, actual.Object.OtherField.Value, StringComparer.Ordinal); // Check for referential equality in the fields which happened to be reference-equals. Assert.Equal(actual.Object.BaseField, actual.Object.OtherField, ReferenceEqualsComparer.Instance); Assert.Equal(actual.Object, actual.Object.SomeObject, ReferenceEqualsComparer.Instance); Assert.Equal(actual.SomeFunObject, actual.Object.OtherField, ReferenceEqualsComparer.Instance); } private static ILExceptionSerializerTestException GetNewException() { ILExceptionSerializerTestException expected; try { var baseField = new SomeFunObject { Value = Guid.NewGuid().ToString() }; var res = new ILExceptionSerializerTestException { BaseField = baseField, SubClassField = Guid.NewGuid().ToString(), OtherField = baseField, }; throw res; } catch (ILExceptionSerializerTestException exception) { expected = exception; } return expected; } /// <summary> /// Tests that <see cref="ILBasedExceptionSerializer"/> supports distinct field selection for serialization /// versus copy operations. /// </summary> [Fact] public void ExceptionSerializer_UnknownException() { var expected = GetNewException(); var knowsException = new ILBasedExceptionSerializer(this.serializerGenerator, new TypeSerializer(new CachedTypeResolver())); var writer = new SerializationContext(this.environment.SerializationManager) { StreamWriter = new BinaryTokenStreamWriter() }; knowsException.Serialize(expected, writer, null); // Deep copies should be reference-equal. var copyContext = new SerializationContext(this.environment.SerializationManager); Assert.Equal(expected, knowsException.DeepCopy(expected, copyContext), ReferenceEqualsComparer.Instance); // Create a deserializer which doesn't know about the expected exception type. var reader = new DeserializationContext(this.environment.SerializationManager) { StreamReader = new BinaryTokenStreamReader(writer.StreamWriter.ToByteArray()) }; // Ensure that the deserialized object has the fallback type. var doesNotKnowException = new ILBasedExceptionSerializer(this.serializerGenerator, new TestTypeSerializer(new CachedTypeResolver())); var untypedActual = doesNotKnowException.Deserialize(null, reader); Assert.IsType<RemoteNonDeserializableException>(untypedActual); // Ensure that the original type name is preserved correctly. var actualDeserialized = (RemoteNonDeserializableException) untypedActual; Assert.Equal(typeof(ILExceptionSerializerTestException).AssemblyQualifiedName, actualDeserialized.OriginalTypeName); // Re-serialize the deserialized object using the serializer which does not have access to the original type. writer = new SerializationContext(this.environment.SerializationManager) { StreamWriter = new BinaryTokenStreamWriter() }; doesNotKnowException.Serialize(untypedActual, writer, null); reader = new DeserializationContext(this.environment.SerializationManager) { StreamReader = new BinaryTokenStreamReader(writer.StreamWriter.ToByteArray()) }; // Deserialize the round-tripped object and verify that it has the original type and all properties are // correctly. untypedActual = knowsException.Deserialize(null, reader); Assert.IsType<ILExceptionSerializerTestException>(untypedActual); var actual = (ILExceptionSerializerTestException) untypedActual; Assert.Equal(expected.BaseField.Value, actual.BaseField.Value, StringComparer.Ordinal); Assert.Equal(expected.SubClassField, actual.SubClassField, StringComparer.Ordinal); Assert.Equal(expected.OtherField.Value, actual.OtherField.Value, StringComparer.Ordinal); // Check for referential equality in the two fields which happened to be reference-equals. Assert.Equal(actual.BaseField, actual.OtherField, ReferenceEqualsComparer.Instance); } private class Outer { public SomeFunObject SomeFunObject { get; set; } public ILExceptionSerializerTestException Object { get; set; } } private class SomeFunObject { public string Value { get; set; } } private class BaseException : Exception { public SomeFunObject BaseField { get; set; } } private class ILExceptionSerializerTestException : BaseException { public string SubClassField { get; set; } public SomeFunObject OtherField { get; set; } public object SomeObject { get; set; } } private class TestTypeSerializer : TypeSerializer { internal override Type GetTypeFromName(string assemblyQualifiedTypeName, bool throwOnError) { if (throwOnError) throw new TypeLoadException($"Type {assemblyQualifiedTypeName} could not be loaded"); return null; } public TestTypeSerializer(ITypeResolver typeResolver) : base(typeResolver) { } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Caching; namespace Codentia.Common.Data.Caching { /// <summary> /// Class encapsulating access to the current HttpCache. A Cache object will be created if no HttpContext is available. /// </summary> public static class DataCache { private static Cache _cache = null; private static HttpRuntime _httpRuntime = null; private static object _lockObject = new object(); private static bool _consoleOutput; private static List<string> _keyList = new List<string>(); /// <summary> /// Gets or sets a value indicating whether the console output flag. If enabled, this will cause diagnostic output to be written to Console. /// </summary> public static bool ConsoleOutputEnabled { get { bool value; lock (_lockObject) { value = _consoleOutput; } return _consoleOutput; } set { lock (_lockObject) { _consoleOutput = value; } } } /// <summary> /// Retrieve a value from a cached Dictionary (strongly typed). /// </summary> /// <typeparam name="TKey">Key Type</typeparam> /// <typeparam name="TValue">Value Type</typeparam> /// <param name="cacheKey">Identification Key identifying dictionary</param> /// <param name="id">Dictionary Key to retrieve</param> /// <returns>TValue of Dictionary Value</returns> public static TValue GetFromDictionary<TKey, TValue>(string cacheKey, TKey id) { EnsureCache(); TValue result = default(TValue); if (ContainsKey(cacheKey)) { Dictionary<TKey, TValue> index; lock (_lockObject) { index = (Dictionary<TKey, TValue>)_cache.Get(cacheKey); } if (index != null && index.ContainsKey(id)) { result = index[id]; WriteDiagnosticMessage(string.Format("HIT - GetFromDictionary({0}): {1}", cacheKey, id)); } } return result; } /// <summary> /// Checks if the given cached Dictionary contains the specified key /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="cacheKey">The cache key.</param> /// <param name="id">The id.</param> /// <returns>bool - true </returns> public static bool DictionaryContainsKey<TKey, TValue>(string cacheKey, TKey id) { bool result = false; EnsureCache(); if (ContainsKey(cacheKey)) { Dictionary<TKey, TValue> index; lock (_lockObject) { index = (Dictionary<TKey, TValue>)_cache.Get(cacheKey); } if (index != null && index.ContainsKey(id)) { result = true; WriteDiagnosticMessage(string.Format("HIT - DictionaryContainsKey({0}): {1}", cacheKey, id)); } } return result; } /// <summary> /// Add an entry to a cached dictionary. The dictionary will be created if non-existant. /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="cacheKey">Key identifying the Dictionary</param> /// <param name="id">Dictionary Key to insert/update</param> /// <param name="data">Dictionary value to be stored</param> public static void AddToDictionary<TKey, TValue>(string cacheKey, TKey id, TValue data) { EnsureCache(); lock (_lockObject) { Dictionary<TKey, TValue> index = (Dictionary<TKey, TValue>)_cache.Get(cacheKey); if (index == null) { index = new Dictionary<TKey, TValue>(); _keyList.Add(cacheKey); } if (index.ContainsKey(id)) { index.Remove(id); WriteDiagnosticMessage(string.Format("REMOVE - AddToDictionary({0}): {1}", cacheKey, id)); } index.Add(id, data); _cache.Add(cacheKey, index, null, DateTime.MaxValue, new TimeSpan(0, 20, 0), CacheItemPriority.Normal, new CacheItemRemovedCallback(DataCacheItemRemoved)); WriteDiagnosticMessage(string.Format("ADD - AddToDictionary({0}): {1}", cacheKey, id)); WriteDiagnosticMessage(string.Format("COUNT - AddToDictionary({0}): {1}", cacheKey, index.Keys.Count)); } } /// <summary> /// Remove an item from a cached dictionary. /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="cacheKey">Cache Key identifying the dictionary</param> /// <param name="id">Dictionary Id specifying the item to remove</param> public static void RemoveFromDictionary<TKey, TValue>(string cacheKey, TKey id) { EnsureCache(); lock (_lockObject) { Dictionary<TKey, TValue> index = (Dictionary<TKey, TValue>)_cache.Get(cacheKey); if (index != null && index.ContainsKey(id)) { index.Remove(id); _cache.Add(cacheKey, index, null, DateTime.MaxValue, new TimeSpan(0, 20, 0), CacheItemPriority.Normal, new CacheItemRemovedCallback(DataCacheItemRemoved)); WriteDiagnosticMessage(string.Format("DEL - RemoveFromDictionary({0}): {1}", cacheKey, id)); WriteDiagnosticMessage(string.Format("COUNT - AddToDictionary({0}): {1}", cacheKey, index.Keys.Count)); } } } /// <summary> /// Get a single object from the cache. /// </summary> /// <typeparam name="TValue">Value type</typeparam> /// <param name="cacheKey">Cache key identifying the object to be retrieved</param> /// <returns>TValue of Single Object</returns> public static TValue GetSingleObject<TValue>(string cacheKey) { EnsureCache(); TValue data = default(TValue); if (ContainsKey(cacheKey)) { lock (_lockObject) { data = (TValue)_cache.Get(cacheKey); if (data != null && !data.Equals(default(TValue))) { WriteDiagnosticMessage(string.Format("HIT - GetSingleObject({0})", cacheKey)); } } } return data; } /// <summary> /// Add a single object to the cache. /// </summary> /// <typeparam name="TValue">Value type</typeparam> /// <param name="cacheKey">Cache Key identifying the value being added</param> /// <param name="data">object to be added</param> public static void AddSingleObject<TValue>(string cacheKey, TValue data) { EnsureCache(); lock (_lockObject) { _cache.Remove(cacheKey); _keyList.Remove(cacheKey); _cache.Add(cacheKey, data, null, DateTime.MaxValue, new TimeSpan(0, 20, 0), CacheItemPriority.Normal, new CacheItemRemovedCallback(DataCacheItemRemoved)); _keyList.Add(cacheKey); WriteDiagnosticMessage(string.Format("ADD - AddSingleObject({0})", cacheKey)); } } /// <summary> /// Remove a specific item from the cache (either a whole entry or a single object) /// </summary> /// <param name="cacheKey">Cache Key to be removed</param> public static void Remove(string cacheKey) { EnsureCache(); lock (_lockObject) { _cache.Remove(cacheKey); WriteDiagnosticMessage(string.Format("DEL - Remove({0})", cacheKey)); } } /// <summary> /// Purge the entire Cache. /// </summary> public static void Purge() { EnsureCache(); lock (_lockObject) { WriteDiagnosticMessage("PURGE - Start"); IDictionaryEnumerator x = _cache.GetEnumerator(); while (x.MoveNext()) { _cache.Remove(Convert.ToString(x.Key)); WriteDiagnosticMessage(string.Format("PURGE - Remove({0})", x.Key)); } _keyList.Clear(); WriteDiagnosticMessage("PURGE - Finish"); } } /// <summary> /// Check if the cache currently contains a given key /// </summary> /// <param name="cacheKey">Cache Key to check for</param> /// <returns>bool - true if Key exists, otherwise false</returns> public static bool ContainsKey(string cacheKey) { EnsureCache(); bool contains = false; lock (_lockObject) { contains = _keyList.Contains(cacheKey); } return contains; } /// <summary> /// Ensure that a cache object exists, and is available for use. /// </summary> private static void EnsureCache() { lock (_lockObject) { if (_httpRuntime == null) { _httpRuntime = new HttpRuntime(); } if (_cache == null) { _cache = HttpRuntime.Cache; } } } /// <summary> /// Write out a Diagnostic message /// </summary> /// <param name="message">Messge to be written</param> private static void WriteDiagnosticMessage(string message) { if (_consoleOutput) { Console.Out.WriteLine(message); } } private static void DataCacheItemRemoved(string key, object value, CacheItemRemovedReason reason) { WriteDiagnosticMessage(string.Format("EXPIRED - {0} for reason {1}", key, reason.ToString())); lock (_lockObject) { _keyList.Remove(key); } WriteDiagnosticMessage(string.Format("REMOVED KEY - {0} for expiry reason {1}", key, reason.ToString())); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Skybrud.Social.Google.Analytics.Interfaces; namespace Skybrud.Social.Google.Analytics.Objects { public class AnalyticsMetric : IAnalyticsField { #region Readonly properties // ReSharper disable InconsistentNaming #region Visitor public static readonly AnalyticsMetric Visitors = new AnalyticsMetric("ga:visitors"); public static readonly AnalyticsMetric NewVisits = new AnalyticsMetric("ga:newVisits"); public static readonly AnalyticsMetric PercentNewVisits = new AnalyticsMetric("ga:percentNewVisits"); #endregion #region Session public static readonly AnalyticsMetric Visits = new AnalyticsMetric("ga:visits"); public static readonly AnalyticsMetric Bounces = new AnalyticsMetric("ga:bounces"); public static readonly AnalyticsMetric EntranceBounceRate = new AnalyticsMetric("ga:entranceBounceRate"); public static readonly AnalyticsMetric VisitBounceRate = new AnalyticsMetric("ga:visitBounceRate"); public static readonly AnalyticsMetric TimeOnSite = new AnalyticsMetric("ga:timeOnSite"); public static readonly AnalyticsMetric AvgTimeOnSite = new AnalyticsMetric("ga:avgTimeOnSite"); #endregion #region Traffic Sources public static readonly AnalyticsMetric OrganicSearches = new AnalyticsMetric("ga:organicSearches"); #endregion #region AdWords public static readonly AnalyticsMetric Impressions = new AnalyticsMetric("ga:impressions"); public static readonly AnalyticsMetric AdClicks = new AnalyticsMetric("ga:adClicks"); public static readonly AnalyticsMetric AdCost = new AnalyticsMetric("ga:adCost"); public static readonly AnalyticsMetric CPM = new AnalyticsMetric("ga:CPM"); public static readonly AnalyticsMetric CPC = new AnalyticsMetric("ga:CPC"); public static readonly AnalyticsMetric CTR = new AnalyticsMetric("ga:CTR"); public static readonly AnalyticsMetric CostPerTransaction = new AnalyticsMetric("ga:costPerTransaction"); public static readonly AnalyticsMetric CostPerGoalConversion = new AnalyticsMetric("ga:costPerGoalConversion"); public static readonly AnalyticsMetric CostPerConversion = new AnalyticsMetric("ga:costPerConversion"); public static readonly AnalyticsMetric RPC = new AnalyticsMetric("ga:RPC"); public static readonly AnalyticsMetric ROI = new AnalyticsMetric("ga:ROI"); public static readonly AnalyticsMetric Margin = new AnalyticsMetric("ga:margin"); #endregion #region Goal Conversions public static readonly AnalyticsMetric GoalXXStarts = new AnalyticsMetric("ga:goalXXStarts"); public static readonly AnalyticsMetric GoalStartsAll = new AnalyticsMetric("ga:goalStartsAll"); public static readonly AnalyticsMetric GoalXXCompletions = new AnalyticsMetric("ga:goalXXCompletions"); public static readonly AnalyticsMetric GoalCompletionsAll = new AnalyticsMetric("ga:goalCompletionsAll"); public static readonly AnalyticsMetric GoalXXValue = new AnalyticsMetric("ga:goalXXValue"); public static readonly AnalyticsMetric GoalValueAll = new AnalyticsMetric("ga:goalValueAll"); public static readonly AnalyticsMetric GoalValuePerVisit = new AnalyticsMetric("ga:goalValuePerVisit"); public static readonly AnalyticsMetric GoalXXConversionRate = new AnalyticsMetric("ga:goalXXConversionRate"); public static readonly AnalyticsMetric GoalConversionRateAll = new AnalyticsMetric("ga:goalConversionRateAll"); public static readonly AnalyticsMetric GoalXXAbandons = new AnalyticsMetric("ga:goalXXAbandons"); public static readonly AnalyticsMetric GoalAbandonsAll = new AnalyticsMetric("ga:goalAbandonsAll"); public static readonly AnalyticsMetric GoalXXAbandonRate = new AnalyticsMetric("ga:goalXXAbandonRate"); public static readonly AnalyticsMetric GoalAbandonRateAll = new AnalyticsMetric("ga:goalAbandonRateAll"); #endregion #region Social Activities public static readonly AnalyticsMetric SocialActivities = new AnalyticsMetric("ga:socialActivities"); #endregion #region Page Tracking public static readonly AnalyticsMetric Entrances = new AnalyticsMetric("ga:entrances"); public static readonly AnalyticsMetric EntranceRate = new AnalyticsMetric("ga:entranceRate"); public static readonly AnalyticsMetric Pageviews = new AnalyticsMetric("ga:pageviews"); public static readonly AnalyticsMetric PageviewsPerVisit = new AnalyticsMetric("ga:pageviewsPerVisit"); public static readonly AnalyticsMetric UniquePageviews = new AnalyticsMetric("ga:uniquePageviews"); public static readonly AnalyticsMetric PageValue = new AnalyticsMetric("ga:pageValue"); public static readonly AnalyticsMetric TimeOnPage = new AnalyticsMetric("ga:timeOnPage"); public static readonly AnalyticsMetric AvgTimeOnPage = new AnalyticsMetric("ga:avgTimeOnPage"); public static readonly AnalyticsMetric Exits = new AnalyticsMetric("ga:exits"); public static readonly AnalyticsMetric ExitRate = new AnalyticsMetric("ga:exitRate"); #endregion #region Internal Search public static readonly AnalyticsMetric SearchResultViews = new AnalyticsMetric("ga:searchResultViews"); public static readonly AnalyticsMetric SearchUniques = new AnalyticsMetric("ga:searchUniques"); public static readonly AnalyticsMetric AvgSearchResultViews = new AnalyticsMetric("ga:avgSearchResultViews"); public static readonly AnalyticsMetric SearchVisits = new AnalyticsMetric("ga:searchVisits"); public static readonly AnalyticsMetric PercentVisitsWithSearch = new AnalyticsMetric("ga:percentVisitsWithSearch"); public static readonly AnalyticsMetric SearchDepth = new AnalyticsMetric("ga:searchDepth"); public static readonly AnalyticsMetric AvgSearchDepth = new AnalyticsMetric("ga:avgSearchDepth"); public static readonly AnalyticsMetric SearchRefinements = new AnalyticsMetric("ga:searchRefinements"); public static readonly AnalyticsMetric PercentSearchRefinements = new AnalyticsMetric("ga:percentSearchRefinements"); public static readonly AnalyticsMetric SearchDuration = new AnalyticsMetric("ga:searchDuration"); public static readonly AnalyticsMetric AvgSearchDuration = new AnalyticsMetric("ga:avgSearchDuration"); public static readonly AnalyticsMetric SearchExits = new AnalyticsMetric("ga:searchExits"); public static readonly AnalyticsMetric SearchExitRate = new AnalyticsMetric("ga:searchExitRate"); public static readonly AnalyticsMetric SearchGoalXXConversionRate = new AnalyticsMetric("ga:searchGoalXXConversionRate"); public static readonly AnalyticsMetric SearchGoalConversionRateAll = new AnalyticsMetric("ga:searchGoalConversionRateAll"); public static readonly AnalyticsMetric GoalValueAllPerSearch = new AnalyticsMetric("ga:goalValueAllPerSearch"); #endregion #region Site Speed public static readonly AnalyticsMetric PageLoadTime = new AnalyticsMetric("ga:pageLoadTime"); public static readonly AnalyticsMetric PageLoadSample = new AnalyticsMetric("ga:pageLoadSample"); public static readonly AnalyticsMetric AvgPageLoadTime = new AnalyticsMetric("ga:avgPageLoadTime"); public static readonly AnalyticsMetric DomainLookupTime = new AnalyticsMetric("ga:domainLookupTime"); public static readonly AnalyticsMetric AvgDomainLookupTime = new AnalyticsMetric("ga:avgDomainLookupTime"); public static readonly AnalyticsMetric PageDownloadTime = new AnalyticsMetric("ga:pageDownloadTime"); public static readonly AnalyticsMetric AvgPageDownloadTime = new AnalyticsMetric("ga:avgPageDownloadTime"); public static readonly AnalyticsMetric RedirectionTime = new AnalyticsMetric("ga:redirectionTime"); public static readonly AnalyticsMetric AvgRedirectionTime = new AnalyticsMetric("ga:avgRedirectionTime"); public static readonly AnalyticsMetric ServerConnectionTime = new AnalyticsMetric("ga:serverConnectionTime"); public static readonly AnalyticsMetric AvgServerConnectionTime = new AnalyticsMetric("ga:avgServerConnectionTime"); public static readonly AnalyticsMetric ServerResponseTime = new AnalyticsMetric("ga:serverResponseTime"); public static readonly AnalyticsMetric AvgServerResponseTime = new AnalyticsMetric("ga:avgServerResponseTime"); public static readonly AnalyticsMetric SpeedMetricsSample = new AnalyticsMetric("ga:speedMetricsSample"); public static readonly AnalyticsMetric DomInteractiveTime = new AnalyticsMetric("ga:domInteractiveTime"); public static readonly AnalyticsMetric AvgDomInteractiveTime = new AnalyticsMetric("ga:avgDomInteractiveTime"); public static readonly AnalyticsMetric DomContentLoadedTime = new AnalyticsMetric("ga:domContentLoadedTime"); public static readonly AnalyticsMetric AvgDomContentLoadedTime = new AnalyticsMetric("ga:avgDomContentLoadedTime"); public static readonly AnalyticsMetric DomLatencyMetricsSample = new AnalyticsMetric("ga:domLatencyMetricsSample"); #endregion #region App Tracking public static readonly AnalyticsMetric Appviews = new AnalyticsMetric("ga:appviews"); public static readonly AnalyticsMetric UniqueAppviews = new AnalyticsMetric("ga:uniqueAppviews"); public static readonly AnalyticsMetric AppviewsPerVisit = new AnalyticsMetric("ga:appviewsPerVisit"); public static readonly AnalyticsMetric Screenviews = new AnalyticsMetric("ga:screenviews"); public static readonly AnalyticsMetric UniqueScreenviews = new AnalyticsMetric("ga:uniqueScreenviews"); public static readonly AnalyticsMetric ScreenviewsPerSession = new AnalyticsMetric("ga:screenviewsPerSession"); public static readonly AnalyticsMetric TimeOnScreen = new AnalyticsMetric("ga:timeOnScreen"); public static readonly AnalyticsMetric AvgScreenviewDuration = new AnalyticsMetric("ga:avgScreenviewDuration"); #endregion #region Event Tracking public static readonly AnalyticsMetric TotalEvents = new AnalyticsMetric("ga:totalEvents"); public static readonly AnalyticsMetric UniqueEvents = new AnalyticsMetric("ga:uniqueEvents"); public static readonly AnalyticsMetric EventValue = new AnalyticsMetric("ga:eventValue"); public static readonly AnalyticsMetric AvgEventValue = new AnalyticsMetric("ga:avgEventValue"); public static readonly AnalyticsMetric VisitsWithEvent = new AnalyticsMetric("ga:visitsWithEvent"); public static readonly AnalyticsMetric EventsPerVisitWithEvent = new AnalyticsMetric("ga:eventsPerVisitWithEvent"); #endregion #region Ecommerce public static readonly AnalyticsMetric Transactions = new AnalyticsMetric("ga:transactions"); public static readonly AnalyticsMetric TransactionsPerVisit = new AnalyticsMetric("ga:transactionsPerVisit"); public static readonly AnalyticsMetric TransactionRevenue = new AnalyticsMetric("ga:transactionRevenue"); public static readonly AnalyticsMetric RevenuePerTransaction = new AnalyticsMetric("ga:revenuePerTransaction"); public static readonly AnalyticsMetric TransactionRevenuePerVisit = new AnalyticsMetric("ga:transactionRevenuePerVisit"); public static readonly AnalyticsMetric TransactionShipping = new AnalyticsMetric("ga:transactionShipping"); public static readonly AnalyticsMetric TransactionTax = new AnalyticsMetric("ga:transactionTax"); public static readonly AnalyticsMetric TotalValue = new AnalyticsMetric("ga:totalValue"); public static readonly AnalyticsMetric ItemQuantity = new AnalyticsMetric("ga:itemQuantity"); public static readonly AnalyticsMetric UniquePurchases = new AnalyticsMetric("ga:uniquePurchases"); public static readonly AnalyticsMetric RevenuePerItem = new AnalyticsMetric("ga:revenuePerItem"); public static readonly AnalyticsMetric ItemRevenue = new AnalyticsMetric("ga:itemRevenue"); public static readonly AnalyticsMetric ItemsPerPurchase = new AnalyticsMetric("ga:itemsPerPurchase"); public static readonly AnalyticsMetric LocalItemRevenue = new AnalyticsMetric("ga:localItemRevenue"); public static readonly AnalyticsMetric LocalTransactionRevenue = new AnalyticsMetric("ga:localTransactionRevenue"); public static readonly AnalyticsMetric LocalTransactionTax = new AnalyticsMetric("ga:localTransactionTax"); public static readonly AnalyticsMetric LocalTransactionShipping = new AnalyticsMetric("ga:localTransactionShipping"); #endregion #region Social Interactions public static readonly AnalyticsMetric SocialInteractions = new AnalyticsMetric("ga:socialInteractions"); public static readonly AnalyticsMetric UniqueSocialInteractions = new AnalyticsMetric("ga:uniqueSocialInteractions"); public static readonly AnalyticsMetric SocialInteractionsPerVisit = new AnalyticsMetric("ga:socialInteractionsPerVisit"); #endregion #region User Timings public static readonly AnalyticsMetric UserTimingValue = new AnalyticsMetric("ga:userTimingValue"); public static readonly AnalyticsMetric UserTimingSample = new AnalyticsMetric("ga:userTimingSample"); public static readonly AnalyticsMetric AvgUserTimingValue = new AnalyticsMetric("ga:avgUserTimingValue"); #endregion #region Exception Tracking public static readonly AnalyticsMetric Exceptions = new AnalyticsMetric("ga:exceptions"); public static readonly AnalyticsMetric ExceptionsPerScreenview = new AnalyticsMetric("ga:exceptionsPerScreenview"); public static readonly AnalyticsMetric FatalExceptions = new AnalyticsMetric("ga:fatalExceptions"); public static readonly AnalyticsMetric FatalExceptionsPerScreenview = new AnalyticsMetric("ga:fatalExceptionsPerScreenview"); #endregion #region Custom Variables or Columns public static readonly AnalyticsMetric MetricXX = new AnalyticsMetric("ga:metricXX"); #endregion #region Realtime public static readonly AnalyticsMetric ActiveVisitors = new AnalyticsMetric("ga:activeVisitors"); #endregion // ReSharper restore InconsistentNaming #endregion #region Static properties public static AnalyticsMetric[] Values { get { return ( from property in typeof(AnalyticsMetric).GetFields(BindingFlags.Public | BindingFlags.Static) select (AnalyticsMetric) property.GetValue(null) ).ToArray(); } } #endregion #region Member properties /// <summary> /// The name of the dimension. /// </summary> public string Name { get; private set; } #endregion #region Constructor private AnalyticsMetric(string name) { Name = name; } #endregion #region Member methods /// <summary> /// Gets the name of the metric (eg. "ga:visits"). /// </summary> public override string ToString() { return Name; } #endregion #region Static methods /// <summary> /// Attempts to parse the specified string as a metric. The parsing is done against a list /// of known metrics. If the parsing fails, an exception will be thrown. /// </summary> /// <param name="str">The string to parse.</param> public static AnalyticsMetric Parse(string str) { AnalyticsMetric metric; if (TryParse(str, out metric)) return metric; throw new Exception("Invalid metric '" + str + "'"); } /// <summary> /// Attempts to parse the specified string as a metric. The parsing is done against a list /// of known metrics. The method will return TRUE if the parsing succeeds, otherwise FALSE. /// </summary> /// <param name="str">The string to parse.</param> /// <param name="metric">The parsed metric.</param> public static bool TryParse(string str, out AnalyticsMetric metric) { metric = Values.FirstOrDefault(temp => temp.Name == str); return metric != null; } #endregion #region Operator overloading public static implicit operator AnalyticsMetric(string name) { return Parse(name); } public static AnalyticsMetricCollection operator +(AnalyticsMetric left, AnalyticsMetric right) { return new AnalyticsMetricCollection(left, right); } #endregion } }
using System; using System.Drawing; using System.Drawing.Text; using System.Text; namespace ICSharpCode.TextEditor.Document { public class DefaultTextEditorProperties : ITextEditorProperties { private int tabIndent = 4; private int indentationSize = 4; private IndentStyle indentStyle = IndentStyle.Smart; private DocumentSelectionMode documentSelectionMode; private Encoding encoding = Encoding.UTF8; private BracketMatchingStyle bracketMatchingStyle = BracketMatchingStyle.After; private FontContainer fontContainer; private static Font DefaultFont; private bool allowCaretBeyondEOL; private bool caretLine; private bool showMatchingBracket = true; private bool showLineNumbers = true; private bool showSpaces; private bool showTabs; private bool showEOLMarker; private bool showInvalidLines; private bool isIconBarVisible; private bool enableFolding = true; private bool showHorizontalRuler; private bool showVerticalRuler = false; private bool convertTabsToSpaces; private TextRenderingHint textRenderingHint; private bool mouseWheelScrollDown = true; private bool mouseWheelTextZoom = true; private bool hideMouseCursor; private bool cutCopyWholeLine = true; private int verticalRulerRow = 80; private LineViewerStyle lineViewerStyle; private string lineTerminator = "\r\n"; private bool autoInsertCurlyBracket = true; private bool supportReadOnlySegments; public int TabIndent { get { return this.tabIndent; } set { this.tabIndent = value; } } public int IndentationSize { get { return this.indentationSize; } set { this.indentationSize = value; } } public IndentStyle IndentStyle { get { return this.indentStyle; } set { this.indentStyle = value; } } public bool CaretLine { get { return this.caretLine; } set { this.caretLine = value; } } public DocumentSelectionMode DocumentSelectionMode { get { return this.documentSelectionMode; } set { this.documentSelectionMode = value; } } public bool AllowCaretBeyondEOL { get { return this.allowCaretBeyondEOL; } set { this.allowCaretBeyondEOL = value; } } public bool ShowMatchingBracket { get { return this.showMatchingBracket; } set { this.showMatchingBracket = value; } } public bool ShowLineNumbers { get { return this.showLineNumbers; } set { this.showLineNumbers = value; } } public bool ShowSpaces { get { return this.showSpaces; } set { this.showSpaces = value; } } public bool ShowTabs { get { return this.showTabs; } set { this.showTabs = value; } } public bool ShowEOLMarker { get { return this.showEOLMarker; } set { this.showEOLMarker = value; } } public bool ShowInvalidLines { get { return this.showInvalidLines; } set { this.showInvalidLines = value; } } public bool IsIconBarVisible { get { return this.isIconBarVisible; } set { this.isIconBarVisible = value; } } public bool EnableFolding { get { return this.enableFolding; } set { this.enableFolding = value; } } public bool ShowHorizontalRuler { get { return this.showHorizontalRuler; } set { this.showHorizontalRuler = value; } } public bool ShowVerticalRuler { get { return this.showVerticalRuler; } set { this.showVerticalRuler = value; } } public bool ConvertTabsToSpaces { get { return this.convertTabsToSpaces; } set { this.convertTabsToSpaces = value; } } public TextRenderingHint TextRenderingHint { get { return this.textRenderingHint; } set { this.textRenderingHint = value; } } public bool MouseWheelScrollDown { get { return this.mouseWheelScrollDown; } set { this.mouseWheelScrollDown = value; } } public bool MouseWheelTextZoom { get { return this.mouseWheelTextZoom; } set { this.mouseWheelTextZoom = value; } } public bool HideMouseCursor { get { return this.hideMouseCursor; } set { this.hideMouseCursor = value; } } public bool CutCopyWholeLine { get { return this.cutCopyWholeLine; } set { this.cutCopyWholeLine = value; } } public Encoding Encoding { get { return this.encoding; } set { this.encoding = value; } } public int VerticalRulerRow { get { return this.verticalRulerRow; } set { this.verticalRulerRow = value; } } public LineViewerStyle LineViewerStyle { get { return this.lineViewerStyle; } set { this.lineViewerStyle = value; } } public string LineTerminator { get { return this.lineTerminator; } set { this.lineTerminator = value; } } public bool AutoInsertCurlyBracket { get { return this.autoInsertCurlyBracket; } set { this.autoInsertCurlyBracket = value; } } public Font Font { get { return this.fontContainer.DefaultFont; } set { this.fontContainer.DefaultFont = value; } } public FontContainer FontContainer { get { return this.fontContainer; } } public BracketMatchingStyle BracketMatchingStyle { get { return this.bracketMatchingStyle; } set { this.bracketMatchingStyle = value; } } public bool SupportReadOnlySegments { get { return this.supportReadOnlySegments; } set { this.supportReadOnlySegments = value; } } public DefaultTextEditorProperties() { if (DefaultTextEditorProperties.DefaultFont == null) { DefaultTextEditorProperties.DefaultFont = new Font("Courier New", 10f); } this.fontContainer = new FontContainer(DefaultTextEditorProperties.DefaultFont); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; 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 Mstc.Web.Api.Areas.HelpPage.ModelDescriptions; using Mstc.Web.Api.Areas.HelpPage.Models; namespace Mstc.Web.Api.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; } if (complexTypeDescription != null) { 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 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); } } } }
namespace Oculus.Platform.Samples.NetChat { using UnityEngine; using UnityEngine.UI; using System; using System.IO; using System.Collections.Generic; using Oculus.Platform; using Oculus.Platform.Models; enum states { NOT_INIT = 0, IDLE, REQUEST_FIND, FINDING_ROOM, REQUEST_CREATE, REQUEST_JOIN, REQUEST_LEAVE, IN_EMPTY_ROOM, IN_FULL_ROOM } // Pools are defined on the Oculus developer portal // // For this test we have a pool created with the pool key set as 'filter_pool' // Mode is set to 'Room' // Skill Pool is set to 'None' // We are not considering Round Trip Time // The following Data Settings are set: // key: map_name, Type: STRING, String options: Small_Map, Big_Map, Really_Big_Map // key: game_type, Type: STRING, String Options: deathmatch, CTF // // We also have the following two queries defined: // Query Key: map // Template: Set (String) // Key: map_name // Wildcards: map_param_1, map_param_2 // // Query Key: game_type // Template: Set (String) // Key: game_type_name // Wildcards: game_type_param // // For this test we have a pool created with the pool key set as 'bout_pool' // Mode is set to 'Bout' // Skill Pool is set to 'None' // We are not considering Round Trip Time // No Data Settings are set: // public static class Constants { public const int BUFFER_SIZE = 512; public const string BOUT_POOL = "bout_pool"; public const string FILTER_POOL = "filter_pool"; } public class chatPacket { public int packetID { get; set; } public string textString { get; set; } public byte[] Serialize() { using (MemoryStream m = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(m)) { // Limit our string to BUFFER_SIZE if (textString.Length > Constants.BUFFER_SIZE) { textString = textString.Substring(0, Constants.BUFFER_SIZE-1); } writer.Write(packetID); writer.Write(textString.ToCharArray()); writer.Write('\0'); } return m.ToArray(); } } public static chatPacket Deserialize(byte[] data) { chatPacket result = new chatPacket(); using (MemoryStream m = new MemoryStream(data)) { using (BinaryReader reader = new BinaryReader(m)) { result.packetID = reader.ReadInt32(); result.textString = System.Text.Encoding.Default.GetString(reader.ReadBytes(Constants.BUFFER_SIZE)); } } return result; } } public class DataEntry : MonoBehaviour { public Text dataOutput; states currentState; User localUser; User remoteUser; Room currentRoom; int lastPacketID; bool ratedMatchStarted; // Use this for initialization void Start () { currentState = states.NOT_INIT; localUser = null; remoteUser = null; currentRoom = null; lastPacketID = 0; ratedMatchStarted = false; Core.Initialize(); // Setup our room update handler Rooms.SetUpdateNotificationCallback(updateRoom); // Setup our match found handler Matchmaking.SetMatchFoundNotificationCallback(foundMatch); checkEntitlement(); } // Update is called once per frame void Update() { string currentText = GetComponent<InputField>().text; if (Input.GetKey(KeyCode.Return)) { if (currentText != "") { SubmitCommand(currentText); } GetComponent<InputField>().text = ""; } processNetPackets(); // Handle all messages being returned Request.RunCallbacks(); } void SubmitCommand(string command) { string[] commandParams = command.Split('!'); if (commandParams.Length > 0) { switch (commandParams[0]) { case "c": requestCreateRoom(); break; case "d": requestCreateFilterRoom(); break; case "f": requestFindMatch(); break; case "g": requestFindRoom(); break; case "i": requestFindFilteredRoom(); break; case "s": if (commandParams.Length > 1) { sendChat(commandParams[1]); } break; case "l": requestLeaveRoom(); break; case "1": requestStartRatedMatch(); break; case "2": requestReportResults(); break; default: printOutputLine("Invalid Command"); break; } } } void printOutputLine(String newLine) { dataOutput.text = "> " + newLine + System.Environment.NewLine + dataOutput.text; } void checkEntitlement() { Entitlements.IsUserEntitledToApplication().OnComplete(getEntitlementCallback); } void getEntitlementCallback(Message msg) { if (!msg.IsError) { printOutputLine("You are entitled to use this app."); Users.GetLoggedInUser().OnComplete(init); } else { printOutputLine("You are NOT entitled to use this app."); } } void init(Message<User> msg) { if (!msg.IsError) { User user = msg.Data; localUser = user; currentState = states.IDLE; } else { printOutputLine("Received get current user error"); Error error = msg.GetError(); printOutputLine("Error: " + error.Message); // Retry getting the current user Users.GetLoggedInUser().OnComplete(init); currentState = states.NOT_INIT; } } void requestCreateRoom() { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID."); break; case states.IDLE: printOutputLine("Trying to create a matchmaking room"); Matchmaking.CreateAndEnqueueRoom(Constants.FILTER_POOL, 8, true, null).OnComplete(createRoomResponse); currentState = states.REQUEST_CREATE; break; case states.REQUEST_FIND: printOutputLine("You have already made a request to find a room. Please wait for that request to complete."); break; case states.FINDING_ROOM: printOutputLine("You have already currently looking for a room. Please wait for the match to be made."); break; case states.REQUEST_JOIN: printOutputLine("We are currently trying to join a room. Please wait to see if we can join it."); break; case states.REQUEST_LEAVE: printOutputLine("We are currently trying to leave a room. Please wait to see if we can leave it."); break; case states.REQUEST_CREATE: printOutputLine("You have already requested a matchmaking room to be created. Please wait for the room to be made."); break; case states.IN_EMPTY_ROOM: printOutputLine("You have already in a matchmaking room. Please wait for an opponent to join."); break; case states.IN_FULL_ROOM: printOutputLine("You have already in a match."); break; default: printOutputLine("You have hit an unknown state."); break; } } void createRoomResponse(Message<MatchmakingEnqueueResultAndRoom> msg) { if (!msg.IsError) { printOutputLine("Received create matchmaking room success"); Room room = msg.Data.Room; currentRoom = room; printOutputLine("RoomID: " + room.ID.ToString()); currentState = states.IN_EMPTY_ROOM; } else { printOutputLine("Received create matchmaking room Error"); Error error = msg.GetError(); printOutputLine("Error: " + error.Message); printOutputLine("You can only create a matchmaking room for pools of mode Room. Make sure you have an appropriate pool setup on the Developer portal.\n"); currentState = states.IDLE; } } void requestCreateFilterRoom() { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID.\n"); break; case states.IDLE: printOutputLine("Trying to create a matchmaking room"); // We're going to create a room that has the following values set: // game_type_name = "CTF" // map_name = "Really_Big_Map" // Matchmaking.CustomQuery roomCustomQuery = new Matchmaking.CustomQuery(); roomCustomQuery.criteria = null; roomCustomQuery.data = new Dictionary<string, object>(); roomCustomQuery.data.Add("game_type_name", "CTF"); roomCustomQuery.data.Add("map_name", "Really_Big_Map"); Matchmaking.CreateAndEnqueueRoom(Constants.FILTER_POOL, 8, true, roomCustomQuery).OnComplete(createRoomResponse); currentState = states.REQUEST_CREATE; break; case states.REQUEST_FIND: printOutputLine("You have already made a request to find a room. Please wait for that request to complete.\n"); break; case states.FINDING_ROOM: printOutputLine("You have already currently looking for a room. Please wait for the match to be made.\n"); break; case states.REQUEST_JOIN: printOutputLine("We are currently trying to join a room. Please wait to see if we can join it.\n"); break; case states.REQUEST_LEAVE: printOutputLine("We are currently trying to leave a room. Please wait to see if we can leave it.\n"); break; case states.REQUEST_CREATE: printOutputLine("You have already requested a matchmaking room to be created. Please wait for the room to be made.\n"); break; case states.IN_EMPTY_ROOM: printOutputLine("You have already in a matchmaking room. Please wait for an opponent to join.\n"); break; case states.IN_FULL_ROOM: printOutputLine("You have already in a match.\n"); break; default: printOutputLine("You have hit an unknown state.\n"); break; } } void requestFindRoom() { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID."); break; case states.IDLE: printOutputLine("\nTrying to find a matchmaking room\n"); Matchmaking.Enqueue(Constants.FILTER_POOL, null).OnComplete(searchingStarted); currentState = states.REQUEST_FIND; break; case states.REQUEST_FIND: printOutputLine("You have already made a request to find a room. Please wait for that request to complete."); break; case states.FINDING_ROOM: printOutputLine("You have already currently looking for a room. Please wait for the match to be made."); break; case states.REQUEST_JOIN: printOutputLine("We are currently trying to join a room. Please wait to see if we can join it."); break; case states.REQUEST_LEAVE: printOutputLine("We are currently trying to leave a room. Please wait to see if we can leave it."); break; case states.REQUEST_CREATE: printOutputLine("You have already requested a matchmaking room to be created. Please wait for the room to be made."); break; case states.IN_EMPTY_ROOM: printOutputLine("You have already in a matchmaking room. Please wait for an opponent to join."); break; case states.IN_FULL_ROOM: printOutputLine("You have already in a match."); break; default: printOutputLine("You have hit an unknown state."); break; } } void requestFindFilteredRoom() { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID."); break; case states.IDLE: printOutputLine("Trying to find a matchmaking room"); // Our search filter criterion // // We're filtering using two different queries setup on the developer portal // // map - query to filter by map. The query allows you to filter with up to two different maps using keys called 'map_1' and 'map_2' // game_type - query to filter by game type. The query allows you to filter with up to two different game types using keys called 'type_1' and 'type_2' // // In the example below we are filtering for matches that are of type CTF and on either Big_Map or Really_Big_Map. // Matchmaking.CustomQuery roomCustomQuery = new Matchmaking.CustomQuery(); Matchmaking.CustomQuery.Criterion[] queries = new Matchmaking.CustomQuery.Criterion[2]; queries[0].key = "map"; queries[0].importance = MatchmakingCriterionImportance.Required; queries[0].parameters = new Dictionary<string, object>(); queries[0].parameters.Add("map_param_1","Really_Big_Map"); queries[0].parameters.Add("map_param_2", "Big_Map"); queries[1].key = "game_type"; queries[1].importance = MatchmakingCriterionImportance.Required; queries[1].parameters = new Dictionary<string, object>(); queries[1].parameters.Add("game_type_param", "CTF"); roomCustomQuery.criteria = queries; roomCustomQuery.data = null; Matchmaking.Enqueue(Constants.FILTER_POOL, roomCustomQuery); currentState = states.REQUEST_FIND; break; case states.REQUEST_FIND: printOutputLine("You have already made a request to find a room. Please wait for that request to complete."); break; case states.FINDING_ROOM: printOutputLine("You have already currently looking for a room. Please wait for the match to be made."); break; case states.REQUEST_JOIN: printOutputLine("We are currently trying to join a room. Please wait to see if we can join it."); break; case states.REQUEST_LEAVE: printOutputLine("We are currently trying to leave a room. Please wait to see if we can leave it."); break; case states.REQUEST_CREATE: printOutputLine("You have already requested a matchmaking room to be created. Please wait for the room to be made."); break; case states.IN_EMPTY_ROOM: printOutputLine("You have already in a matchmaking room. Please wait for an opponent to join."); break; case states.IN_FULL_ROOM: printOutputLine("You have already in a match."); break; default: printOutputLine("You have hit an unknown state."); break; } } void foundMatch(Message<Room> msg) { if (!msg.IsError) { printOutputLine("Received find match success. We are now going to request to join the room."); Room room = msg.Data; Rooms.Join(room.ID, true).OnComplete(joinRoomResponse); currentState = states.REQUEST_JOIN; } else { printOutputLine("Received find match error"); Error error = msg.GetError(); printOutputLine("Error: " + error.Message); currentState = states.IDLE; } } void joinRoomResponse(Message<Room> msg) { if (!msg.IsError) { printOutputLine("Received join room success."); currentRoom = msg.Data; currentState = states.IN_EMPTY_ROOM; // Try to pull out remote user's ID if they have already joined if (currentRoom.UsersOptional != null) { foreach (User element in currentRoom.UsersOptional) { if (element.ID != localUser.ID) { remoteUser = element; currentState = states.IN_FULL_ROOM; } } } } else { printOutputLine("Received join room error"); printOutputLine("It's possible the room filled up before you could join it."); Error error = msg.GetError(); printOutputLine("Error: " + error.Message); currentState = states.IDLE; } } void requestFindMatch() { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID."); break; case states.IDLE: printOutputLine("Trying to find a matchmaking room"); Matchmaking.Enqueue(Constants.BOUT_POOL, null).OnComplete(searchingStarted); currentState = states.REQUEST_FIND; break; case states.REQUEST_FIND: printOutputLine("You have already made a request to find a room. Please wait for that request to complete."); break; case states.FINDING_ROOM: printOutputLine("You have already currently looking for a room. Please wait for the match to be made."); break; case states.REQUEST_JOIN: printOutputLine("We are currently trying to join a room. Please wait to see if we can join it."); break; case states.REQUEST_LEAVE: printOutputLine("We are currently trying to leave a room. Please wait to see if we can leave it."); break; case states.REQUEST_CREATE: printOutputLine("You have already requested a matchmaking room to be created. Please wait for the room to be made."); break; case states.IN_EMPTY_ROOM: printOutputLine("You have already in a matchmaking room. Please wait for an opponent to join."); break; case states.IN_FULL_ROOM: printOutputLine("You have already in a match."); break; default: printOutputLine("You have hit an unknown state."); break; } } void searchingStarted(Message msg) { if (!msg.IsError) { printOutputLine("Searching for a match successfully started"); currentState = states.REQUEST_FIND; } else { printOutputLine("Searching for a match error"); Error error = msg.GetError(); printOutputLine("Error: " + error.Message); } } void updateRoom(Message<Room> msg) { if (!msg.IsError) { printOutputLine("Received room update notification"); Room room = msg.Data; if (currentState == states.IN_EMPTY_ROOM) { // Check to see if this update is another user joining if (room.UsersOptional != null) { foreach (User element in room.UsersOptional) { if (element.ID != localUser.ID) { remoteUser = element; currentState = states.IN_FULL_ROOM; } } } } else { // Check to see if this update is another user leaving if (room.UsersOptional != null && room.UsersOptional.Count == 1) { printOutputLine("User ID: " + remoteUser.ID.ToString() + "has left"); remoteUser = null; currentState = states.IN_EMPTY_ROOM; } } } else { printOutputLine("Received room update error"); Error error = msg.GetError(); printOutputLine("Error: " + error.Message); } } void sendChat(string chatMessage) { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID."); break; case states.IDLE: case states.REQUEST_FIND: case states.FINDING_ROOM: case states.REQUEST_JOIN: case states.REQUEST_CREATE: case states.REQUEST_LEAVE: case states.IN_EMPTY_ROOM: printOutputLine("You need to be in a room with another player to send a message."); break; case states.IN_FULL_ROOM: { chatPacket newMessage = new chatPacket(); // Create a packet to send with the packet ID and string payload lastPacketID++; newMessage.packetID = lastPacketID; newMessage.textString = chatMessage; Oculus.Platform.Net.SendPacket(remoteUser.ID, newMessage.Serialize(), SendPolicy.Reliable); } break; default: printOutputLine("You have hit an unknown state."); break; } } void processNetPackets() { Packet incomingPacket = Net.ReadPacket(); while (incomingPacket != null) { byte[] rawBits = new byte[incomingPacket.Size]; incomingPacket.ReadBytes(rawBits); chatPacket newMessage = chatPacket.Deserialize(rawBits); printOutputLine("Chat Text: " + newMessage.textString.ToString()); printOutputLine("Received Packet from UserID: " + incomingPacket.SenderID.ToString()); printOutputLine("Received Packet ID: " + newMessage.packetID.ToString()); // Look to see if there's another packet waiting incomingPacket = Net.ReadPacket(); } } void requestLeaveRoom() { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID."); break; case states.IDLE: case states.REQUEST_FIND: case states.FINDING_ROOM: case states.REQUEST_JOIN: case states.REQUEST_CREATE: printOutputLine("You are currently not in a room to leave."); break; case states.REQUEST_LEAVE: printOutputLine("We are currently trying to leave a room. Please wait to see if we can leave it."); break; case states.IN_EMPTY_ROOM: case states.IN_FULL_ROOM: printOutputLine("Trying to leave room."); Rooms.Leave(currentRoom.ID).OnComplete(leaveRoomResponse); break; default: printOutputLine("You have hit an unknown state."); break; } } void leaveRoomResponse(Message<Room> msg) { if (!msg.IsError) { printOutputLine("We were able to leave the room"); currentRoom = null; remoteUser = null; currentState = states.IDLE; } else { printOutputLine("Leave room error"); Error error = msg.GetError(); printOutputLine("Error: " + error.Message); } } void requestStartRatedMatch() { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID."); break; case states.IDLE: case states.REQUEST_FIND: case states.FINDING_ROOM: case states.REQUEST_JOIN: case states.REQUEST_CREATE: case states.REQUEST_LEAVE: case states.IN_EMPTY_ROOM: printOutputLine("You need to be in a room with another player to start a rated match."); break; case states.IN_FULL_ROOM: printOutputLine("Trying to start a rated match. This call should be made once a rated match begins so we will be able to submit results after the game is done."); Matchmaking.StartMatch(currentRoom.ID).OnComplete(startRatedMatchResponse); break; default: printOutputLine("You have hit an unknown state."); break; } } void startRatedMatchResponse(Message msg) { if(!msg.IsError) { printOutputLine("Started a rated match"); ratedMatchStarted = true; } else { Error error = msg.GetError(); printOutputLine("Received starting rated match failure: " + error.Message); printOutputLine("Your matchmaking pool needs to have a skill pool associated with it to play rated matches"); } } void requestReportResults() { switch (currentState) { case states.NOT_INIT: printOutputLine("The app has not initialized properly and we don't know your userID."); break; case states.IDLE: case states.REQUEST_FIND: case states.FINDING_ROOM: case states.REQUEST_JOIN: case states.REQUEST_CREATE: case states.REQUEST_LEAVE: printOutputLine("You need to be in a room with another player to report results on a rated match."); break; case states.IN_EMPTY_ROOM: case states.IN_FULL_ROOM: if (ratedMatchStarted) { printOutputLine("Submitting rated match results."); Dictionary <string, int> results = new Dictionary<string, int>(); results.Add(localUser.ID.ToString(), 1); results.Add(remoteUser.ID.ToString(), 2); Matchmaking.ReportResultsInsecure(currentRoom.ID, results).OnComplete(reportResultsResponse); } else { printOutputLine("You can't report results unless you've already started a rated match"); } break; default: printOutputLine("You have hit an unknown state."); break; } } void reportResultsResponse(Message msg) { if (!msg.IsError) { printOutputLine("Rated match results reported. Now attempting to leave room."); ratedMatchStarted = false; requestLeaveRoom(); } else { Error error = msg.GetError(); printOutputLine("Received reporting rated match failure: " + error.Message); } } } }
/* * 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.Xml; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using log4net; using OpenSim.Framework; namespace OpenSim.Framework.Console { public class Commands : ICommands { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Encapsulates a command that can be invoked from the console /// </summary> private class CommandInfo { /// <value> /// The module from which this command comes /// </value> public string module; /// <value> /// Whether the module is shared /// </value> public bool shared; /// <value> /// Very short BNF description /// </value> public string help_text; /// <value> /// Longer one line help text /// </value> public string long_help; /// <value> /// Full descriptive help for this command /// </value> public string descriptive_help; /// <value> /// The method to invoke for this command /// </value> public List<CommandDelegate> fn; } public const string GeneralHelpText = "To enter an argument that contains spaces, surround the argument with double quotes.\nFor example, show object name \"My long object name\"\n"; public const string ItemHelpText = @"For more information, type 'help all' to get a list of all commands, or type help <item>' where <item> is one of the following:"; /// <value> /// Commands organized by keyword in a tree /// </value> private Dictionary<string, object> tree = new Dictionary<string, object>(); /// <summary> /// Commands organized by module /// </summary> private Dictionary<string, List<CommandInfo>> m_modulesCommands = new Dictionary<string, List<CommandInfo>>(); /// <summary> /// Get help for the given help string /// </summary> /// <param name="helpParts">Parsed parts of the help string. If empty then general help is returned.</param> /// <returns></returns> public List<string> GetHelp(string[] cmd) { List<string> help = new List<string>(); List<string> helpParts = new List<string>(cmd); // Remove initial help keyword helpParts.RemoveAt(0); help.Add(""); // Will become a newline. // General help if (helpParts.Count == 0) { help.Add(GeneralHelpText); help.Add(ItemHelpText); help.AddRange(CollectModulesHelp(tree)); } else if (helpParts.Count == 1 && helpParts[0] == "all") { help.AddRange(CollectAllCommandsHelp()); } else { help.AddRange(CollectHelp(helpParts)); } help.Add(""); // Will become a newline. return help; } /// <summary> /// Collects the help from all commands and return in alphabetical order. /// </summary> /// <returns></returns> private List<string> CollectAllCommandsHelp() { List<string> help = new List<string>(); lock (m_modulesCommands) { foreach (List<CommandInfo> commands in m_modulesCommands.Values) { var ourHelpText = commands.ConvertAll(c => string.Format("{0} - {1}", c.help_text, c.long_help)); help.AddRange(ourHelpText); } } help.Sort(); return help; } /// <summary> /// See if we can find the requested command in order to display longer help /// </summary> /// <param name="helpParts"></param> /// <returns></returns> private List<string> CollectHelp(List<string> helpParts) { string originalHelpRequest = string.Join(" ", helpParts.ToArray()); List<string> help = new List<string>(); // Check modules first to see if we just need to display a list of those commands if (TryCollectModuleHelp(originalHelpRequest, help)) { help.Insert(0, ItemHelpText); return help; } Dictionary<string, object> dict = tree; while (helpParts.Count > 0) { string helpPart = helpParts[0]; if (!dict.ContainsKey(helpPart)) break; //m_log.Debug("Found {0}", helpParts[0]); if (dict[helpPart] is Dictionary<string, Object>) dict = (Dictionary<string, object>)dict[helpPart]; helpParts.RemoveAt(0); } // There was a command for the given help string if (dict.ContainsKey(String.Empty)) { CommandInfo commandInfo = (CommandInfo)dict[String.Empty]; help.Add(commandInfo.help_text); help.Add(commandInfo.long_help); string descriptiveHelp = commandInfo.descriptive_help; // If we do have some descriptive help then insert a spacing line before for readability. if (descriptiveHelp != string.Empty) help.Add(string.Empty); help.Add(commandInfo.descriptive_help); } else { help.Add(string.Format("No help is available for {0}", originalHelpRequest)); } return help; } /// <summary> /// Try to collect help for the given module if that module exists. /// </summary> /// <param name="moduleName"></param> /// <param name="helpText">/param> /// <returns>true if there was the module existed, false otherwise.</returns> private bool TryCollectModuleHelp(string moduleName, List<string> helpText) { lock (m_modulesCommands) { foreach (string key in m_modulesCommands.Keys) { // Allow topic help requests to succeed whether they are upper or lowercase. if (moduleName.ToLower() == key.ToLower()) { List<CommandInfo> commands = m_modulesCommands[key]; var ourHelpText = commands.ConvertAll(c => string.Format("{0} - {1}", c.help_text, c.long_help)); ourHelpText.Sort(); helpText.AddRange(ourHelpText); return true; } } return false; } } private List<string> CollectModulesHelp(Dictionary<string, object> dict) { lock (m_modulesCommands) { List<string> helpText = new List<string>(m_modulesCommands.Keys); helpText.Sort(); return helpText; } } // private List<string> CollectHelp(Dictionary<string, object> dict) // { // List<string> result = new List<string>(); // // foreach (KeyValuePair<string, object> kvp in dict) // { // if (kvp.Value is Dictionary<string, Object>) // { // result.AddRange(CollectHelp((Dictionary<string, Object>)kvp.Value)); // } // else // { // if (((CommandInfo)kvp.Value).long_help != String.Empty) // result.Add(((CommandInfo)kvp.Value).help_text+" - "+ // ((CommandInfo)kvp.Value).long_help); // } // } // return result; // } /// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="module"></param> /// <param name="command"></param> /// <param name="help"></param> /// <param name="longhelp"></param> /// <param name="fn"></param> public void AddCommand(string module, bool shared, string command, string help, string longhelp, CommandDelegate fn) { AddCommand(module, shared, command, help, longhelp, String.Empty, fn); } /// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="module"></param> /// <param name="command"></param> /// <param name="help"></param> /// <param name="longhelp"></param> /// <param name="descriptivehelp"></param> /// <param name="fn"></param> public void AddCommand(string module, bool shared, string command, string help, string longhelp, string descriptivehelp, CommandDelegate fn) { string[] parts = Parser.Parse(command); Dictionary<string, Object> current = tree; foreach (string part in parts) { if (current.ContainsKey(part)) { if (current[part] is Dictionary<string, Object>) current = (Dictionary<string, Object>)current[part]; else return; } else { current[part] = new Dictionary<string, Object>(); current = (Dictionary<string, Object>)current[part]; } } CommandInfo info; if (current.ContainsKey(String.Empty)) { info = (CommandInfo)current[String.Empty]; if (!info.shared && !info.fn.Contains(fn)) info.fn.Add(fn); return; } info = new CommandInfo(); info.module = module; info.shared = shared; info.help_text = help; info.long_help = longhelp; info.descriptive_help = descriptivehelp; info.fn = new List<CommandDelegate>(); info.fn.Add(fn); current[String.Empty] = info; // Now add command to modules dictionary lock (m_modulesCommands) { List<CommandInfo> commands; if (m_modulesCommands.ContainsKey(module)) { commands = m_modulesCommands[module]; } else { commands = new List<CommandInfo>(); m_modulesCommands[module] = commands; } // m_log.DebugFormat("[COMMAND CONSOLE]: Adding to category {0} command {1}", module, command); commands.Add(info); } } public string[] FindNextOption(string[] cmd, bool term) { Dictionary<string, object> current = tree; int remaining = cmd.Length; foreach (string s in cmd) { remaining--; List<string> found = new List<string>(); foreach (string opt in current.Keys) { if (remaining > 0 && opt == s) { found.Clear(); found.Add(opt); break; } if (opt.StartsWith(s)) { found.Add(opt); } } if (found.Count == 1 && (remaining != 0 || term)) { current = (Dictionary<string, object>)current[found[0]]; } else if (found.Count > 0) { return found.ToArray(); } else { break; // return new string[] {"<cr>"}; } } if (current.Count > 1) { List<string> choices = new List<string>(); bool addcr = false; foreach (string s in current.Keys) { if (s == String.Empty) { CommandInfo ci = (CommandInfo)current[String.Empty]; if (ci.fn.Count != 0) addcr = true; } else choices.Add(s); } if (addcr) choices.Add("<cr>"); return choices.ToArray(); } if (current.ContainsKey(String.Empty)) return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text}; return new string[] { new List<string>(current.Keys)[0] }; } private CommandInfo ResolveCommand(string[] cmd, out string[] result) { result = cmd; int index = -1; Dictionary<string, object> current = tree; foreach (string s in cmd) { index++; List<string> found = new List<string>(); foreach (string opt in current.Keys) { if (opt == s) { found.Clear(); found.Add(opt); break; } if (opt.StartsWith(s)) { found.Add(opt); } } if (found.Count == 1) { result[index] = found[0]; current = (Dictionary<string, object>)current[found[0]]; } else if (found.Count > 0) { return null; } else { break; } } if (current.ContainsKey(String.Empty)) return (CommandInfo)current[String.Empty]; return null; } public bool HasCommand(string command) { string[] result; return ResolveCommand(Parser.Parse(command), out result) != null; } public string[] Resolve(string[] cmd) { string[] result; CommandInfo ci = ResolveCommand(cmd, out result); if (ci == null) return new string[0]; if (ci.fn.Count == 0) return new string[0]; foreach (CommandDelegate fn in ci.fn) { if (fn != null) fn(ci.module, result); else return new string[0]; } return result; } public XmlElement GetXml(XmlDocument doc) { CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty]; ((Dictionary<string, object>)tree["help"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["help"]).Count == 0) tree.Remove("help"); CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty]; ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["quit"]).Count == 0) tree.Remove("quit"); XmlElement root = doc.CreateElement("", "HelpTree", ""); ProcessTreeLevel(tree, root, doc); if (!tree.ContainsKey("help")) tree["help"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["help"])[String.Empty] = help; if (!tree.ContainsKey("quit")) tree["quit"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit; return root; } private void ProcessTreeLevel(Dictionary<string, object> level, XmlElement xml, XmlDocument doc) { foreach (KeyValuePair<string, object> kvp in level) { if (kvp.Value is Dictionary<string, Object>) { XmlElement next = doc.CreateElement("", "Level", ""); next.SetAttribute("Name", kvp.Key); xml.AppendChild(next); ProcessTreeLevel((Dictionary<string, object>)kvp.Value, next, doc); } else { CommandInfo c = (CommandInfo)kvp.Value; XmlElement cmd = doc.CreateElement("", "Command", ""); XmlElement e; e = doc.CreateElement("", "Module", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.module)); e = doc.CreateElement("", "Shared", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.shared.ToString())); e = doc.CreateElement("", "HelpText", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.help_text)); e = doc.CreateElement("", "LongHelp", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.long_help)); e = doc.CreateElement("", "Description", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.descriptive_help)); xml.AppendChild(cmd); } } } public void FromXml(XmlElement root, CommandDelegate fn) { CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty]; ((Dictionary<string, object>)tree["help"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["help"]).Count == 0) tree.Remove("help"); CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty]; ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["quit"]).Count == 0) tree.Remove("quit"); tree.Clear(); ReadTreeLevel(tree, root, fn); if (!tree.ContainsKey("help")) tree["help"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["help"])[String.Empty] = help; if (!tree.ContainsKey("quit")) tree["quit"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit; } private void ReadTreeLevel(Dictionary<string, object> level, XmlNode node, CommandDelegate fn) { Dictionary<string, object> next; string name; XmlNodeList nodeL = node.ChildNodes; XmlNodeList cmdL; CommandInfo c; foreach (XmlNode part in nodeL) { switch (part.Name) { case "Level": name = ((XmlElement)part).GetAttribute("Name"); next = new Dictionary<string, object>(); level[name] = next; ReadTreeLevel(next, part, fn); break; case "Command": cmdL = part.ChildNodes; c = new CommandInfo(); foreach (XmlNode cmdPart in cmdL) { switch (cmdPart.Name) { case "Module": c.module = cmdPart.InnerText; break; case "Shared": c.shared = Convert.ToBoolean(cmdPart.InnerText); break; case "HelpText": c.help_text = cmdPart.InnerText; break; case "LongHelp": c.long_help = cmdPart.InnerText; break; case "Description": c.descriptive_help = cmdPart.InnerText; break; } } c.fn = new List<CommandDelegate>(); c.fn.Add(fn); level[String.Empty] = c; break; } } } } public class Parser { // If an unquoted portion ends with an element matching this regex // and the next element contains a space, then we have stripped // embedded quotes that should not have been stripped private static Regex optionRegex = new Regex("^--[a-zA-Z0-9-]+=$"); public static string[] Parse(string text) { List<string> result = new List<string>(); int index; string[] unquoted = text.Split(new char[] {'"'}); for (index = 0 ; index < unquoted.Length ; index++) { if (index % 2 == 0) { string[] words = unquoted[index].Split(new char[] {' '}); bool option = false; foreach (string w in words) { if (w != String.Empty) { if (optionRegex.Match(w) == Match.Empty) option = false; else option = true; result.Add(w); } } // The last item matched the regex, put the quotes back if (option) { // If the line ended with it, don't do anything if (index < (unquoted.Length - 1)) { // Get and remove the option name string optionText = result[result.Count - 1]; result.RemoveAt(result.Count - 1); // Add the quoted value back optionText += "\"" + unquoted[index + 1] + "\""; // Push the result into our return array result.Add(optionText); // Skip the already used value index++; } } } else { result.Add(unquoted[index]); } } return result.ToArray(); } } /// <summary> /// A console that processes commands internally /// </summary> public class CommandConsole : ConsoleBase, ICommandConsole { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event OnOutputDelegate OnOutput; public ICommands Commands { get; private set; } public CommandConsole(string defaultPrompt) : base(defaultPrompt) { Commands = new Commands(); Commands.AddCommand( "Help", false, "help", "help [<item>]", "Display help on a particular command or on a list of commands in a category", Help); } private void Help(string module, string[] cmd) { List<string> help = Commands.GetHelp(cmd); foreach (string s in help) Output(s); } protected void FireOnOutput(string text) { OnOutputDelegate onOutput = OnOutput; if (onOutput != null) onOutput(text); } /// <summary> /// Display a command prompt on the console and wait for user input /// </summary> public void Prompt() { string line = ReadLine(DefaultPrompt + "# ", true, true); if (line != String.Empty) Output("Invalid command"); } public void RunCommand(string cmd) { string[] parts = Parser.Parse(cmd); Commands.Resolve(parts); } public override string ReadLine(string p, bool isCommand, bool e) { System.Console.Write("{0}", p); string cmdinput = System.Console.ReadLine(); if (isCommand) { string[] cmd = Commands.Resolve(Parser.Parse(cmdinput)); if (cmd.Length != 0) { int i; for (i=0 ; i < cmd.Length ; i++) { if (cmd[i].Contains(" ")) cmd[i] = "\"" + cmd[i] + "\""; } return String.Empty; } } return cmdinput; } } }
using System; using System.Collections; using NBM.Plugin; using NBM.Plugin.Settings; using WinForms = System.Windows.Forms; using System.Threading; using Drawing = System.Drawing; // 1/6/03 namespace NBM { /// <summary> /// Each plugin protocol has a Protocol object. /// </summary> public class Protocol : IProtocolListener, IDisposable { private Hashtable conversationTable = new Hashtable(); private ProtocolSettings settings; private volatile bool isConnected = false; private volatile bool isConnecting = false; private IProtocol protocol = null; private ClassFactory classFactory; private IStorage localStorage; private ProtocolServer protocolServer; private ProtocolControl protocolControl; private TreeViewEx treeView; private TaskbarNotifier taskbarNotify; private ArgThread connectionThread = null; private const int connectionTimeout = 10 * 1000; // 10 second timeout private ArrayList optionsList = new ArrayList(); private NBM.Diagnostics.ProtocolReporter reporter; #region Properties /// <summary> /// An arraylist of IOptions defined by the plugin. /// </summary> public ArrayList OptionsNodes { get { return optionsList; } } /// <summary> /// Gets a value determining whether the current protocol is connected or not. /// </summary> public bool Connected { get { return isConnected; } } /// <summary> /// ClassFactory object associated with the protocol. /// </summary> public ClassFactory ClassFactory { get { return this.classFactory; } } /// <summary> /// ProtocolServer object associated with the protocol. /// </summary> public ProtocolServer Server { get { return protocolServer; } } /// <summary> /// IProtocol object associated with the protocol. /// </summary> public IProtocol IProtocol { get { return protocol; } } /// <summary> /// IProtocolSettings object associated with the protocol. /// </summary> public ProtocolSettings Settings { get { return settings; } } /// <summary> /// Name of the protocol. /// </summary> public string Name { get { return this.settings.Constants.Name; } } /// <summary> /// True if the user has enabled the protocol, false otherwise. /// </summary> public bool Enabled { get { return this.settings.Enabled; } } /// <summary> /// ProtocolReporter object associated with the protocol, the reporter is used for /// debugging purposes /// </summary> public NBM.Diagnostics.ProtocolReporter Reporter { get { return this.reporter; } } #endregion /// <summary> /// Constructs a Protocol object. /// </summary> /// <param name="treeView">TreeViewEx object which holds the contact list for the application</param> /// <param name="taskbarNotify">TaskbarNotify object which pops up on certain events</param> /// <param name="fileName">Filename of the plugin assembly</param> /// <param name="mainStorage">IStorage instance where the application's settings are stored</param> public Protocol(TreeViewEx treeView, TaskbarNotifier taskbarNotify, string fileName, IStorage mainStorage) { this.treeView = treeView; this.taskbarNotify = taskbarNotify; this.classFactory = new ClassFactory(fileName); // create plugin constants class IConstants constants = classFactory.CreateConstants(); this.localStorage = mainStorage.CreateSubSection(constants.Name); // create registry key for this protocol to store the settings this.settings = classFactory.CreateSettings(constants, this.localStorage, this.optionsList); this.settings.Load(); // create protocol control and register this class to be an event listener this.protocolServer = new ProtocolServer(); this.protocolServer.AddListener(this); this.protocolControl = new ProtocolControl(this.protocolServer); this.reporter = new NBM.Diagnostics.ProtocolReporter(this); } /// <summary> /// Invoke a delegate on the UI thread. /// </summary> /// <param name="dele"></param> /// <param name="args"></param> public void Invoke(Delegate dele, object[] args) { this.treeView.Invoke(dele, args); } /// <summary> /// Invoke a delegate on the UI thread. /// </summary> /// <param name="dele"></param> public void Invoke(Delegate dele) { this.treeView.Invoke(dele); } /// <summary> /// Disposes the object. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes the object. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing) { this.reporter.Dispose(); this.settings.Save(); this.localStorage.Close(); } } /// <summary> /// /// </summary> ~Protocol() { this.Dispose(false); } #region Protocol control event registration methods /// <summary> /// Add a listener to the protocol. The listeners receive events triggered by the plugin. /// </summary> /// <param name="listener"></param> public void AddListener(IProtocolListener listener) { this.protocolServer.AddListener(listener); } /// <summary> /// Remove a listener from the protocol. /// </summary> /// <param name="listener"></param> public void RemoveListener(IProtocolListener listener) { this.protocolServer.RemoveListener(listener); } #endregion #region Connection / Disconnection methods private delegate void ConnectHandler(OperationCompleteEvent opCompleteEvent); /// <summary> /// Connect the protocol. /// </summary> /// <param name="opCompleteEvent"></param> public void Connect(OperationCompleteEvent opCompleteEvent) { if (!this.isConnected && this.settings.Enabled) { this.isConnecting = true; this.protocolServer.OnBeginConnect(); opCompleteEvent.RegisterEvent(new OperationCompleteHandler(OnConnectionComplete)); // abort the connection thread if exists if (this.connectionThread != null) { try { if (this.connectionThread.IsAlive) this.connectionThread.Abort(); } catch {} this.connectionThread = null; } // start the connection on a new thread. this.connectionThread = new ArgThread(new ConnectHandler(pConnect)); this.connectionThread.Start(new object[] { opCompleteEvent }); } } /// <summary> /// Handler for the thread created by Connect(). /// </summary> /// <param name="opCompleteEvent"></param> private void pConnect(OperationCompleteEvent opCompleteEvent) { // create IProtocol derived class this.protocol = this.classFactory.CreateProtocol(this.protocolControl, this.settings); this.protocol.Connect(opCompleteEvent); Thread.Sleep(connectionTimeout); } /// <summary> /// Occurs when the connection is complete. /// </summary> /// <param name="args"></param> /// <param name="tag"></param> private void OnConnectionComplete(OperationCompleteArgs args, object tag) { this.treeView.Invalidate(); this.treeView.Update(); this.isConnecting = false; if (args is ConnectionCompleteArgs) { ConnectionCompleteArgs a = (ConnectionCompleteArgs)args; if (a.Success) { this.isConnected = true; this.protocolServer.OnConnect(); } else { this.protocolServer.OnConnectCanceled(); switch (a.Report) { case ConnectionFailedReport.AuthFailed: { // could not connect - pop up auth failed window AuthFailedForm form = new AuthFailedForm(this, args.ErrorMessage); if (form.ShowDialog() == WinForms.DialogResult.OK) { // attempt reconnect Connect(new OperationCompleteEvent()); } } break; default: case ConnectionFailedReport.InvalidProtocol: case ConnectionFailedReport.ConnectionFailed: if (GlobalSettings.Instance().ReconnectOnDisconnection) { Connect(new OperationCompleteEvent()); } break; } } } else { if (args.Success) { this.isConnected = true; this.protocolServer.OnConnect(); } else { this.protocolServer.OnConnectCanceled(); if (GlobalSettings.Instance().ReconnectOnDisconnection) { Connect(new OperationCompleteEvent()); } } } } /// <summary> /// Disconnects the protocol. /// </summary> /// <param name="opCompleteEvent"></param> public void Disconnect(OperationCompleteEvent opCompleteEvent) { // if disconnect is called whilst we are connecting, abort the connection thread. if (this.isConnecting = true || this.connectionThread != null) { opCompleteEvent.RegisterEvent(new OperationCompleteHandler(OnCancelationComplete)); this.protocol.CancelConnection(opCompleteEvent); } if (this.isConnected) { opCompleteEvent.RegisterEvent(new OperationCompleteHandler(OnDisconnectionComplete)); this.protocol.Disconnect(opCompleteEvent); } } /// <summary> /// Occurs when the protocol has completed canceling the connection /// </summary> /// <param name="args"></param> /// <param name="tag"></param> private void OnCancelationComplete(OperationCompleteArgs args, object tag) { this.protocolServer.OnConnectCanceled(); try { if (this.connectionThread.IsAlive) this.connectionThread.Abort(); } catch {} this.connectionThread = null; } /// <summary> /// Occurs when disconnection is complete. /// </summary> /// <param name="args"></param> /// <param name="tag"></param> private void OnDisconnectionComplete(OperationCompleteArgs args, object tag) { if (args.Success) { this.protocolServer.OnNormalDisconnect(); this.isConnected = false; } this.connectionThread = null; } #endregion #region Friend manipulation - Adding, removing and blocking /// <summary> /// Add a friend to the contact list. /// </summary> /// <param name="username">Username of friend to add</param> /// <param name="message">[optional] Friend message</param> /// <param name="op"></param> public void AddFriendToList(string username, string message, OperationCompleteEvent op) { this.protocol.AddFriendToList(username, message, op); this.protocolServer.AddFriendToList(username); } /// <summary> /// Remove a friend from the contact list. /// </summary> /// <param name="friend"></param> /// <param name="op"></param> public void RemoveFriendFromList(Friend friend, OperationCompleteEvent op) { this.protocol.RemoveFriendFromList(friend, op); this.protocolServer.RemoveFriendFromList(friend); } /// <summary> /// Block a friend /// </summary> /// <param name="friend"></param> /// <param name="op"></param> public void BlockFriend(Friend friend, OperationCompleteEvent op) { this.protocol.BlockFriend(friend, op); this.protocolServer.BlockFriend(friend); op.RegisterEvent(new OperationCompleteHandler(OnBlockFriendCompleted), friend); } /// <summary> /// When the block friend operation is completed /// </summary> /// <param name="args"></param> /// <param name="tag"></param> private void OnBlockFriendCompleted(OperationCompleteArgs args, object tag) { if (args.Success) ((Friend)tag).Blocked = true; } /// <summary> /// Unblock a friend. /// </summary> /// <param name="friend"></param> /// <param name="op"></param> public void UnblockFriend(Friend friend, OperationCompleteEvent op) { this.protocol.UnblockFriend(friend, op); this.protocolServer.UnblockFriend(friend); op.RegisterEvent(new OperationCompleteHandler(OnUnblockFriendCompleted), friend); } /// <summary> /// When the unblock operation is complete. /// </summary> /// <param name="args"></param> /// <param name="tag"></param> private void OnUnblockFriendCompleted(OperationCompleteArgs args, object tag) { if (args.Success) ((Friend)tag).Blocked = false; } #endregion #region Status change methods /// <summary> /// Change the user's status /// </summary> /// <param name="status"></param> /// <param name="opCompleteEvent"></param> public void ChangeStatus(OnlineStatus status, OperationCompleteEvent opCompleteEvent) { if (this.isConnected) { // if connected, change status through protocol opCompleteEvent.RegisterEvent(new OperationCompleteHandler(OnStatusChangeComplete), status); this.protocol.ChangeStatus(status, opCompleteEvent); } else { // else change the initial status pChangeStatus(status); } } /// <summary> /// When the status change operation is complete. /// </summary> /// <param name="args"></param> /// <param name="tag"></param> private void OnStatusChangeComplete(OperationCompleteArgs args, object tag) { if (args.Success) { pChangeStatus((OnlineStatus)tag); } } /// <summary> /// Change the status settings and inform the listeners /// </summary> /// <param name="status"></param> private void pChangeStatus(OnlineStatus status) { this.protocolServer.OnChangeStatus(status); this.settings.Status = status; } #endregion #region Conversation methods /// <summary> /// Begins a conversation with the specified friend. /// </summary> /// <param name="friend"></param> /// <param name="byinvite">Whether the conversation has been initiated by the user or by the plugin</param> /// <param name="tag">Plugin-defined object</param> /// <param name="opCompleteEvent"></param> public void StartConversation(Friend friend, bool byinvite, object tag, OperationCompleteEvent opCompleteEvent) { if (this.conversationTable.Contains(friend)) { MessageForm messageForm = (MessageForm)this.conversationTable[friend]; if (!byinvite) messageForm.BringToFront(); } else { MessageForm messageForm = new MessageForm(this, friend); messageForm.Closed += new EventHandler(OnMessageFormClosed); if (!byinvite) messageForm.Show(); messageForm.Connect(byinvite, tag, opCompleteEvent); conversationTable.Add(friend, messageForm); } } /// <summary> /// When a message form is closed, remove it from the conversation table. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnMessageFormClosed(object sender, EventArgs e) { this.conversationTable.Remove(((MessageForm)sender).OriginalFriend); } #endregion #region ProtocolListener events /// <summary> /// /// </summary> /// <param name="friend"></param> public void OnFriendAdd(Friend friend) { } /// <summary> /// /// </summary> /// <param name="friend"></param> public void OnFriendRemove(Friend friend) { } /// <summary> /// /// </summary> /// <param name="friend"></param> /// <param name="status"></param> public void OnFriendChangeStatus(Friend friend, OnlineStatus status) { if (this.Connected) // ignore any status changes until we have connected { if (friend.Status == OnlineStatus.Offline) { if (GlobalSettings.Instance().PlaySoundOnFriendOnline) { NativeMethods.PlaySoundFromFile(GlobalSettings.Instance().SoundOnFriendOnline, PlaySoundFlags.NoDefault | PlaySoundFlags.Asynchronous); } switch (GlobalSettings.Instance().FriendOnlineEvent) { default: case FriendOnlineEvent.DoNothing: break; case FriendOnlineEvent.BalloonToolTip: break; case FriendOnlineEvent.MSNPopUp: { this.taskbarNotify.Invoke( new ShowTaskbarNotifierHandler(ShowTaskbarNotifier), new object[] { "", friend.DisplayName + " (" + friend.Username + ") is Online" }); } break; } } } } private delegate void ShowTaskbarNotifierHandler(string title, string text); private void ShowTaskbarNotifier(string title, string text) { this.taskbarNotify.Show(title, text, 1000, 3000, 500); } /// <summary> /// /// </summary> /// <param name="friend"></param> /// <param name="newName"></param> public void OnFriendChangeDisplayName(Friend friend, string newName) { } /// <summary> /// /// </summary> public void OnBeginConnect() { } /// <summary> /// /// </summary> public void OnConnect() { } /// <summary> /// Called when the connection is canceled /// </summary> public void OnConnectCanceled() { } /// <summary> /// /// </summary> /// <param name="forced"></param> public void OnDisconnect(bool forced) { this.isConnected = false; this.protocol = null; if (forced && NBM.Plugin.Settings.GlobalSettings.Instance().ReconnectOnDisconnection) { // reconnect Connect(new OperationCompleteEvent()); } } /// <summary> /// /// </summary> /// <param name="friend"></param> /// <param name="opCompleteEvent"></param> /// <param name="tag"></param> public void OnInvitedToConversation(Friend friend, OperationCompleteEvent opCompleteEvent, object tag) { this.StartConversation(friend, true, tag, opCompleteEvent); } /// <summary> /// /// </summary> /// <param name="status"></param> public void OnChangeStatus(OnlineStatus status) { } /// <summary> /// /// </summary> /// <param name="username"></param> public void OnAddFriendToList(string username) { } /// <summary> /// /// </summary> /// <param name="friend"></param> public void OnRemoveFriendFromList(Friend friend) { } /// <summary> /// /// </summary> /// <param name="friend"></param> public void OnBlockFriend(Friend friend) { } /// <summary> /// /// </summary> /// <param name="friend"></param> public void OnUnblockFriend(Friend friend) { } /// <summary> /// /// </summary> /// <param name="text"></param> public void OnWriteDebug(string text) { } /// <summary> /// /// </summary> /// <param name="friend"></param> /// <param name="reason"></param> /// <param name="enableAddCheckbox"></param> public void OnPromptForStrangerHasAddedMe(Friend friend, string reason, bool enableAddCheckbox) { this.treeView.Invoke( new OnPromptForStrangerHasAddedMeHandler(OnPromptForStrangerHasAddedMeFunc), new object[] { friend, reason, enableAddCheckbox }); } private delegate void OnPromptForStrangerHasAddedMeHandler(Friend friend, string reason, bool enableAddCheckbox); /// <summary> /// /// </summary> /// <param name="friend"></param> /// <param name="reason"></param> /// <param name="enableAddCheckbox"></param> private void OnPromptForStrangerHasAddedMeFunc(Friend friend, string reason, bool enableAddCheckbox) { OnFriendAddForm form = new OnFriendAddForm(this.protocol, friend, reason, enableAddCheckbox); form.Show(); } #endregion /// <summary> /// /// </summary> public void SelfDestruct() { this.protocol.SelfDestruct(); } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; #if !NO_DYNAMIC_CODEGEN using System.Reflection.Emit; #endif using System.Security; using System.Security.Permissions; using System.Runtime.Serialization.Diagnostics.Application; using System.Xml; #if USE_REFEMIT public delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context,ClassDataContract dataContract); public delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); public sealed class XmlFormatWriterGenerator #else internal delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); internal delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); internal sealed partial class XmlFormatWriterGenerator #endif { [Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that was produced within an assert.")] [SecurityCritical] CriticalHelper helper; [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.")] [SecurityCritical] public XmlFormatWriterGenerator() { helper = new CriticalHelper(); } [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.")] [SecurityCritical] internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { try { if (TD.DCGenWriterStartIsEnabled()) { TD.DCGenWriterStart("Class", classContract.UnderlyingType.FullName); } return helper.GenerateClassWriter(classContract); } finally { if (TD.DCGenWriterStopIsEnabled()) { TD.DCGenWriterStop(); } } } [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical helper class 'CriticalHelper'.")] [SecurityCritical] internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { try { if (TD.DCGenWriterStartIsEnabled()) { TD.DCGenWriterStart("Collection", collectionContract.UnderlyingType.FullName); } return helper.GenerateCollectionWriter(collectionContract); } finally { if (TD.DCGenWriterStopIsEnabled()) { TD.DCGenWriterStop(); } } } #if !NO_DYNAMIC_CODEGEN [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Handles all aspects of IL generation including initializing the DynamicMethod." + " Changes to how IL generated could affect how data is serialized and what gets access to data," + " therefore we mark it for review so that changes to generation logic are reviewed.")] partial class CriticalHelper { CodeGenerator ilg; ArgBuilder xmlWriterArg; ArgBuilder contextArg; ArgBuilder dataContractArg; LocalBuilder objectLocal; // Used for classes LocalBuilder contractNamespacesLocal; LocalBuilder memberNamesLocal; LocalBuilder childElementNamespacesLocal; int typeIndex = 1; int childElementIndex = 0; internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { ilg.BeginMethod("Write" + classContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatClassWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag && securityException.PermissionType.Equals(typeof(ReflectionPermission))) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(classContract.UnderlyingType); DemandSerializationFormatterPermission(classContract); DemandMemberAccessPermission(memberAccessFlag); if (classContract.IsReadOnlyContract) { ThrowIfCannotSerializeReadOnlyTypes(classContract); } WriteClass(classContract); return (XmlFormatClassWriterDelegate)ilg.EndMethod(); } internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null); try { ilg.BeginMethod("Write" + collectionContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatCollectionWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag && securityException.PermissionType.Equals(typeof(ReflectionPermission))) { collectionContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(collectionContract.UnderlyingType); DemandMemberAccessPermission(memberAccessFlag); if (collectionContract.IsReadOnlyContract) { ThrowIfCannotSerializeReadOnlyTypes(collectionContract); } WriteCollection(collectionContract); return (XmlFormatCollectionWriterDelegate)ilg.EndMethod(); } void InitArgs(Type objType) { xmlWriterArg = ilg.GetArg(0); contextArg = ilg.GetArg(2); dataContractArg = ilg.GetArg(3); objectLocal = ilg.DeclareLocal(objType, "objSerialized"); ArgBuilder objectArg = ilg.GetArg(1); ilg.Load(objectArg); // Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter. // DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (objType == Globals.TypeOfDateTimeOffsetAdapter) { ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset); ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod); } else { ilg.ConvertValue(objectArg.ArgType, objType); } ilg.Stloc(objectLocal); } void DemandMemberAccessPermission(bool memberAccessFlag) { if (memberAccessFlag) { ilg.Call(contextArg, XmlFormatGeneratorStatics.DemandMemberAccessPermissionMethod); } } void DemandSerializationFormatterPermission(ClassDataContract classContract) { if (!classContract.HasDataContract && !classContract.IsNonAttributedType) { ilg.Call(contextArg, XmlFormatGeneratorStatics.DemandSerializationFormatterPermissionMethod); } } void ThrowIfCannotSerializeReadOnlyTypes(ClassDataContract classContract) { ThrowIfCannotSerializeReadOnlyTypes(XmlFormatGeneratorStatics.ClassSerializationExceptionMessageProperty); } void ThrowIfCannotSerializeReadOnlyTypes(CollectionDataContract classContract) { ThrowIfCannotSerializeReadOnlyTypes(XmlFormatGeneratorStatics.CollectionSerializationExceptionMessageProperty); } void ThrowIfCannotSerializeReadOnlyTypes(PropertyInfo serializationExceptionMessageProperty) { ilg.Load(contextArg); ilg.LoadMember(XmlFormatGeneratorStatics.SerializeReadOnlyTypesProperty); ilg.IfNot(); ilg.Load(dataContractArg); ilg.LoadMember(serializationExceptionMessageProperty); ilg.Load(null); ilg.Call(XmlFormatGeneratorStatics.ThrowInvalidDataContractExceptionMethod); ilg.EndIf(); } void InvokeOnSerializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerializing(classContract.BaseContract); if (classContract.OnSerializing != null) { ilg.LoadAddress(objectLocal); ilg.Load(contextArg); ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); ilg.Call(classContract.OnSerializing); } } void InvokeOnSerialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerialized(classContract.BaseContract); if (classContract.OnSerialized != null) { ilg.LoadAddress(objectLocal); ilg.Load(contextArg); ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); ilg.Call(classContract.OnSerialized); } } void WriteClass(ClassDataContract classContract) { InvokeOnSerializing(classContract); if (classContract.IsISerializable) ilg.Call(contextArg, XmlFormatGeneratorStatics.WriteISerializableMethod, xmlWriterArg, objectLocal); else { if (classContract.ContractNamespaces.Length > 1) { contractNamespacesLocal = ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces"); ilg.Load(dataContractArg); ilg.LoadMember(XmlFormatGeneratorStatics.ContractNamespacesField); ilg.Store(contractNamespacesLocal); } memberNamesLocal = ilg.DeclareLocal(typeof(XmlDictionaryString[]), "memberNames"); ilg.Load(dataContractArg); ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField); ilg.Store(memberNamesLocal); for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++) { if (classContract.ChildElementNamespaces[i] != null) { childElementNamespacesLocal = ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces"); ilg.Load(dataContractArg); ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespacesProperty); ilg.Store(childElementNamespacesLocal); } } if (classContract.HasExtensionData) { LocalBuilder extensionDataLocal = ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); ilg.Load(objectLocal); ilg.ConvertValue(objectLocal.LocalType, Globals.TypeOfIExtensibleDataObject); ilg.LoadMember(XmlFormatGeneratorStatics.ExtensionDataProperty); ilg.Store(extensionDataLocal); ilg.Call(contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, xmlWriterArg, extensionDataLocal, -1); WriteMembers(classContract, extensionDataLocal, classContract); } else WriteMembers(classContract, null, classContract); } InvokeOnSerialized(classContract); } int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract) { int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); LocalBuilder namespaceLocal = ilg.DeclareLocal(typeof(XmlDictionaryString), "ns"); if (contractNamespacesLocal == null) { ilg.Load(dataContractArg); ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); } else ilg.LoadArrayElement(contractNamespacesLocal, typeIndex - 1); ilg.Store(namespaceLocal); ilg.Call(contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classContract.Members.Count); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember member = classContract.Members[i]; Type memberType = member.MemberType; LocalBuilder memberValue = null; if (member.IsGetOnlyCollection) { ilg.Load(contextArg); ilg.Call(XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod); } if (!member.EmitDefaultValue) { memberValue = LoadMemberValue(member); ilg.IfNotDefaultValue(memberValue); } bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract); if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, null /*arrayItemIndex*/, namespaceLocal, null /*nameLocal*/, i + childElementIndex)) { WriteStartElement(memberType, classContract.Namespace, namespaceLocal, null /*nameLocal*/, i + childElementIndex); if (classContract.ChildElementNamespaces[i + childElementIndex] != null) { ilg.Load(xmlWriterArg); ilg.LoadArrayElement(childElementNamespacesLocal, i + childElementIndex); ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (memberValue == null) memberValue = LoadMemberValue(member); WriteValue(memberValue, writeXsiType); WriteEndElement(); } if (classContract.HasExtensionData) ilg.Call(contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, xmlWriterArg, extensionDataLocal, memberCount); if (!member.EmitDefaultValue) { if (member.IsRequired) { ilg.Else(); ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType); } ilg.EndIf(); } } typeIndex++; childElementIndex += classContract.Members.Count; return memberCount; } private LocalBuilder LoadMemberValue(DataMember member) { ilg.LoadAddress(objectLocal); ilg.LoadMember(member.MemberInfo); LocalBuilder memberValue = ilg.DeclareLocal(member.MemberType, member.Name + "Value"); ilg.Stloc(memberValue); return memberValue; } void WriteCollection(CollectionDataContract collectionContract) { LocalBuilder itemNamespace = ilg.DeclareLocal(typeof(XmlDictionaryString), "itemNamespace"); ilg.Load(dataContractArg); ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); ilg.Store(itemNamespace); LocalBuilder itemName = ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName"); ilg.Load(dataContractArg); ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty); ilg.Store(itemName); if (collectionContract.ChildElementNamespace != null) { ilg.Load(xmlWriterArg); ilg.Load(dataContractArg); ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespaceProperty); ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; LocalBuilder i = ilg.DeclareLocal(Globals.TypeOfInt, "i"); ilg.Call(contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, xmlWriterArg, objectLocal); if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, objectLocal, itemName, itemNamespace)) { ilg.For(i, 0, objectLocal); if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(itemType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); ilg.LoadArrayElement(objectLocal, i); LocalBuilder memberValue = ilg.DeclareLocal(itemType, "memberValue"); ilg.Stloc(memberValue); WriteValue(memberValue, false /*writeXsiType*/); WriteEndElement(); } ilg.EndFor(); } } else { MethodInfo incrementCollectionCountMethod = null; switch (collectionContract.Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod; break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType); break; case CollectionKind.GenericDictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } if (incrementCollectionCountMethod != null) { ilg.Call(contextArg, incrementCollectionCountMethod, xmlWriterArg, objectLocal); } bool isDictionary = false, isGenericDictionary = false; Type enumeratorType = null; Type[] keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { isGenericDictionary = true; keyValueTypes = collectionContract.ItemType.GetGenericArguments(); enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes); } else if (collectionContract.Kind == CollectionKind.Dictionary) { isDictionary = true; keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; enumeratorType = Globals.TypeOfDictionaryEnumerator; } else { enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType; } MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); if (moveNextMethod == null || getCurrentMethod == null) { if (enumeratorType.IsInterface) { if (moveNextMethod == null) moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod; if (getCurrentMethod == null) getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; } else { Type ienumeratorInterface = Globals.TypeOfIEnumerator; CollectionKind kind = collectionContract.Kind; if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable) { Type[] interfaceTypes = enumeratorType.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType) { ienumeratorInterface = interfaceType; break; } } } if (moveNextMethod == null) moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface); if (getCurrentMethod == null) getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface); } } Type elementType = getCurrentMethod.ReturnType; LocalBuilder currentValue = ilg.DeclareLocal(elementType, "currentValue"); LocalBuilder enumerator = ilg.DeclareLocal(enumeratorType, "enumerator"); ilg.Call(objectLocal, collectionContract.GetEnumeratorMethod); if (isDictionary) { ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator); ilg.New(XmlFormatGeneratorStatics.DictionaryEnumeratorCtor); } else if (isGenericDictionary) { Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes)); ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { ctorParam }, null); ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam); ilg.New(dictEnumCtor); } ilg.Stloc(enumerator); ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); if (incrementCollectionCountMethod == null) { ilg.Call(contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); } if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(elementType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); if (isGenericDictionary || isDictionary) { ilg.Call(dataContractArg, XmlFormatGeneratorStatics.GetItemContractMethod); ilg.Load(xmlWriterArg); ilg.Load(currentValue); ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject); ilg.Load(contextArg); ilg.Call(XmlFormatGeneratorStatics.WriteXmlValueMethod); } else { WriteValue(currentValue, false /*writeXsiType*/); } WriteEndElement(); } ilg.EndForEach(moveNextMethod); } } bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; // load xmlwriter if (type.IsValueType) { ilg.Load(xmlWriterArg); } else { ilg.Load(contextArg); ilg.Load(xmlWriterArg); } // load primitive value if (value != null) { ilg.Load(value); } else if (memberInfo != null) { ilg.LoadAddress(objectLocal); ilg.LoadMember(memberInfo); } else { ilg.LoadArrayElement(objectLocal, arrayItemIndex); } // load name if (name != null) { ilg.Load(name); } else { ilg.LoadArrayElement(memberNamesLocal, nameIndex); } // load namespace ilg.Load(ns); // call method to write primitive ilg.Call(primitiveContract.XmlFormatWriterMethod); return true; } bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string writeArrayMethod = null; switch (Type.GetTypeCode(itemType)) { case TypeCode.Boolean: writeArrayMethod = "WriteBooleanArray"; break; case TypeCode.DateTime: writeArrayMethod = "WriteDateTimeArray"; break; case TypeCode.Decimal: writeArrayMethod = "WriteDecimalArray"; break; case TypeCode.Int32: writeArrayMethod = "WriteInt32Array"; break; case TypeCode.Int64: writeArrayMethod = "WriteInt64Array"; break; case TypeCode.Single: writeArrayMethod = "WriteSingleArray"; break; case TypeCode.Double: writeArrayMethod = "WriteDoubleArray"; break; default: break; } if (writeArrayMethod != null) { ilg.Load(xmlWriterArg); ilg.Load(value); ilg.Load(itemName); ilg.Load(itemNamespace); ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, null, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null)); return true; } return false; } void WriteValue(LocalBuilder memberValue, bool writeXsiType) { Type memberType = memberValue.LocalType; if (memberType.IsPointer) { ilg.Load(memberValue); ilg.Load(memberType); ilg.Call(XmlFormatGeneratorStatics.BoxPointer); memberType = Globals.TypeOfReflectionPointer; memberValue = ilg.DeclareLocal(memberType, "memberValueRefPointer"); ilg.Store(memberValue); } bool isNullableOfT = (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.IsValueType && !isNullableOfT) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && !writeXsiType) ilg.Call(xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, writeXsiType); } else { if (isNullableOfT) { memberValue = UnwrapNullableObject(memberValue); //Leaves !HasValue on stack memberType = memberValue.LocalType; } else { ilg.Load(memberValue); ilg.Load(null); ilg.Ceq(); } ilg.If(); ilg.Call(contextArg, XmlFormatGeneratorStatics.WriteNullMethod, xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); ilg.Else(); PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { if (isNullableOfT) { ilg.Call(xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); } else { ilg.Call(contextArg, primitiveContract.XmlFormatContentWriterMethod, xmlWriterArg, memberValue); } } else { if (memberType == Globals.TypeOfObject || //boxed Nullable<T> memberType == Globals.TypeOfValueType || ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) { ilg.Load(memberValue); ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); memberValue = ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue"); memberType = memberValue.LocalType; ilg.Stloc(memberValue); ilg.If(memberValue, Cmp.EqualTo, null); ilg.Call(contextArg, XmlFormatGeneratorStatics.WriteNullMethod, xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); ilg.Else(); } InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod), memberValue, memberType, writeXsiType); if (memberType == Globals.TypeOfObject) //boxed Nullable<T> ilg.EndIf(); } ilg.EndIf(); } } void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType) { ilg.Load(contextArg); ilg.Load(xmlWriterArg); ilg.Load(memberValue); ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); LocalBuilder typeHandleValue = ilg.DeclareLocal(typeof(RuntimeTypeHandle), "typeHandleValue"); ilg.Call(null, typeof(Type).GetMethod("GetTypeHandle"), memberValue); ilg.Stloc(typeHandleValue); ilg.LoadAddress(typeHandleValue); ilg.Ldtoken(memberType); ilg.Call(typeof(RuntimeTypeHandle).GetMethod("Equals", new Type[] { typeof(RuntimeTypeHandle) })); ilg.Load(writeXsiType); ilg.Load(DataContract.GetId(memberType.TypeHandle)); ilg.Ldtoken(memberType); ilg.Call(methodInfo); } LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack { Type memberType = memberValue.LocalType; Label onNull = ilg.DefineLabel(); Label end = ilg.DefineLabel(); ilg.Load(memberValue); while (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { Type innerType = memberType.GetGenericArguments()[0]; ilg.Dup(); ilg.Call(XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(innerType)); ilg.Brfalse(onNull); ilg.Call(XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(innerType)); memberType = innerType; } memberValue = ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue"); ilg.Stloc(memberValue); ilg.Load(false); //isNull ilg.Br(end); ilg.MarkLabel(onNull); ilg.Pop(); ilg.Call(XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType)); ilg.Stloc(memberValue); ilg.Load(true); //isNull ilg.MarkLabel(end); return memberValue; } bool NeedsPrefix(Type type, XmlDictionaryString ns) { return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex) { bool needsPrefix = NeedsPrefix(type, ns); ilg.Load(xmlWriterArg); // prefix if (needsPrefix) ilg.Load(Globals.ElementPrefix); // localName if (nameLocal == null) ilg.LoadArrayElement(memberNamesLocal, nameIndex); else ilg.Load(nameLocal); // namespace ilg.Load(namespaceLocal); ilg.Call(needsPrefix ? XmlFormatGeneratorStatics.WriteStartElementMethod3 : XmlFormatGeneratorStatics.WriteStartElementMethod2); } void WriteEndElement() { ilg.Call(xmlWriterArg, XmlFormatGeneratorStatics.WriteEndElementMethod); } bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) { // Check for conflict with base type members if (CheckIfConflictingMembersHaveDifferentTypes(member)) return true; // Check for conflict with derived type members string name = member.Name; string ns = classContract.StableName.Namespace; ClassDataContract currentContract = derivedMostClassContract; while (currentContract != null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { List<DataMember> members = currentContract.Members; for (int j = 0; j < members.Count; j++) { if (name == members[j].Name) return CheckIfConflictingMembersHaveDifferentTypes(members[j]); } } currentContract = currentContract.BaseContract; } return false; } bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { while (member.ConflictingMember != null) { if (member.MemberType != member.ConflictingMember.MemberType) return true; member = member.ConflictingMember; } return false; } #if NotUsed static Hashtable nsToPrefixTable = new Hashtable(4); internal static string GetPrefix(string ns) { string prefix = (string)nsToPrefixTable[ns]; if (prefix == null) { lock (nsToPrefixTable) { if (prefix == null) { prefix = "p" + nsToPrefixTable.Count; nsToPrefixTable.Add(ns, prefix); } } } return prefix; } #endif } #endif } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Mail.Net.Dns.Client { #region usings using System; using System.Collections.Generic; #endregion /// <summary> /// This class represents dns server response. /// </summary> [Serializable] public class DnsServerResponse { #region Members private readonly List<DNS_rr_base> m_pAdditionalAnswers; private readonly List<DNS_rr_base> m_pAnswers; private readonly List<DNS_rr_base> m_pAuthoritiveAnswers; private readonly RCODE m_RCODE = RCODE.NO_ERROR; private readonly bool m_Success = true; #endregion #region Properties /// <summary> /// Gets if connection to dns server was successful. /// </summary> public bool ConnectionOk { get { return m_Success; } } /// <summary> /// Gets dns server response code. /// </summary> public RCODE ResponseCode { get { return m_RCODE; } } /// <summary> /// Gets all resource records returned by server (answer records section + authority records section + additional records section). /// NOTE: Before using this property ensure that ConnectionOk=true and ResponseCode=RCODE.NO_ERROR. /// </summary> public DNS_rr_base[] AllAnswers { get { List<DNS_rr_base> retVal = new List<DNS_rr_base>(); retVal.AddRange(m_pAnswers.ToArray()); retVal.AddRange(m_pAuthoritiveAnswers.ToArray()); retVal.AddRange(m_pAdditionalAnswers.ToArray()); return retVal.ToArray(); } } /// <summary> /// Gets dns server returned answers. NOTE: Before using this property ensure that ConnectionOk=true and ResponseCode=RCODE.NO_ERROR. /// </summary> /// <code> /// // NOTE: DNS server may return diffrent record types even if you query MX. /// // For example you query lumisoft.ee MX and server may response: /// // 1) MX - mail.lumisoft.ee /// // 2) A - lumisoft.ee /// // /// // Before casting to right record type, see what type record is ! /// /// /// foreach(DnsRecordBase record in Answers){ /// // MX record, cast it to MX_Record /// if(record.RecordType == QTYPE.MX){ /// MX_Record mx = (MX_Record)record; /// } /// } /// </code> public DNS_rr_base[] Answers { get { return m_pAnswers.ToArray(); } } /// <summary> /// Gets name server resource records in the authority records section. NOTE: Before using this property ensure that ConnectionOk=true and ResponseCode=RCODE.NO_ERROR. /// </summary> public DNS_rr_base[] AuthoritiveAnswers { get { return m_pAuthoritiveAnswers.ToArray(); } } /// <summary> /// Gets resource records in the additional records section. NOTE: Before using this property ensure that ConnectionOk=true and ResponseCode=RCODE.NO_ERROR. /// </summary> public DNS_rr_base[] AdditionalAnswers { get { return m_pAdditionalAnswers.ToArray(); } } #endregion #region Constructor internal DnsServerResponse(bool connectionOk, RCODE rcode, List<DNS_rr_base> answers, List<DNS_rr_base> authoritiveAnswers, List<DNS_rr_base> additionalAnswers) { m_Success = connectionOk; m_RCODE = rcode; m_pAnswers = answers; m_pAuthoritiveAnswers = authoritiveAnswers; m_pAdditionalAnswers = additionalAnswers; } #endregion #region Methods /// <summary> /// Gets IPv4 host addess records. /// </summary> /// <returns></returns> public DNS_rr_A[] GetARecords() { List<DNS_rr_A> retVal = new List<DNS_rr_A>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.A) { retVal.Add((DNS_rr_A) record); } } return retVal.ToArray(); } /// <summary> /// Gets name server records. /// </summary> /// <returns></returns> public DNS_rr_NS[] GetNSRecords() { List<DNS_rr_NS> retVal = new List<DNS_rr_NS>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.NS) { retVal.Add((DNS_rr_NS) record); } } return retVal.ToArray(); } /// <summary> /// Gets CNAME records. /// </summary> /// <returns></returns> public DNS_rr_CNAME[] GetCNAMERecords() { List<DNS_rr_CNAME> retVal = new List<DNS_rr_CNAME>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.CNAME) { retVal.Add((DNS_rr_CNAME) record); } } return retVal.ToArray(); } /// <summary> /// Gets SOA records. /// </summary> /// <returns></returns> public DNS_rr_SOA[] GetSOARecords() { List<DNS_rr_SOA> retVal = new List<DNS_rr_SOA>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.SOA) { retVal.Add((DNS_rr_SOA) record); } } return retVal.ToArray(); } /// <summary> /// Gets PTR records. /// </summary> /// <returns></returns> public DNS_rr_PTR[] GetPTRRecords() { List<DNS_rr_PTR> retVal = new List<DNS_rr_PTR>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.PTR) { retVal.Add((DNS_rr_PTR) record); } } return retVal.ToArray(); } /// <summary> /// Gets HINFO records. /// </summary> /// <returns></returns> public DNS_rr_HINFO[] GetHINFORecords() { List<DNS_rr_HINFO> retVal = new List<DNS_rr_HINFO>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.HINFO) { retVal.Add((DNS_rr_HINFO) record); } } return retVal.ToArray(); } /// <summary> /// Gets MX records.(MX records are sorted by preference, lower array element is prefered) /// </summary> /// <returns></returns> public DNS_rr_MX[] GetMXRecords() { List<DNS_rr_MX> mx = new List<DNS_rr_MX>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.MX) { mx.Add((DNS_rr_MX) record); } } // Sort MX records by preference. DNS_rr_MX[] retVal = mx.ToArray(); Array.Sort(retVal); return retVal; } /// <summary> /// Gets text records. /// </summary> /// <returns></returns> public DNS_rr_TXT[] GetTXTRecords() { List<DNS_rr_TXT> retVal = new List<DNS_rr_TXT>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.TXT) { retVal.Add((DNS_rr_TXT) record); } } return retVal.ToArray(); } /// <summary> /// Gets IPv6 host addess records. /// </summary> /// <returns></returns> public DNS_rr_A[] GetAAAARecords() { List<DNS_rr_A> retVal = new List<DNS_rr_A>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.AAAA) { retVal.Add((DNS_rr_A) record); } } return retVal.ToArray(); } /// <summary> /// Gets SRV resource records. /// </summary> /// <returns></returns> public DNS_rr_SRV[] GetSRVRecords() { List<DNS_rr_SRV> retVal = new List<DNS_rr_SRV>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.SRV) { retVal.Add((DNS_rr_SRV) record); } } return retVal.ToArray(); } /// <summary> /// Gets NAPTR resource records. /// </summary> /// <returns></returns> public DNS_rr_NAPTR[] GetNAPTRRecords() { List<DNS_rr_NAPTR> retVal = new List<DNS_rr_NAPTR>(); foreach (DNS_rr_base record in m_pAnswers) { if (record.RecordType == QTYPE.NAPTR) { retVal.Add((DNS_rr_NAPTR) record); } } return retVal.ToArray(); } #endregion #region Utility methods /// <summary> /// Filters out specified type of records from answer. /// </summary> /// <param name="answers"></param> /// <param name="type"></param> /// <returns></returns> private List<DNS_rr_base> FilterRecordsX(List<DNS_rr_base> answers, QTYPE type) { List<DNS_rr_base> retVal = new List<DNS_rr_base>(); foreach (DNS_rr_base record in answers) { if (record.RecordType == type) { retVal.Add(record); } } return retVal; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WebApiResourcesServer.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using WeifenLuo.WinFormsUI.Docking; namespace ks_admin.Customization { internal class VS2003DockPaneStrip : DockPaneStripBase { private class TabVS2003 : Tab { internal TabVS2003(IDockContent content) : base(content) { } private int m_tabX; protected internal int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; protected internal int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; protected internal int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected override DockPaneStripBase.Tab CreateTab(IDockContent content) { return new TabVS2003(content); } private class DocumentButton : Label { public DocumentButton(Image image) { Image = image; } } #region consts private const int _ToolWindowStripGapLeft = 4; private const int _ToolWindowStripGapRight = 3; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 3; private const int _ToolWindowImageGapRight = 2; private const int _ToolWindowTextGapRight = 1; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 5; private const int _DocumentButtonGapBottom = 5; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 3; private const int _DocumentTabGapLeft = 3; private const int _DocumentTabGapRight = 3; private const int _DocumentIconGapLeft = 6; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; #endregion private InertButton m_buttonClose, m_buttonScrollLeft, m_buttonScrollRight; private IContainer m_components; private ToolTip m_toolTip; /// <exclude/> protected IContainer Components { get { return m_components; } } private int m_offsetX = 0; private int OffsetX { get { return m_offsetX; } set { m_offsetX = value; #if DEBUG if (m_offsetX > 0) throw new InvalidOperationException(); #endif } } #region Customizable Properties /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowStripGapLeft"]/*'/> protected virtual int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowStripGapRight"]/*'/> protected virtual int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageHeight"]/*'/> protected virtual int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageWidth"]/*'/> protected virtual int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapTop"]/*'/> protected virtual int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapBottom"]/*'/> protected virtual int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapLeft"]/*'/> protected virtual int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowImageGapRight"]/*'/> protected virtual int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowTextGapRight"]/*'/> protected virtual int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowSeperatorGaptop"]/*'/> protected virtual int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowSeperatorGapBottom"]/*'/> protected virtual int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static Image _imageCloseEnabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageCloseEnabled"]/*'/> protected virtual Image ImageCloseEnabled { get { if (_imageCloseEnabled == null) _imageCloseEnabled = Resources.DockPaneStrip_CloseEnabled; return _imageCloseEnabled; } } private static Image _imageCloseDisabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageCloseDisabled"]/*'/> protected virtual Image ImageCloseDisabled { get { if (_imageCloseDisabled == null) _imageCloseDisabled = Resources.DockPaneStrip_CloseDisabled; return _imageCloseDisabled; } } private static Image _imageScrollLeftEnabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollLeftEnabled"]/*'/> protected virtual Image ImageScrollLeftEnabled { get { if (_imageScrollLeftEnabled == null) _imageScrollLeftEnabled = Resources.DockPaneStrip_ScrollLeftEnabled; return _imageScrollLeftEnabled; } } private static Image _imageScrollLeftDisabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollLeftDisabled"]/*'/> protected virtual Image ImageScrollLeftDisabled { get { if (_imageScrollLeftDisabled == null) _imageScrollLeftDisabled = Resources.DockPaneStrip_ScrollLeftDisabled; return _imageScrollLeftDisabled; } } private static Image _imageScrollRightEnabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollRightEnabled"]/*'/> protected virtual Image ImageScrollRightEnabled { get { if (_imageScrollRightEnabled == null) _imageScrollRightEnabled = Resources.DockPaneStrip_ScrollRightEnabled; return _imageScrollRightEnabled; } } private static Image _imageScrollRightDisabled = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ImageScrollRightDisabled"]/*'/> protected virtual Image ImageScrollRightDisabled { get { if (_imageScrollRightDisabled == null) _imageScrollRightDisabled = Resources.DockPaneStrip_ScrollRightDisabled; return _imageScrollRightDisabled; } } private static string _toolTipClose = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipClose"]/*'/> protected virtual string ToolTipClose { get { if (_toolTipClose == null) _toolTipClose = Strings.DockPaneStrip_ToolTipClose; return _toolTipClose; } } private static string _toolTipScrollLeft = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipScrollLeft"]/*'/> protected virtual string ToolTipScrollLeft { get { if (_toolTipScrollLeft == null) _toolTipScrollLeft = Strings.DockPaneStrip_ToolTipScrollLeft; return _toolTipScrollLeft; } } private static string _toolTipScrollRight = null; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolTipScrollRight"]/*'/> protected virtual string ToolTipScrollRight { get { if (_toolTipScrollRight == null) _toolTipScrollRight = Strings.DockPaneStrip_ToolTipScrollRight; return _toolTipScrollRight; } } private static TextFormatFlags _toolWindowTextFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ToolWindowTextStringFormat"]/*'/> protected virtual TextFormatFlags ToolWindowTextFormat { get { return _toolWindowTextFormat; } } private static TextFormatFlags _documentTextFormat = TextFormatFlags.PathEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTextStringFormat"]/*'/> public static TextFormatFlags DocumentTextFormat { get { return _documentTextFormat; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabMaxWidth"]/*'/> protected virtual int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapTop"]/*'/> protected virtual int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapBottom"]/*'/> protected virtual int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapBetween"]/*'/> protected virtual int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentButtonGapRight"]/*'/> protected virtual int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapTop"]/*'/> protected virtual int DocumentTabGapTop { get { return _DocumentTabGapTop; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapLeft"]/*'/> protected virtual int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentTabGapRight"]/*'/> protected virtual int DocumentTabGapRight { get { return _DocumentTabGapRight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconGapLeft"]/*'/> protected virtual int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconWidth"]/*'/> protected virtual int DocumentIconWidth { get { return _DocumentIconWidth; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="DocumentIconHeight"]/*'/> protected virtual int DocumentIconHeight { get { return _DocumentIconHeight; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="OutlineInnerPen"]/*'/> protected virtual Pen OutlineInnerPen { get { return SystemPens.ControlText; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="OutlineOuterPen"]/*'/> protected virtual Pen OutlineOuterPen { get { return SystemPens.ActiveCaptionText; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ActiveBackBrush"]/*'/> protected virtual Brush ActiveBackBrush { get { return SystemBrushes.Control; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="ActiveTextBrush"]/*'/> protected virtual Color ActiveTextColor { get { return SystemColors.ControlText; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="TabSeperatorPen"]/*'/> protected virtual Pen TabSeperatorPen { get { return SystemPens.GrayText; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Property[@name="InactiveTextBrush"]/*'/> protected virtual Color InactiveTextColor { get { return SystemColors.ControlDarkDark; } } #endregion public VS2003DockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SuspendLayout(); Font = SystemInformation.MenuFont; BackColor = Color.WhiteSmoke; m_components = new Container(); m_toolTip = new ToolTip(Components); m_buttonClose = new InertButton(ImageCloseEnabled, ImageCloseDisabled); m_buttonScrollLeft = new InertButton(ImageScrollLeftEnabled, ImageScrollLeftDisabled); m_buttonScrollRight = new InertButton(ImageScrollRightEnabled, ImageScrollRightDisabled); m_buttonClose.ToolTipText = ToolTipClose; m_buttonClose.Anchor = AnchorStyles.Top | AnchorStyles.Right; m_buttonClose.Click += new EventHandler(Close_Click); m_buttonScrollLeft.Enabled = false; m_buttonScrollLeft.RepeatClick = true; m_buttonScrollLeft.ToolTipText = ToolTipScrollLeft; m_buttonScrollLeft.Anchor = AnchorStyles.Top | AnchorStyles.Right; m_buttonScrollLeft.Click += new EventHandler(ScrollLeft_Click); m_buttonScrollRight.Enabled = false; m_buttonScrollRight.RepeatClick = true; m_buttonScrollRight.ToolTipText = ToolTipScrollRight; m_buttonScrollRight.Anchor = AnchorStyles.Top | AnchorStyles.Right; m_buttonScrollRight.Click += new EventHandler(ScrollRight_Click); Controls.AddRange(new Control[] { m_buttonClose, m_buttonScrollLeft, m_buttonScrollRight }); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); } base.Dispose (disposing); } protected override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(Font.Height, ToolWindowImageHeight) + ToolWindowImageGapTop + ToolWindowImageGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(Font.Height + DocumentTabGapTop, ImageCloseEnabled.Height + DocumentButtonGapTop + DocumentButtonGapBottom); return height; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); CalculateTabs(); DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { CalculateTabs(); SetInertButtons(); Invalidate(); } protected override GraphicsPath GetOutline(int index) { Point[] pts = new Point[8]; if (Appearance == DockPane.AppearanceStyle.Document) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); int y = DockPane.PointToClient(PointToScreen(new Point(0, rectTab.Bottom))).Y; Rectangle rectPaneClient = DockPane.ClientRectangle; pts[0] = DockPane.PointToScreen(new Point(rectPaneClient.Left, y)); pts[1] = PointToScreen(new Point(rectTab.Left, rectTab.Bottom)); pts[2] = PointToScreen(new Point(rectTab.Left, rectTab.Top)); pts[3] = PointToScreen(new Point(rectTab.Right, rectTab.Top)); pts[4] = PointToScreen(new Point(rectTab.Right, rectTab.Bottom)); pts[5] = DockPane.PointToScreen(new Point(rectPaneClient.Right, y)); pts[6] = DockPane.PointToScreen(new Point(rectPaneClient.Right, rectPaneClient.Bottom)); pts[7] = DockPane.PointToScreen(new Point(rectPaneClient.Left, rectPaneClient.Bottom)); } else { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); int y = DockPane.PointToClient(PointToScreen(new Point(0, rectTab.Top))).Y; Rectangle rectPaneClient = DockPane.ClientRectangle; pts[0] = DockPane.PointToScreen(new Point(rectPaneClient.Left, rectPaneClient.Top)); pts[1] = DockPane.PointToScreen(new Point(rectPaneClient.Right, rectPaneClient.Top)); pts[2] = DockPane.PointToScreen(new Point(rectPaneClient.Right, y)); pts[3] = PointToScreen(new Point(rectTab.Right, rectTab.Top)); pts[4] = PointToScreen(new Point(rectTab.Right, rectTab.Bottom)); pts[5] = PointToScreen(new Point(rectTab.Left, rectTab.Bottom)); pts[6] = PointToScreen(new Point(rectTab.Left, rectTab.Top)); pts[7] = DockPane.PointToScreen(new Point(rectPaneClient.Left, y)); } GraphicsPath path = new GraphicsPath(); path.AddLines(pts); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = ClientRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2003 tab in Tabs) { tab.MaxWidth = GetTabOriginalWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage=true; anyWidthWithinAverage && remainedTabs>0;) { anyWidthWithinAverage = false; foreach (TabVS2003 tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2003 tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth --; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2003 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private void CalculateTabs_Document() { Rectangle rectTabStrip = TabsRectangle; int totalWidth = 0; foreach (TabVS2003 tab in Tabs) { tab.TabWidth = Math.Min(GetTabOriginalWidth(Tabs.IndexOf(tab)), DocumentTabMaxWidth); totalWidth += tab.TabWidth; } if (totalWidth + OffsetX < rectTabStrip.Width && OffsetX < 0) OffsetX = Math.Min(0, rectTabStrip.Width - totalWidth); int x = rectTabStrip.X + OffsetX; foreach (TabVS2003 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } protected override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; Rectangle rectTabStrip = TabsRectangle; Rectangle rectTab = GetTabRectangle(Tabs.IndexOf(content)); if (rectTab.Right > rectTabStrip.Right) { OffsetX -= rectTab.Right - rectTabStrip.Right; rectTab.X -= rectTab.Right - rectTabStrip.Right; } if (rectTab.Left < rectTabStrip.Left) OffsetX += rectTabStrip.Left - rectTab.Left; OnRefreshChanges(); } private int GetTabOriginalWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOriginalWidth_ToolWindow(index); else return GetTabOriginalWidth_Document(index); } private int GetTabOriginalWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; using (Graphics g = CreateGraphics()) { Size sizeString = TextRenderer.MeasureText(g, content.DockHandler.TabText, Font); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } } private int GetTabOriginalWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; using (Graphics g = CreateGraphics()) { Size sizeText; if (content == DockPane.ActiveContent && DockPane.IsActiveDocumentPane) { using (Font boldFont = new Font(this.Font, FontStyle.Bold)) { sizeText = TextRenderer.MeasureText(g, content.DockHandler.TabText, boldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); } } else sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, Font, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); if (DockPane.DockPanel.ShowDocumentIcon) return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft; else return sizeText.Width; } } private void DrawTabStrip(Graphics g) { OnBeginDrawTabStrip(); if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); OnEndDrawTabStrip(); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = ClientRectangle; g.DrawLine(OutlineOuterPen, rectTabStrip.Left, rectTabStrip.Bottom - 1, rectTabStrip.Right, rectTabStrip.Bottom - 1); // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; g.SetClip(rectTabOnly); for (int i=0; i<count; i++) { rectTab = GetTabRectangle(i); if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2003, rectTab); } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = ClientRectangle; g.DrawLine(OutlineInnerPen, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i=0; i<Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2003, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = ClientRectangle; TabVS2003 tab = (TabVS2003)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = ClientRectangle; TabVS2003 tab = (TabVS2003)Tabs[index]; return new Rectangle(tab.TabX, rectTabStrip.Y + DocumentTabGapTop, tab.TabWidth, rectTabStrip.Height - DocumentTabGapTop); } private void DrawTab(Graphics g, TabVS2003 tab, Rectangle rect) { OnBeginDrawTab(tab); if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); OnEndDrawTab(tab); } private void DrawTab_ToolWindow(Graphics g, TabVS2003 tab, Rectangle rect) { Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; if (DockPane.ActiveContent == tab.Content) { g.FillRectangle(ActiveBackBrush, rect); g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X, rect.Y + rect.Height - 1); g.DrawLine(OutlineInnerPen, rect.X, rect.Y + rect.Height - 1, rect.X + rect.Width - 1, rect.Y + rect.Height - 1); g.DrawLine(OutlineInnerPen, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, ActiveTextColor, ToolWindowTextFormat); } else { if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) g.DrawLine(TabSeperatorPen, rect.X + rect.Width - 1, rect.Y + ToolWindowTabSeperatorGapTop, rect.X + rect.Width - 1, rect.Y + rect.Height - 1 - ToolWindowTabSeperatorGapBottom); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, ToolWindowTextFormat); } if (rect.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2003 tab, Rectangle rect) { Rectangle rectText = rect; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += DocumentIconWidth + DocumentIconGapLeft; rectText.Width -= DocumentIconWidth + DocumentIconGapLeft; } if (DockPane.ActiveContent == tab.Content) { g.FillRectangle(ActiveBackBrush, rect); g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X, rect.Y + rect.Height); g.DrawLine(OutlineOuterPen, rect.X, rect.Y, rect.X + rect.Width - 1, rect.Y); g.DrawLine(OutlineInnerPen, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1); if (DockPane.DockPanel.ShowDocumentIcon) { Icon icon = (tab.Content as Form).Icon; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + (rect.Height - DocumentIconHeight) / 2, DocumentIconWidth, DocumentIconHeight); g.DrawIcon(tab.ContentForm.Icon, rectIcon); } if (DockPane.IsActiveDocumentPane) { using (Font boldFont = new Font(this.Font, FontStyle.Bold)) { TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, boldFont, rectText, ActiveTextColor, DocumentTextFormat); } } else TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, DocumentTextFormat); } else { if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) g.DrawLine(TabSeperatorPen, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Y + rect.Height - 1 - DocumentTabGapTop); if (DockPane.DockPanel.ShowDocumentIcon) { Icon icon = tab.ContentForm.Icon; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + (rect.Height - DocumentIconHeight) / 2, DocumentIconWidth, DocumentIconHeight); g.DrawIcon(tab.ContentForm.Icon, rectIcon); } TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, Font, rectText, InactiveTextColor, DocumentTextFormat); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return ClientRectangle; Rectangle rectWindow = ClientRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + m_buttonClose.Width + m_buttonScrollRight.Width + m_buttonScrollLeft.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private void ScrollLeft_Click(object sender, EventArgs e) { Rectangle rectTabStrip = TabsRectangle; int index; for (index=0; index<Tabs.Count; index++) if (GetTabRectangle(index).IntersectsWith(rectTabStrip)) break; Rectangle rectTab = GetTabRectangle(index); if (rectTab.Left < rectTabStrip.Left) OffsetX += rectTabStrip.Left - rectTab.Left; else if (index == 0) OffsetX = 0; else OffsetX += rectTabStrip.Left - GetTabRectangle(index - 1).Left; OnRefreshChanges(); } private void ScrollRight_Click(object sender, EventArgs e) { Rectangle rectTabStrip = TabsRectangle; int index; int count = Tabs.Count; for (index=0; index<count; index++) if (GetTabRectangle(index).IntersectsWith(rectTabStrip)) break; if (index + 1 < count) { OffsetX -= GetTabRectangle(index + 1).Left - rectTabStrip.Left; CalculateTabs(); } Rectangle rectLastTab = GetTabRectangle(count - 1); if (rectLastTab.Right < rectTabStrip.Right) OffsetX += rectTabStrip.Right - rectLastTab.Right; OnRefreshChanges(); } private void SetInertButtons() { // Set the visibility of the inert buttons m_buttonScrollLeft.Visible = m_buttonScrollRight.Visible = m_buttonClose.Visible = (DockPane.DockState == DockState.Document); m_buttonClose.ForeColor = m_buttonScrollRight.ForeColor = m_buttonScrollLeft.ForeColor = SystemColors.ControlDarkDark; m_buttonClose.BorderColor = m_buttonScrollRight.BorderColor = m_buttonScrollLeft.BorderColor = SystemColors.ControlDarkDark; // Enable/disable scroll buttons int count = Tabs.Count; Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = (count == 0) ? Rectangle.Empty : GetTabRectangle(count - 1); m_buttonScrollLeft.Enabled = (OffsetX < 0); m_buttonScrollRight.Enabled = rectTab.Right > rectTabOnly.Right; // show/hide close button if (Appearance == DockPane.AppearanceStyle.ToolWindow) m_buttonClose.Visible = false; else { bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton; if (m_buttonClose.Visible != showCloseButton) { m_buttonClose.Visible = showCloseButton; PerformLayout(); } } } /// <exclude/> protected override void OnLayout(LayoutEventArgs levent) { Rectangle rectTabStrip = ClientRectangle; // Set position and size of the buttons int buttonWidth = ImageCloseEnabled.Width; int buttonHeight = ImageCloseEnabled.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); m_buttonClose.Size = m_buttonScrollLeft.Size = m_buttonScrollRight.Size = buttonSize; int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; m_buttonClose.Location = new Point(x, y); Point point = m_buttonClose.Location; bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton; if (showCloseButton) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); m_buttonScrollRight.Location = point; point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); m_buttonScrollLeft.Location = point; OnRefreshChanges(); base.OnLayout (levent); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } /// <exclude/> protected override int HitTest(Point ptMouse) { Rectangle rectTabStrip = TabsRectangle; for (int i=0; i<Tabs.Count; i++) { Rectangle rectTab = GetTabRectangle(i); rectTab.Intersect(rectTabStrip); if (rectTab.Contains(ptMouse)) return i; } return -1; } /// <exclude/> protected override void OnMouseMove(MouseEventArgs e) { int index = HitTest(PointToClient(Control.MousePosition)); string toolTip = string.Empty; base.OnMouseMove(e); if (index != -1) { Rectangle rectTab = GetTabRectangle(index); if (Tabs[index].Content.DockHandler.ToolTipText != null) toolTip = Tabs[index].Content.DockHandler.ToolTipText; else if (rectTab.Width < GetTabOriginalWidth(index)) toolTip = Tabs[index].Content.DockHandler.TabText; } if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnBeginDrawTabStrip()"]/*'/> protected virtual void OnBeginDrawTabStrip() { } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnEndDrawTabStrip()"]/*'/> protected virtual void OnEndDrawTabStrip() { } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnBeginDrawTab(DockPaneTab)"]/*'/> protected virtual void OnBeginDrawTab(Tab tab) { } /// <include file='CodeDoc/DockPaneStripVS2003.xml' path='//CodeDoc/Class[@name="DockPaneStripVS2003"]/Method[@name="OnEndDrawTab(DockPaneTab)"]/*'/> protected virtual void OnEndDrawTab(Tab tab) { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.Mime { /// <summary> /// Rfc 2822 3.4 address-list. Rfc defines two types of addresses mailbox and group. /// <p/> /// <p style="margin-top: 0; margin-bottom: 0"/><b>address-list</b> syntax: address *("," address). /// <p style="margin-top: 0; margin-bottom: 0"/><b>address</b> syntax: mailbox / group. /// <p style="margin-top: 0; margin-bottom: 0"/><b>mailbox</b> syntax: ['"'dispaly-name'"' ]&lt;localpart@domain&gt;. /// <p style="margin-top: 0; margin-bottom: 0"/><b>group</b> syntax: '"'dispaly-name'":' [mailbox *(',' mailbox)]';'. /// </summary> [Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")] public class AddressList : IEnumerable { private HeaderField m_HeaderField = null; private List<Address> m_pAddresses = null; /// <summary> /// Default constructor. /// </summary> public AddressList() { m_pAddresses = new List<Address>(); } #region method Add /// <summary> /// Adds a new address to the end of the collection. /// </summary> /// <param name="address">Address to add.</param> public void Add(Address address) { address.Owner = this; m_pAddresses.Add(address); OnCollectionChanged(); } #endregion #region method Insert /// <summary> /// Inserts a new address into the collection at the specified location. /// </summary> /// <param name="index">The location in the collection where you want to add the address.</param> /// <param name="address">Address to add.</param> public void Insert(int index,Address address) { address.Owner = this; m_pAddresses.Insert(index,address); OnCollectionChanged(); } #endregion #region method Remove /// <summary> /// Removes address at the specified index from the collection. /// </summary> /// <param name="index">Index of the address which to remove.</param> public void Remove(int index) { Remove((Address)m_pAddresses[index]); } /// <summary> /// Removes specified address from the collection. /// </summary> /// <param name="address">Address to remove.</param> public void Remove(Address address) { address.Owner = null; m_pAddresses.Remove(address); OnCollectionChanged(); } #endregion #region method Clear /// <summary> /// Clears the collection of all addresses. /// </summary> public void Clear() { foreach(Address address in m_pAddresses){ address.Owner = null; } m_pAddresses.Clear(); OnCollectionChanged(); } #endregion #region method Parse /// <summary> /// Parses address-list from string. /// </summary> /// <param name="addressList">Address list string.</param> /// <returns></returns> public void Parse(string addressList) { addressList = addressList.Trim(); StringReader reader = new StringReader(addressList); while(reader.SourceString.Length > 0){ // See if mailbox or group. If ',' is before ':', then mailbox // Example: [email protected], group:[email protected]; int commaIndex = TextUtils.QuotedIndexOf(reader.SourceString,','); int colonIndex = TextUtils.QuotedIndexOf(reader.SourceString,':'); // Mailbox if(colonIndex == -1 || (commaIndex < colonIndex && commaIndex != -1)){ // FIX: why quotes missing //System.Windows.Forms.MessageBox.Show(reader.SourceString + "#" + reader.OriginalString); // Read to ',' or to end if last element MailboxAddress address = MailboxAddress.Parse(reader.QuotedReadToDelimiter(',')); m_pAddresses.Add(address); address.Owner = this; } // Group else{ // Read to ';', this is end of group GroupAddress address = GroupAddress.Parse(reader.QuotedReadToDelimiter(';')); m_pAddresses.Add(address); address.Owner = this; // If there are next items, remove first comma because it's part of group address if(reader.SourceString.Length > 0){ reader.QuotedReadToDelimiter(','); } } } OnCollectionChanged(); } #endregion #region method ToAddressListString /// <summary> /// Convert addresses to Rfc 2822 address-list string. /// </summary> /// <returns></returns> public string ToAddressListString() { StringBuilder retVal = new StringBuilder(); for(int i=0;i<m_pAddresses.Count;i++){ if(m_pAddresses[i] is MailboxAddress){ // For last address don't add , and <TAB> if(i == (m_pAddresses.Count - 1)){ retVal.Append(((MailboxAddress)m_pAddresses[i]).ToMailboxAddressString()); } else{ retVal.Append(((MailboxAddress)m_pAddresses[i]).ToMailboxAddressString() + ",\t"); } } else if(m_pAddresses[i] is GroupAddress){ // For last address don't add , and <TAB> if(i == (m_pAddresses.Count - 1)){ retVal.Append(((GroupAddress)m_pAddresses[i]).GroupString); } else{ retVal.Append(((GroupAddress)m_pAddresses[i]).GroupString + ",\t"); } } } return retVal.ToString(); } #endregion #region internal method OnCollectionChanged /// <summary> /// This called when collection has changed. Item is added,deleted,changed or collection cleared. /// </summary> internal void OnCollectionChanged() { // AddressList is bounded to HeaderField, update header field value if(m_HeaderField != null){ m_HeaderField.Value = this.ToAddressListString(); } } #endregion #region interface IEnumerator /// <summary> /// Gets enumerator. /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return m_pAddresses.GetEnumerator(); } #endregion #region Properties Implementation /// <summary> /// Gets all mailbox addresses. Note: group address mailbox addresses are also included. /// </summary> public MailboxAddress[] Mailboxes { get{ ArrayList adressesAll = new ArrayList(); foreach(Address adress in this){ if(!adress.IsGroupAddress){ adressesAll.Add((MailboxAddress)adress); } else{ foreach(MailboxAddress groupChildAddress in ((GroupAddress)adress).GroupMembers){ adressesAll.Add((MailboxAddress)groupChildAddress); } } } MailboxAddress[] retVal = new MailboxAddress[adressesAll.Count]; adressesAll.CopyTo(retVal); return retVal; } } /// <summary> /// Gets address from specified index. /// </summary> public Address this[int index] { get{ return (Address)m_pAddresses[index]; } } /// <summary> /// Gets address count in the collection. /// </summary> public int Count { get{ return m_pAddresses.Count; } } /// <summary> /// Bound address-list to specified header field. /// </summary> internal HeaderField BoundedHeaderField { get{ return m_HeaderField; } set{m_HeaderField = value; } } #endregion } }
using Orleans; namespace UnitTests.General { using System; using System.Reflection; using System.Threading.Tasks; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using Xunit.Abstractions; /// <summary> /// Tests that exceptions are correctly propagated. /// </summary> public class ExceptionPropagationTests : OrleansTestingBase, IClassFixture<ExceptionPropagationTests.Fixture> { private readonly ITestOutputHelper output; private readonly Fixture fixture; public ExceptionPropagationTests(ITestOutputHelper output, Fixture fixture) { this.output = output; this.fixture = fixture; } public class Fixture : BaseTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.ConfigureLegacyConfiguration(legacy => { legacy.ClientConfiguration.SerializationProviders.Add(typeof(OneWaySerializer).GetTypeInfo()); legacy.ClusterConfiguration.Globals.SerializationProviders.Add(typeof(OneWaySerializer).GetTypeInfo()); legacy.ClusterConfiguration.Globals.TypeMapRefreshInterval = TimeSpan.FromMilliseconds(200); }); } } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task BasicExceptionPropagation() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); var exception = await Assert.ThrowsAsync<InvalidOperationException>( () => grain.ThrowsInvalidOperationException()); output.WriteLine(exception.ToString()); Assert.Equal("Test exception", exception.Message); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public void ExceptionContainsOriginalStackTrace() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); // Explicitly using .Wait() instead of await the task to avoid any modification of the inner exception var aggEx = Assert.Throws<AggregateException>( () => grain.ThrowsInvalidOperationException().Wait()); var exception = aggEx.InnerException; output.WriteLine(exception.ToString()); Assert.IsAssignableFrom<InvalidOperationException>(exception); Assert.Equal("Test exception", exception.Message); Assert.Contains("ThrowsInvalidOperationException", exception.StackTrace); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ExceptionContainsOriginalStackTraceWhenRethrowingLocally() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); try { // Use await to force the exception to be rethrown and validate that the remote stack trace is still present await grain.ThrowsInvalidOperationException(); Assert.True(false, "should have thrown"); } catch (InvalidOperationException exception) { output.WriteLine(exception.ToString()); Assert.IsAssignableFrom<InvalidOperationException>(exception); Assert.Equal("Test exception", exception.Message); Assert.Contains("ThrowsInvalidOperationException", exception.StackTrace); } } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ExceptionPropagationDoesNotUnwrapAggregateExceptions() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); var exception = await Assert.ThrowsAsync<AggregateException>( () => grain.ThrowsAggregateExceptionWrappingInvalidOperationException()); var nestedEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerException); Assert.Equal("Test exception", nestedEx.Message); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ExceptionPropagationDoesNoFlattenAggregateExceptions() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); var exception = await Assert.ThrowsAsync<AggregateException>( () => grain.ThrowsNestedAggregateExceptionsWrappingInvalidOperationException()); var nestedAggEx = Assert.IsAssignableFrom<AggregateException>(exception.InnerException); var doubleNestedEx = Assert.IsAssignableFrom<InvalidOperationException>(nestedAggEx.InnerException); Assert.Equal("Test exception", doubleNestedEx.Message); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task TaskCancelationPropagation() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); await Assert.ThrowsAsync<TaskCanceledException>( () => grain.Canceled()); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task GrainForwardingExceptionPropagation() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); var otherGrainId = GetRandomGrainId(); var exception = await Assert.ThrowsAsync<InvalidOperationException>( () => grain.GrainCallToThrowsInvalidOperationException(otherGrainId)); Assert.Equal("Test exception", exception.Message); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task GrainForwardingExceptionPropagationDoesNotUnwrapAggregateExceptions() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); var otherGrainId = GetRandomGrainId(); var exception = await Assert.ThrowsAsync<AggregateException>( () => grain.GrainCallToThrowsAggregateExceptionWrappingInvalidOperationException(otherGrainId)); var nestedEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerException); Assert.Equal("Test exception", nestedEx.Message); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task SynchronousExceptionThrownShouldResultInFaultedTask() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); // start the grain call but don't await it nor wrap in try/catch, to make sure it doesn't throw synchronously var grainCallTask = grain.ThrowsSynchronousInvalidOperationException(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => grainCallTask); Assert.Equal("Test exception", exception.Message); var grainCallTask2 = grain.ThrowsSynchronousInvalidOperationException(); var exception2 = await Assert.ThrowsAsync<InvalidOperationException>(() => grainCallTask2); Assert.Equal("Test exception", exception2.Message); } [Fact(Skip = "Implementation of issue #1378 is still pending"), TestCategory("BVT"), TestCategory("Functional")] public void ExceptionPropagationForwardsEntireAggregateException() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); var grainCall = grain.ThrowsMultipleExceptionsAggregatedInFaultedTask(); try { // use Wait() so that we get the entire AggregateException ('await' would just catch the first inner exception) // Do not use Assert.Throws to avoid any tampering of the AggregateException itself from the test framework grainCall.Wait(); Assert.True(false, "Expected AggregateException"); } catch (AggregateException exception) { output.WriteLine(exception.ToString()); // make sure that all exceptions in the task are present, and not just the first one. Assert.Equal(2, exception.InnerExceptions.Count); var firstEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerExceptions[0]); Assert.Equal("Test exception 1", firstEx.Message); var secondEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerExceptions[1]); Assert.Equal("Test exception 2", secondEx.Message); } } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task SynchronousAggregateExceptionThrownShouldResultInFaultedTaskWithOriginalAggregateExceptionUnmodifiedAsInnerException() { IExceptionGrain grain = this.fixture.GrainFactory.GetGrain<IExceptionGrain>(GetRandomGrainId()); // start the grain call but don't await it nor wrap in try/catch, to make sure it doesn't throw synchronously var grainCallTask = grain.ThrowsSynchronousAggregateExceptionWithMultipleInnerExceptions(); // assert that the faulted task has an inner exception of type AggregateException, which should be our original exception var exception = await Assert.ThrowsAsync<AggregateException>(() => grainCallTask); Assert.Equal("Test AggregateException message", exception.Message); // make sure that all exceptions in the task are present, and not just the first one. Assert.Equal(2, exception.InnerExceptions.Count); var firstEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerExceptions[0]); Assert.Equal("Test exception 1", firstEx.Message); var secondEx = Assert.IsAssignableFrom<InvalidOperationException>(exception.InnerExceptions[1]); Assert.Equal("Test exception 2", secondEx.Message); } /// <summary> /// Tests that when the body of a message sent between a client and a grain cannot be deserialized, an exception /// is immediately propagated back to the caller. /// </summary> /// <returns>A <see cref="Task"/> representing the work performed.</returns> [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Messaging"), TestCategory("Serialization")] public async Task ExceptionPropagationMessageBodyDeserializationFailure() { var grain = this.fixture.GrainFactory.GetGrain<IMessageSerializationGrain>(GetRandomGrainId()); // A serializer is used on the client & silo which can serialize but not deserialize the type being used. var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => grain.EchoObject(new SimpleType(2))); Assert.Contains(OneWaySerializer.FailureMessage, exception.Message); } /// <summary> /// Tests that when the body of a message sent between two grains cannot be deserialized, an exception is immediately /// propagated back to the caller. /// </summary> /// <returns>A <see cref="Task"/> representing the work performed.</returns> [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Messaging"), TestCategory("Serialization")] public async Task ExceptionPropagationGrainToGrainMessageBodyDeserializationFailure() { var grain = this.fixture.GrainFactory.GetGrain<IMessageSerializationGrain>(GetRandomGrainId()); // A serializer is used on the client & silo which can serialize but not deserialize the type being used. var exception = await Assert.ThrowsAnyAsync<NotSupportedException>(() => grain.GetUnserializableObjectChained()); Assert.Contains(OneWaySerializer.FailureMessage, exception.Message); } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using OpenTK.Graphics.OpenGL; using nzy3D.Chart; using nzy3D.Colors; using nzy3D.Events; using nzy3D.Factories; using nzy3D.Maths; using nzy3D.Plot3D.Primitives; using nzy3D.Plot3D.Primitives.Axes; using nzy3D.Plot3D.Rendering; using nzy3D.Plot3D.Rendering.Canvas; using nzy3D.Plot3D.Rendering.View.Modes; using nzy3D.Plot3D.Transform; namespace nzy3D.Plot3D.Rendering.View { public class View { public static float STRETCH_RATIO = 0.25f; // force to have all object maintained in screen, meaning axebox won't always keep the same size. internal bool MAINTAIN_ALL_OBJECTS_IN_VIEW = false; // display a magenta parallelepiped (debug) internal bool DISPLAY_AXE_WHOLE_BOUNDS = false; internal bool _axeBoxDisplayed = true; internal bool _squared = true; internal Camera _cam; internal IAxe _axe; internal Quality _quality; // TODO : Implement overlay // Friend _overlay As Overlay internal Scene _scene; internal ICanvas _canvas; internal Coord3d _viewpoint; internal Coord3d _center; internal Coord3d _scaling; internal BoundingBox3d _viewbounds; internal CameraMode _cameraMode; internal ViewPositionMode _viewmode; internal ViewBoundMode _boundmode; internal ImageViewport _bgViewport; internal System.Drawing.Bitmap _bgImg = null; internal BoundingBox3d _targetBox; internal Color _bgColor = Color.BLACK; internal Color _bgOverlay = new Color(0, 0, 0, 0); // TODO : Implement overlay //Friend _tooltips As List(Of ITooltipRenderer) internal List<IRenderer2D> _renderers; internal List<IViewPointChangedListener> _viewPointChangedListeners; internal List<IViewIsVerticalEventListener> _viewOnTopListeners; internal bool _wasOnTopAtLastRendering; static internal float PI_div2 = Convert.ToSingle(System.Math.PI / 2); public static Coord3d DEFAULT_VIEW = new Coord3d(System.Math.PI / 3, System.Math.PI / 3, 2000); internal bool _dimensionDirty = false; internal bool _viewDirty = false; static internal View Current; public View(Scene scene, ICanvas canvas, Quality quality) { BoundingBox3d sceneBounds = scene.Graph.Bounds; _viewpoint = (Coord3d)DEFAULT_VIEW.Clone(); _center = (Coord3d)sceneBounds.getCenter(); _scaling = (Coord3d)Coord3d.IDENTITY.Clone(); _viewmode = ViewPositionMode.FREE; _boundmode = ViewBoundMode.AUTO_FIT; _cameraMode = CameraMode.ORTHOGONAL; _axe = (IAxe)AxeFactory.getInstance(sceneBounds, this); _cam = CameraFactory.getInstance(_center); _scene = scene; _canvas = canvas; _quality = quality; _renderers = new List<IRenderer2D>(); //_tooltips = New List(Of ITooltipRenderer) _bgViewport = new ImageViewport(); _viewOnTopListeners = new List<IViewIsVerticalEventListener>(); _viewPointChangedListeners = new List<IViewPointChangedListener>(); _wasOnTopAtLastRendering = false; //_overlay = New Overlay View.Current = this; } public void Dispose() { _axe.Dispose(); _cam = null; _renderers.Clear(); _viewOnTopListeners.Clear(); _scene = null; _canvas = null; _quality = null; } public void Shoot() { _canvas.ForceRepaint(); } public void Project() { _scene.Graph.Project(_cam); } public Coord3d ProjectMouse(int x, int y) { return _cam.ScreenToModel(new Coord3d(x, y, 0)); } #region "GENERAL DISPLAY CONTROLS" public void Rotate(Coord2d move) { Rotate(move, true); } public void Rotate(Coord2d move, bool updateView) { Coord3d eye = this.ViewPoint; eye.x -= move.x; eye.y += move.y; setViewPoint(eye, updateView); //fireControllerEvent(ControllerType.ROTATE, eye); } public void Shift(float factor) { Shift(factor, true); } public void Shift(float factor, bool updateView) { nzy3D.Maths.Scale current = this.Scale; nzy3D.Maths.Scale newScale = current.@add(factor * current.Range); setScale(newScale, updateView); //fireControllerEvent(ControllerType.SHIFT, newScale); } public void Zoom(float factor) { Zoom(factor, true); } public void Zoom(float factor, bool updateView) { nzy3D.Maths.Scale current = this.Scale; double range = current.Max - current.Min; if (range <= 0) { return; } double center = (current.Max + current.Min) / 2; double zmin = center + (current.Min - center) * factor; double zmax = center + (current.Max - center) * factor; // set min/max according to bounds nzy3D.Maths.Scale scale = null; if ((zmin < zmax)) { scale = new nzy3D.Maths.Scale(zmin, zmax); } else { // forbid to have zmin = zmax if we zoom in if ((factor < 1)) { scale = new nzy3D.Maths.Scale(center, center); } } if ((scale != null)) { setScale(scale, updateView); // fireControllerEvent(ControllerType.ZOOM, scale); } } public void ZoomX(float factor) { ZoomX(factor, true); } public void ZoomX(float factor, bool updateView) { double range = this.Bounds.xmax - this.Bounds.xmin; if (range <= 0) { return; } double center = (this.Bounds.xmax + this.Bounds.xmin) / 2; double min = center + (this.Bounds.xmin - center) * factor; double max = center + (this.Bounds.xmax - center) * factor; // set min/max according to bounds nzy3D.Maths.Scale scale = null; if ((min < max)) { scale = new nzy3D.Maths.Scale(min, max); } else { // forbid to have min = max if we zoom in if ((factor < 1)) { scale = new nzy3D.Maths.Scale(center, center); } } if ((scale != null)) { BoundingBox3d bounds = this.Bounds; bounds.xmin = scale.Min; bounds.xmax = scale.Max; this.BoundManual = bounds; if (updateView) { Shoot(); } // fireControllerEvent(ControllerType.ZOOM, scale); } } public void ZoomY(float factor) { ZoomY(factor, true); } public void ZoomY(float factor, bool updateView) { double range = this.Bounds.ymax - this.Bounds.ymin; if (range <= 0) { return; } double center = (this.Bounds.ymax + this.Bounds.ymin) / 2; double min = center + (this.Bounds.ymin - center) * factor; double max = center + (this.Bounds.ymax - center) * factor; // set min/max according to bounds nzy3D.Maths.Scale scale = null; if ((min < max)) { scale = new nzy3D.Maths.Scale(min, max); } else { // forbid to have min = max if we zoom in if ((factor < 1)) { scale = new nzy3D.Maths.Scale(center, center); } } if ((scale != null)) { BoundingBox3d bounds = this.Bounds; bounds.ymin = scale.Min; bounds.ymax = scale.Max; this.BoundManual = bounds; if (updateView) { Shoot(); } // fireControllerEvent(ControllerType.ZOOM, scale); } } public void ZoomZ(float factor) { ZoomZ(factor, true); } public void ZoomZ(float factor, bool updateView) { double range = this.Bounds.zmax - this.Bounds.zmin; if (range <= 0) { return; } double center = (this.Bounds.zmax + this.Bounds.zmin) / 2; double min = center + (this.Bounds.zmin - center) * factor; double max = center + (this.Bounds.zmax - center) * factor; // set min/max according to bounds nzy3D.Maths.Scale scale = null; if ((min < max)) { scale = new nzy3D.Maths.Scale(min, max); } else { // forbid to have min = max if we zoom in if ((factor < 1)) { scale = new nzy3D.Maths.Scale(center, center); } } if ((scale != null)) { BoundingBox3d bounds = this.Bounds; bounds.zmin = scale.Min; bounds.zmax = scale.Max; this.BoundManual = bounds; if (updateView) { Shoot(); } // fireControllerEvent(ControllerType.ZOOM, scale); } } public bool DimensionDirty { get { return _dimensionDirty; } set { _dimensionDirty = value; } } public nzy3D.Maths.Scale Scale { get { return new nzy3D.Maths.Scale(this.Bounds.zmin, this.Bounds.zmax); } set { setScale(value, true); } } public void setScale(nzy3D.Maths.Scale scale, bool notify) { BoundingBox3d bounds = this.Bounds; bounds.zmin = scale.Min; bounds.zmax = scale.Max; this.BoundManual = bounds; if (notify) { Shoot(); } } /// <summary> /// Set the surrounding AxeBox dimensions and the Camera target, and the /// colorbar range. /// </summary> public void lookToBox(BoundingBox3d box) { _center = box.getCenter(); _axe.setAxe(box); _targetBox = box; } /// <summary> /// Get the <see cref="AxeBox"/>'s bounds /// </summary> public BoundingBox3d Bounds { get { return _axe.getBoxBounds(); } } public ViewBoundMode BoundsMode { get { return _boundmode; } } /// <summary> /// Set the ViewPositionMode applied to this view. /// </summary> public ViewPositionMode ViewMode { get { return _viewmode; } set { _viewmode = value; } } public Coord3d ViewPoint { get { return _viewpoint; } set { setViewPoint(value, true); } } public void setViewPoint(Coord3d polar, bool updateView) { _viewpoint = polar; _viewpoint.y = (_viewpoint.y < -PI_div2 ? -PI_div2 : _viewpoint.y); _viewpoint.y = (_viewpoint.y > PI_div2 ? PI_div2 : _viewpoint.y); if (updateView) { Shoot(); } fireViewPointChangedEvent(new ViewPointChangedEventArgs(this, polar)); } public Coord3d getLastViewScaling() { return _scaling; } public IAxe Axe { get { return _axe; } set { _axe = value; updateBounds(); } } public bool Squared { get { return _squared; } set { _squared = value; } } public bool AxeBoxDisplayed { get { return _axeBoxDisplayed; } set { _axeBoxDisplayed = value; } } public Color BackgroundColor { get { return _bgColor; } set { _bgColor = value; } } public System.Drawing.Bitmap BackgroundImage { get { return _bgImg; } set { _bgImg = value; _bgViewport.Image = _bgImg; } } public Camera Camera { get { return _cam; } } /// <summary> /// Get the projection of this view, either CameraMode.ORTHOGONAL or CameraMode.PERSPECTIVE. /// </summary> public CameraMode CameraMode { get { return _cameraMode; } set { _cameraMode = value; } } public bool Maximized { get { return _cam.StretchToFill; } set { _cam.StretchToFill = value; } } public Scene Scene { get { return _scene; } } public System.Drawing.Rectangle SceneViewportRectangle { get { return _cam.Rectange; } } public ICanvas Canvas { get { return _canvas; } } public void addRenderer2d(IRenderer2D renderer) { _renderers.Add(renderer); } public void removeRenderer2d(IRenderer2D renderer) { _renderers.Remove(renderer); } public void addViewOnTopEventListener(IViewIsVerticalEventListener listener) { _viewOnTopListeners.Add(listener); } public void removeViewOnTopEventListener(IViewIsVerticalEventListener listener) { _viewOnTopListeners.Remove(listener); } internal void fireViewOnTopEvent(bool isOnTop) { ViewIsVerticalEventArgs e = new ViewIsVerticalEventArgs(this); if (isOnTop) { foreach (IViewIsVerticalEventListener listener in _viewOnTopListeners) { listener.ViewVerticalReached(e); } } else { foreach (IViewIsVerticalEventListener listener in _viewOnTopListeners) { listener.ViewVerticalLeft(e); } } } public void addViewPointChangedListener(IViewPointChangedListener listener) { _viewPointChangedListeners.Add(listener); } public void removeViewPointChangedListener(IViewPointChangedListener listener) { _viewPointChangedListeners.Remove(listener); } internal void fireViewPointChangedEvent(ViewPointChangedEventArgs e) { foreach (IViewPointChangedListener vp in _viewPointChangedListeners) { vp.ViewPointChanged(e); } } /// <summary> /// Select between an automatic bounding (that allows fitting the entire scene graph), or a custom bounding. /// </summary> public ViewBoundMode BoundMode { set { _boundmode = value; updateBounds(); } } /// <summary> /// Set the bounds of the view according to the current BoundMode, and orders a Camera.shoot(). /// </summary> public void updateBounds() { switch (_boundmode) { case ViewBoundMode.AUTO_FIT: lookToBox(Scene.Graph.Bounds); // set axe and camera break; case ViewBoundMode.MANUAL: lookToBox(_viewbounds); // set axe and camera break; default: throw new Exception("Unsupported bound mode : " + _boundmode); } Shoot(); } /// <summary> /// Update the bounds according to the scene graph whatever is the current /// BoundMode, and orders a shoot() if refresh is True /// </summary> /// <param name="refresh">Wether to order a shoot() or not.</param> /// <remarks></remarks> public void updateBoundsForceUpdate(bool refresh) { lookToBox(Scene.Graph.Bounds); if (refresh) { Shoot(); } } /// <summary> /// Set a manual bounding box and switch the bounding mode to /// ViewBoundMode.MANUAL, meaning that any call to updateBounds() /// will update view bounds to the current bounds. /// </summary> /// <value></value> /// <remarks>The camero.shoot is not called in this case</remarks> public BoundingBox3d BoundManual { set { _viewbounds = value; _boundmode = ViewBoundMode.MANUAL; lookToBox(_viewbounds); } } /// <summary> /// Return a 3d scaling factor that allows scaling the scene into a square /// box, according to the current ViewBoundMode. /// <p/> /// If the scene bounds are Infinite, NaN or zero, for a given dimension, the /// scaler will be set to 1 on the given dimension. /// /// @return a scaling factor for each dimension. /// </summary> internal Coord3d Squarify() { // Get the view bounds BoundingBox3d bounds = default(BoundingBox3d); switch (_boundmode) { case ViewBoundMode.AUTO_FIT: bounds = Scene.Graph.Bounds; break; case ViewBoundMode.MANUAL: bounds = _viewbounds; break; default: throw new Exception("Unsupported bound mode : " + _boundmode); } // Compute factors float xLen = (float)(bounds.xmax - bounds.xmin); float yLen = (float)(bounds.ymax - bounds.ymin); float zLen = (float)(bounds.zmax - bounds.zmin); float lmax = Math.Max(Math.Max(xLen, yLen), zLen); if (float.IsInfinity(xLen) | float.IsNaN(xLen) | xLen == 0) { xLen = 1; // throw new ArithmeticException("x scale is infinite, nan or 0"); } if (float.IsInfinity(yLen) | float.IsNaN(yLen) | yLen == 0) { yLen = 1; // throw new ArithmeticException("y scale is infinite, nan or 0"); } if (float.IsInfinity(zLen) | float.IsNaN(zLen) | zLen == 0) { zLen = 1; // throw new ArithmeticException("z scale is infinite, nan or 0"); } if (float.IsInfinity(lmax) | float.IsNaN(lmax) | lmax == 0) { lmax = 1; // throw new ArithmeticException("lmax is infinite, nan or 0"); } return new Coord3d(lmax / xLen, lmax / yLen, lmax / zLen); } #endregion #region "GL2" /// <summary> /// The init function specifies general GL settings that impact the rendering /// quality and performance (computation speed). /// <p/> /// The rendering settings are set by the Quality instance given in /// the constructor parameters. /// </summary> /// <remarks></remarks> public void Init() { InitQuality(); InitLights(); } public void InitQuality() { // Activate Depth buffer if (_quality.DepthActivated) { GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Lequal); } else { GL.Disable(EnableCap.DepthTest); } // Blending GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); // on/off is handled by each viewport (camera or image) // Activate transparency if (_quality.AlphaActivated) { GL.Enable(EnableCap.AlphaTest); if (_quality.DisableDepthBufferWhenAlpha) { GL.Disable(EnableCap.DepthTest); } } else { GL.Disable(EnableCap.AlphaTest); } // Make smooth colors for polygons (interpolate color between points) if (_quality.SmoothColor) { GL.ShadeModel(ShadingModel.Smooth); } else { GL.ShadeModel(ShadingModel.Flat); } // Make smoothing setting if (_quality.SmoothLine) { GL.Enable(EnableCap.LineSmooth); GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest); } else { GL.Disable(EnableCap.LineSmooth); } if (_quality.SmoothPoint) { GL.Enable(EnableCap.PointSmooth); GL.Hint(HintTarget.PointSmoothHint, HintMode.Fastest); } else { GL.Disable(EnableCap.PointSmooth); } } public void InitLights() { // Init light Scene.LightSet.Init(); Scene.LightSet.Enable(); } // Clear color and depth buffer (same as ClearColorAndDepth) public void Clear() { ClearColorAndDepth(); } // Clear color and depth buffer (same as Clear) public void ClearColorAndDepth() { GL.ClearColor((float)_bgColor.r, (float)_bgColor.g, (float)_bgColor.b, (float)_bgColor.a); // clear with background GL.ClearDepth(1); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); } public virtual void Render() { RenderBackground(0, 1); RenderScene(); RenderOverlay(); if (_dimensionDirty) { _dimensionDirty = false; } } public void RenderBackground(float left, float right) { if ((_bgImg != null)) { _bgViewport.SetViewPort(_canvas.RendererWidth, _canvas.RendererHeight, left, right); _bgViewport.Render(); } } public void RenderBackground(ViewPort viewport) { if ((_bgImg != null)) { _bgViewport.SetViewPort(viewport); _bgViewport.Render(); } } public void RenderScene() { RenderScene(new ViewPort(_canvas.RendererWidth, _canvas.RendererHeight)); } public void RenderScene(float left, float right) { RenderScene(new ViewPort(_canvas.RendererWidth, _canvas.RendererHeight, (int)left, (int)right)); } public void RenderScene(ViewPort viewport) { UpdateQuality(); UpdateCamera(viewport, computeScaling()); RenderAxeBox(); RenderSceneGraph(); } public void UpdateQuality() { if (_quality.AlphaActivated) { GL.Enable(EnableCap.Blend); } else { GL.Disable(EnableCap.Blend); } } public BoundingBox3d computeScaling() { //-- Scale the scene's view ------------------- if (Squared) { _scaling = Squarify(); } else { _scaling = (Coord3d)Coord3d.IDENTITY.Clone(); } // Compute the bounds for computing cam distance, clipping planes, etc ... if ((_targetBox == null)) { _targetBox = new BoundingBox3d(0, 1, 0, 1, 0, 1); } BoundingBox3d boundsScaled = new BoundingBox3d(); boundsScaled.Add(_targetBox.scale(_scaling)); if (MAINTAIN_ALL_OBJECTS_IN_VIEW) { boundsScaled.Add(Scene.Graph.Bounds.scale(_scaling)); } return boundsScaled; } public void UpdateCamera(ViewPort viewport, BoundingBox3d boundsScaled) { UpdateCamera(viewport, boundsScaled, (float)boundsScaled.getRadius()); } public void UpdateCamera(ViewPort viewport, BoundingBox3d boundsScaled, float sceneRadiusScaled) { Coord3d target = _center.multiply(_scaling); Coord3d eye = default(Coord3d); _viewpoint.z = sceneRadiusScaled * 2; // maintain a reasonnable distance to the scene for viewing it switch (_viewmode) { case Modes.ViewPositionMode.FREE: eye = _viewpoint.cartesian().@add(target); break; case Modes.ViewPositionMode.TOP: eye = _viewpoint; eye.x = -PI_div2; // on x eye.y = PI_div2; // on top eye = eye.cartesian().@add(target); break; case Modes.ViewPositionMode.PROFILE: eye = _viewpoint; eye.y = 0; eye = eye.cartesian().@add(target); break; default: throw new Exception("Unsupported viewmode : " + _viewmode); } Coord3d up = default(Coord3d); if (Math.Abs(_viewpoint.y) == PI_div2) { // handle up vector Coord2d direction = new Coord2d(_viewpoint.x, _viewpoint.y).cartesian(); if (_viewpoint.y > 0) { // on top up = new Coord3d(-direction.x, -direction.y, 0); } else { up = new Coord3d(direction.x, direction.y, 0); } // handle "on-top" events if (!_wasOnTopAtLastRendering) { _wasOnTopAtLastRendering = true; fireViewOnTopEvent(true); } } else { // handle up vector up = new Coord3d(0, 0, 1); // handle "on-top" events if (_wasOnTopAtLastRendering) { _wasOnTopAtLastRendering = false; fireViewOnTopEvent(false); } } // Apply camera settings _cam.Target = target; _cam.Up = up; _cam.Eye = eye; // Set rendering volume if (_viewmode == Modes.ViewPositionMode.TOP) { _cam.RenderingSphereRadius = (float)(Math.Max(boundsScaled.xmax - boundsScaled.xmin, boundsScaled.ymax - boundsScaled.ymin) / 2); // correctCameraPositionForIncludingTextLabels(viewport) ' quite experimental ! } else { _cam.RenderingSphereRadius = sceneRadiusScaled; } // Setup camera (i.e. projection matrix) //cam.setViewPort(canvas.getRendererWidth(), // canvas.getRendererHeight(), left, right); _cam.SetViewPort(viewport); _cam.shoot(_cameraMode); } public void RenderAxeBox() { if (_axeBoxDisplayed) { GL.MatrixMode(MatrixMode.Modelview); _scene.LightSet.Disable(); _axe.setScale(_scaling); _axe.Draw(_cam); // for debug if (DISPLAY_AXE_WHOLE_BOUNDS) { AxeBox abox = (AxeBox)_axe; BoundingBox3d box = abox.WholeBounds; Parallelepiped p = new Parallelepiped(box); p.FaceDisplayed = false; p.WireframeColor = Color.MAGENTA; p.WireframeDisplayed = true; p.Draw(_cam); } _scene.LightSet.Enable(); } } public void RenderSceneGraph() { RenderSceneGraph(true); } public void RenderSceneGraph(bool light) { if (light) { Scene.LightSet.apply(_scaling); // gl.glEnable(GL2.GL_LIGHTING); // gl.glEnable(GL2.GL_LIGHT0); // gl.glDisable(GL2.GL_LIGHTING); } Transform.Transform transform = new Transform.Transform(new nzy3D.Plot3D.Transform.Scale(_scaling)); Scene.Graph.Transform = transform; Scene.Graph.Draw(_cam); } public void RenderOverlay() { RenderOverlay(new ViewPort(0, 0, _canvas.RendererWidth, _canvas.RendererHeight)); } /// <summary> /// Renders all provided Tooltips and Renderer2ds on top of /// the scene. /// /// Due to the behaviour of the Overlay implementation, Java2d /// geometries must be drawn relative to the Chart's /// IScreenCanvas, BUT will then be stretched to fit in the /// Camera's viewport. This bug is very important to consider, since /// the Camera's viewport may not occupy the full IScreenCanvas. /// Indeed, when View is not maximized (like the default behaviour), the /// viewport remains square and centered in the canvas, meaning the Overlay /// won't cover the full canvas area. /// /// In other words, the following piece of code draws a border around the /// View, and not around the complete chart canvas, although queried /// to occupy chart canvas dimensions: /// /// g2d.drawRect(1, 1, chart.getCanvas().getRendererWidth()-2, /// chart.getCanvas().getRendererHeight()-2); /// /// renderOverlay() must be called while the OpenGL2 context for the /// drawable is current, and after the OpenGL2 scene has been rendered. /// </summary> /// <param name="viewport"></param> /// <remarks></remarks> public void RenderOverlay(ViewPort viewport) { // NOT Implemented so far } internal void correctCameraPositionForIncludingTextLabels(ViewPort viewport) { _cam.SetViewPort(viewport); _cam.shoot(_cameraMode); _axe.Draw(_cam); Clear(); AxeBox abox = (AxeBox)_axe; BoundingBox3d newBounds = abox.WholeBounds.scale(_scaling); if (_viewmode == Modes.ViewPositionMode.TOP) { float radius = (float)Math.Max(newBounds.xmax - newBounds.xmin, newBounds.ymax - newBounds.ymin); radius += radius * STRETCH_RATIO; _cam.RenderingSphereRadius = radius; } else { _cam.RenderingSphereRadius = (float)newBounds.getRadius(); Coord3d target = newBounds.getCenter(); Coord3d eye = _viewpoint.cartesian().@add(target); _cam.Target = target; _cam.Eye = eye; } } #endregion } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
//------------------------------------------------------------------------------ // <copyright file="HttpRequestBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web { using System; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Security.Authentication.ExtendedProtection; using System.Security.Principal; using System.Text; using System.Threading; using System.Web.Routing; [TypeForwardedFrom("System.Web.Abstractions, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public abstract class HttpRequestBase { [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Matches HttpRequest class")] public virtual String[] AcceptTypes { get { throw new NotImplementedException(); } } public virtual String ApplicationPath { get { throw new NotImplementedException(); } } [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", MessageId="ID")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID")] public virtual String AnonymousID { get { throw new NotImplementedException(); } } public virtual String AppRelativeCurrentExecutionFilePath { get { throw new NotImplementedException(); } } public virtual HttpBrowserCapabilitiesBase Browser { get { throw new NotImplementedException(); } } public virtual ChannelBinding HttpChannelBinding { get { throw new NotImplementedException(); } } public virtual HttpClientCertificate ClientCertificate { get { throw new NotImplementedException(); } } public virtual Encoding ContentEncoding { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual int ContentLength { get { throw new NotImplementedException(); } } public virtual String ContentType { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual HttpCookieCollection Cookies { get { throw new NotImplementedException(); } } public virtual String CurrentExecutionFilePath { get { throw new NotImplementedException(); } } public virtual string CurrentExecutionFilePathExtension { get { throw new NotImplementedException(); } } public virtual String FilePath { get { throw new NotImplementedException(); } } public virtual HttpFileCollectionBase Files { get { throw new NotImplementedException(); } } public virtual Stream Filter { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual NameValueCollection Form { get { throw new NotImplementedException(); } } public virtual String HttpMethod { get { throw new NotImplementedException(); } } public virtual Stream InputStream { get { throw new NotImplementedException(); } } public virtual bool IsAuthenticated { get { throw new NotImplementedException(); } } public virtual bool IsLocal { get { throw new NotImplementedException(); } } public virtual bool IsSecureConnection { get { throw new NotImplementedException(); } } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpRequest class")] public virtual WindowsIdentity LogonUserIdentity { get { throw new NotImplementedException(); } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Matches HttpRequest class")] public virtual NameValueCollection Params { get { throw new NotImplementedException(); } } public virtual String Path { get { throw new NotImplementedException(); } } public virtual String PathInfo { get { throw new NotImplementedException(); } } public virtual String PhysicalApplicationPath { get { throw new NotImplementedException(); } } public virtual String PhysicalPath { get { throw new NotImplementedException(); } } [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Matches HttpRequest class")] public virtual String RawUrl { get { throw new NotImplementedException(); } } public virtual ReadEntityBodyMode ReadEntityBodyMode { get { throw new NotImplementedException(); } } public virtual RequestContext RequestContext { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual String RequestType { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual NameValueCollection ServerVariables { get { throw new NotImplementedException(); } } public virtual CancellationToken TimedOutToken { get { throw new NotImplementedException(); } } public virtual ITlsTokenBindingInfo TlsTokenBindingInfo { get { throw new NotImplementedException(); } } public virtual int TotalBytes { get { throw new NotImplementedException(); } } public virtual UnvalidatedRequestValuesBase Unvalidated { get { throw new NotImplementedException(); } } public virtual Uri Url { get { throw new NotImplementedException(); } } public virtual Uri UrlReferrer { get { throw new NotImplementedException(); } } public virtual String UserAgent { get { throw new NotImplementedException(); } } [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Matches HttpRequest class")] public virtual String[] UserLanguages { get { throw new NotImplementedException(); } } public virtual String UserHostAddress { get { throw new NotImplementedException(); } } public virtual String UserHostName { get { throw new NotImplementedException(); } } public virtual NameValueCollection Headers { get { throw new NotImplementedException(); } } public virtual NameValueCollection QueryString { get { throw new NotImplementedException(); } } public virtual String this[String key] { get { throw new NotImplementedException(); } } public virtual void Abort() { throw new NotImplementedException(); } public virtual byte[] BinaryRead(int count) { throw new NotImplementedException(); } public virtual Stream GetBufferedInputStream() { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bufferless", Justification = "Inline with HttpRequest.GetBufferlessInputStream")] public virtual Stream GetBufferlessInputStream() { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bufferless", Justification = "Inline with HttpRequest.GetBufferlessInputStream")] public virtual Stream GetBufferlessInputStream(bool disableMaxRequestLength) { throw new NotImplementedException(); } public virtual void InsertEntityBody() { throw new NotImplementedException(); } public virtual void InsertEntityBody(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public virtual int[] MapImageCoordinates(String imageFieldName) { throw new NotImplementedException(); } public virtual double[] MapRawImageCoordinates(String imageFieldName) { throw new NotImplementedException(); } public virtual String MapPath(String virtualPath) { throw new NotImplementedException(); } public virtual String MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping) { throw new NotImplementedException(); } public virtual void ValidateInput() { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpRequest class")] public virtual void SaveAs(String filename, bool includeHeaders) { throw new NotImplementedException(); } } }
using Lucene.Net.Codecs.SimpleText; using Lucene.Net.Documents; using Lucene.Net.Randomized.Generators; using Lucene.Net.Search; using Lucene.Net.Support; using Lucene.Net.Support.Threading; using NUnit.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index { using BytesRef = Lucene.Net.Util.BytesRef; using Codec = Lucene.Net.Codecs.Codec; using Directory = Lucene.Net.Store.Directory; //using SimpleTextCodec = Lucene.Net.Codecs.simpletext.SimpleTextCodec; using Document = Documents.Document; using DoubleField = DoubleField; using Field = Field; using FieldType = FieldType; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using Int32Field = Int32Field; using Int64Field = Int64Field; using Lucene46Codec = Lucene.Net.Codecs.Lucene46.Lucene46Codec; using MMapDirectory = Lucene.Net.Store.MMapDirectory; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using NumericRangeQuery = Lucene.Net.Search.NumericRangeQuery; using Query = Lucene.Net.Search.Query; using SingleField = SingleField; using StoredField = StoredField; using StringField = StringField; using TermQuery = Lucene.Net.Search.TermQuery; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; using TopDocs = Lucene.Net.Search.TopDocs; /// <summary> /// Base class aiming at testing <seealso cref="StoredFieldsFormat"/>. /// To test a new format, all you need is to register a new <seealso cref="Codec"/> which /// uses it and extend this class and override <seealso cref="#getCodec()"/>. /// @lucene.experimental /// </summary> public abstract class BaseStoredFieldsFormatTestCase : BaseIndexFileFormatTestCase { protected internal override void AddRandomFields(Document d) { int numValues = Random().Next(3); for (int i = 0; i < numValues; ++i) { d.Add(new StoredField("f", TestUtil.RandomSimpleString(Random(), 100))); } } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestRandomStoredFields() { Directory dir = NewDirectory(); Random rand = Random(); RandomIndexWriter w = new RandomIndexWriter(rand, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(TestUtil.NextInt(rand, 5, 20))); //w.w.setNoCFSRatio(0.0); int docCount = AtLeast(200); int fieldCount = TestUtil.NextInt(rand, 1, 5); IList<int?> fieldIDs = new List<int?>(); FieldType customType = new FieldType(TextField.TYPE_STORED); customType.IsTokenized = false; Field idField = NewField("id", "", customType); for (int i = 0; i < fieldCount; i++) { fieldIDs.Add(i); } IDictionary<string, Document> docs = new Dictionary<string, Document>(); if (VERBOSE) { Console.WriteLine("TEST: build index docCount=" + docCount); } FieldType customType2 = new FieldType(); customType2.IsStored = true; for (int i = 0; i < docCount; i++) { Document doc = new Document(); doc.Add(idField); string id = "" + i; idField.SetStringValue(id); docs[id] = doc; if (VERBOSE) { Console.WriteLine("TEST: add doc id=" + id); } foreach (int field in fieldIDs) { string s; if (rand.Next(4) != 3) { s = TestUtil.RandomUnicodeString(rand, 1000); doc.Add(NewField("f" + field, s, customType2)); } else { s = null; } } w.AddDocument(doc); if (rand.Next(50) == 17) { // mixup binding of field name -> Number every so often Collections.Shuffle(fieldIDs); } if (rand.Next(5) == 3 && i > 0) { string delID = "" + rand.Next(i); if (VERBOSE) { Console.WriteLine("TEST: delete doc id=" + delID); } w.DeleteDocuments(new Term("id", delID)); docs.Remove(delID); } } if (VERBOSE) { Console.WriteLine("TEST: " + docs.Count + " docs in index; now load fields"); } if (docs.Count > 0) { string[] idsList = docs.Keys.ToArray(/*new string[docs.Count]*/); for (int x = 0; x < 2; x++) { IndexReader r = w.Reader; IndexSearcher s = NewSearcher(r); if (VERBOSE) { Console.WriteLine("TEST: cycle x=" + x + " r=" + r); } int num = AtLeast(1000); for (int iter = 0; iter < num; iter++) { string testID = idsList[rand.Next(idsList.Length)]; if (VERBOSE) { Console.WriteLine("TEST: test id=" + testID); } TopDocs hits = s.Search(new TermQuery(new Term("id", testID)), 1); Assert.AreEqual(1, hits.TotalHits); Document doc = r.Document(hits.ScoreDocs[0].Doc); Document docExp = docs[testID]; for (int i = 0; i < fieldCount; i++) { assertEquals("doc " + testID + ", field f" + fieldCount + " is wrong", docExp.Get("f" + i), doc.Get("f" + i)); } } r.Dispose(); w.ForceMerge(1); } } w.Dispose(); dir.Dispose(); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass // LUCENE-1727: make sure doc fields are stored in order public virtual void TestStoredFieldsOrder() { Directory d = NewDirectory(); IndexWriter w = new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document doc = new Document(); FieldType customType = new FieldType(); customType.IsStored = true; doc.Add(NewField("zzz", "a b c", customType)); doc.Add(NewField("aaa", "a b c", customType)); doc.Add(NewField("zzz", "1 2 3", customType)); w.AddDocument(doc); IndexReader r = w.GetReader(); Document doc2 = r.Document(0); IEnumerator<IIndexableField> it = doc2.Fields.GetEnumerator(); Assert.IsTrue(it.MoveNext()); Field f = (Field)it.Current; Assert.AreEqual(f.Name, "zzz"); Assert.AreEqual(f.GetStringValue(), "a b c"); Assert.IsTrue(it.MoveNext()); f = (Field)it.Current; Assert.AreEqual(f.Name, "aaa"); Assert.AreEqual(f.GetStringValue(), "a b c"); Assert.IsTrue(it.MoveNext()); f = (Field)it.Current; Assert.AreEqual(f.Name, "zzz"); Assert.AreEqual(f.GetStringValue(), "1 2 3"); Assert.IsFalse(it.MoveNext()); r.Dispose(); w.Dispose(); d.Dispose(); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass // LUCENE-1219 public virtual void TestBinaryFieldOffsetLength() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); var b = new byte[50]; for (int i = 0; i < 50; i++) { b[i] = (byte)(i + 77); } Document doc = new Document(); Field f = new StoredField("binary", b, 10, 17); var bx = f.GetBinaryValue().Bytes; Assert.IsTrue(bx != null); Assert.AreEqual(50, bx.Length); Assert.AreEqual(10, f.GetBinaryValue().Offset); Assert.AreEqual(17, f.GetBinaryValue().Length); doc.Add(f); w.AddDocument(doc); w.Dispose(); IndexReader ir = DirectoryReader.Open(dir); Document doc2 = ir.Document(0); IIndexableField f2 = doc2.GetField("binary"); b = f2.GetBinaryValue().Bytes; Assert.IsTrue(b != null); Assert.AreEqual(17, b.Length, 17); Assert.AreEqual(87, b[0]); ir.Dispose(); dir.Dispose(); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestNumericField() { Directory dir = NewDirectory(); var w = new RandomIndexWriter(Random(), dir, ClassEnvRule.similarity, ClassEnvRule.timeZone); var numDocs = AtLeast(500); var answers = new object[numDocs]; NumericType[] typeAnswers = new NumericType[numDocs]; for (int id = 0; id < numDocs; id++) { Document doc = new Document(); Field nf; Field sf; object answer; NumericType typeAnswer; if (Random().NextBoolean()) { // float/double if (Random().NextBoolean()) { float f = Random().NextFloat(); answer = Convert.ToSingle(f, CultureInfo.InvariantCulture); nf = new SingleField("nf", f, Field.Store.NO); sf = new StoredField("nf", f); typeAnswer = NumericType.SINGLE; } else { double d = Random().NextDouble(); answer = Convert.ToDouble(d, CultureInfo.InvariantCulture); nf = new DoubleField("nf", d, Field.Store.NO); sf = new StoredField("nf", d); typeAnswer = NumericType.DOUBLE; } } else { // int/long if (Random().NextBoolean()) { int i = Random().Next(); answer = Convert.ToInt32(i, CultureInfo.InvariantCulture); nf = new Int32Field("nf", i, Field.Store.NO); sf = new StoredField("nf", i); typeAnswer = NumericType.INT32; } else { long l = Random().NextLong(); answer = Convert.ToInt64(l, CultureInfo.InvariantCulture); nf = new Int64Field("nf", l, Field.Store.NO); sf = new StoredField("nf", l); typeAnswer = NumericType.INT64; } } doc.Add(nf); doc.Add(sf); answers[id] = answer; typeAnswers[id] = typeAnswer; FieldType ft = new FieldType(Int32Field.TYPE_STORED); ft.NumericPrecisionStep = int.MaxValue; doc.Add(new Int32Field("id", id, ft)); w.AddDocument(doc); } DirectoryReader r = w.Reader; w.Dispose(); Assert.AreEqual(numDocs, r.NumDocs); foreach (AtomicReaderContext ctx in r.Leaves) { AtomicReader sub = (AtomicReader)ctx.Reader; FieldCache.Int32s ids = FieldCache.DEFAULT.GetInt32s(sub, "id", false); for (int docID = 0; docID < sub.NumDocs; docID++) { Document doc = sub.Document(docID); Field f = doc.GetField<Field>("nf"); Assert.IsTrue(f is StoredField, "got f=" + f); #pragma warning disable 612, 618 Assert.AreEqual(answers[ids.Get(docID)], f.GetNumericValue()); #pragma warning restore 612, 618 } } r.Dispose(); dir.Dispose(); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestIndexedBit() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir, ClassEnvRule.similarity, ClassEnvRule.timeZone); Document doc = new Document(); FieldType onlyStored = new FieldType(); onlyStored.IsStored = true; doc.Add(new Field("field", "value", onlyStored)); doc.Add(new StringField("field2", "value", Field.Store.YES)); w.AddDocument(doc); IndexReader r = w.Reader; w.Dispose(); Assert.IsFalse(r.Document(0).GetField("field").IndexableFieldType.IsIndexed); Assert.IsTrue(r.Document(0).GetField("field2").IndexableFieldType.IsIndexed); r.Dispose(); dir.Dispose(); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestReadSkip() { Directory dir = NewDirectory(); IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); iwConf.SetMaxBufferedDocs(RandomInts.NextIntBetween(Random(), 2, 30)); RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwConf); FieldType ft = new FieldType(); ft.IsStored = true; ft.Freeze(); string @string = TestUtil.RandomSimpleString(Random(), 50); var bytes = @string.GetBytes(Encoding.UTF8); long l = Random().NextBoolean() ? Random().Next(42) : Random().NextLong(); int i = Random().NextBoolean() ? Random().Next(42) : Random().Next(); float f = Random().NextFloat(); double d = Random().NextDouble(); IList<Field> fields = Arrays.AsList(new Field("bytes", bytes, ft), new Field("string", @string, ft), new Int64Field("long", l, Field.Store.YES), new Int32Field("int", i, Field.Store.YES), new SingleField("float", f, Field.Store.YES), new DoubleField("double", d, Field.Store.YES) ); for (int k = 0; k < 100; ++k) { Document doc = new Document(); foreach (Field fld in fields) { doc.Add(fld); } iw.w.AddDocument(doc); } iw.Commit(); DirectoryReader reader = DirectoryReader.Open(dir); int docID = Random().Next(100); foreach (Field fld in fields) { string fldName = fld.Name; Document sDoc = reader.Document(docID, Collections.Singleton(fldName)); IIndexableField sField = sDoc.GetField(fldName); if (typeof(Field) == fld.GetType()) { Assert.AreEqual(fld.GetBinaryValue(), sField.GetBinaryValue()); Assert.AreEqual(fld.GetStringValue(), sField.GetStringValue()); } else { #pragma warning disable 612, 618 Assert.AreEqual(fld.GetNumericValue(), sField.GetNumericValue()); #pragma warning restore 612, 618 } } reader.Dispose(); iw.Dispose(); dir.Dispose(); } // [Test, Timeout(300000)] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestEmptyDocs() { Directory dir = NewDirectory(); IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); iwConf.SetMaxBufferedDocs(RandomInts.NextIntBetween(Random(), 2, 30)); RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwConf); // make sure that the fact that documents might be empty is not a problem Document emptyDoc = new Document(); int numDocs = Random().NextBoolean() ? 1 : AtLeast(1000); for (int i = 0; i < numDocs; ++i) { iw.AddDocument(emptyDoc); } iw.Commit(); DirectoryReader rd = DirectoryReader.Open(dir); for (int i = 0; i < numDocs; ++i) { Document doc = rd.Document(i); Assert.IsNotNull(doc); Assert.IsTrue(doc.Fields.Count <= 0); } rd.Dispose(); iw.Dispose(); dir.Dispose(); } // [Test, Timeout(300000)] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestConcurrentReads() { Directory dir = NewDirectory(); IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); iwConf.SetMaxBufferedDocs(RandomInts.NextIntBetween(Random(), 2, 30)); RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwConf); // make sure the readers are properly cloned Document doc = new Document(); Field field = new StringField("fld", "", Field.Store.YES); doc.Add(field); int numDocs = AtLeast(1000); for (int i = 0; i < numDocs; ++i) { field.SetStringValue("" + i); iw.AddDocument(doc); } iw.Commit(); DirectoryReader rd = DirectoryReader.Open(dir); IndexSearcher searcher = new IndexSearcher(rd); int concurrentReads = AtLeast(5); int readsPerThread = AtLeast(50); IList<ThreadClass> readThreads = new List<ThreadClass>(); AtomicObject<Exception> ex = new AtomicObject<Exception>(); for (int i = 0; i < concurrentReads; ++i) { readThreads.Add(new ThreadAnonymousInnerClassHelper(numDocs, rd, searcher, readsPerThread, ex, i)); } foreach (ThreadClass thread in readThreads) { thread.Start(); } foreach (ThreadClass thread in readThreads) { thread.Join(); } rd.Dispose(); if (ex.Value != null) { throw ex.Value; } iw.Dispose(); dir.Dispose(); } private class ThreadAnonymousInnerClassHelper : ThreadClass { private int NumDocs; private readonly DirectoryReader Rd; private readonly IndexSearcher Searcher; private int ReadsPerThread; private AtomicObject<Exception> Ex; private int i; private readonly int[] queries; public ThreadAnonymousInnerClassHelper(int numDocs, DirectoryReader rd, IndexSearcher searcher, int readsPerThread, AtomicObject<Exception> ex, int i) { this.NumDocs = numDocs; this.Rd = rd; this.Searcher = searcher; this.ReadsPerThread = readsPerThread; this.Ex = ex; this.i = i; queries = new int[ReadsPerThread]; for (int j = 0; j < queries.Length; ++j) { queries[j] = Random().Next(NumDocs); } } public override void Run() { foreach (int q in queries) { Query query = new TermQuery(new Term("fld", "" + q)); try { TopDocs topDocs = Searcher.Search(query, 1); if (topDocs.TotalHits != 1) { Console.WriteLine(query); throw new InvalidOperationException("Expected 1 hit, got " + topDocs.TotalHits); } Document sdoc = Rd.Document(topDocs.ScoreDocs[0].Doc); if (sdoc == null || sdoc.Get("fld") == null) { throw new InvalidOperationException("Could not find document " + q); } if (!Convert.ToString(q, CultureInfo.InvariantCulture).Equals(sdoc.Get("fld"), StringComparison.Ordinal)) { throw new InvalidOperationException("Expected " + q + ", but got " + sdoc.Get("fld")); } } catch (Exception e) { Ex.Value = e; } } } } private static byte[] RandomByteArray(int length, int max) { var result = new byte[length]; for (int i = 0; i < length; ++i) { result[i] = (byte)Random().Next(max); } return result; } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestWriteReadMerge() { // get another codec, other than the default: so we are merging segments across different codecs Codec otherCodec; if ("SimpleText".Equals(Codec.Default.Name, StringComparison.Ordinal)) { otherCodec = new Lucene46Codec(); } else { otherCodec = new SimpleTextCodec(); } Directory dir = NewDirectory(); IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); iwConf.SetMaxBufferedDocs(RandomInts.NextIntBetween(Random(), 2, 30)); RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, (IndexWriterConfig)iwConf.Clone()); int docCount = AtLeast(200); var data = new byte[docCount][][]; for (int i = 0; i < docCount; ++i) { int fieldCount = Rarely() ? RandomInts.NextIntBetween(Random(), 1, 500) : RandomInts.NextIntBetween(Random(), 1, 5); data[i] = new byte[fieldCount][]; for (int j = 0; j < fieldCount; ++j) { int length = Rarely() ? Random().Next(1000) : Random().Next(10); int max = Rarely() ? 256 : 2; data[i][j] = RandomByteArray(length, max); } } FieldType type = new FieldType(StringField.TYPE_STORED); type.IsIndexed = false; type.Freeze(); Int32Field id = new Int32Field("id", 0, Field.Store.YES); for (int i = 0; i < data.Length; ++i) { Document doc = new Document(); doc.Add(id); id.SetInt32Value(i); for (int j = 0; j < data[i].Length; ++j) { Field f = new Field("bytes" + j, data[i][j], type); doc.Add(f); } iw.w.AddDocument(doc); if (Random().NextBoolean() && (i % (data.Length / 10) == 0)) { iw.w.Dispose(); // test merging against a non-compressing codec if (iwConf.Codec == otherCodec) { iwConf.SetCodec(Codec.Default); } else { iwConf.SetCodec(otherCodec); } iw = new RandomIndexWriter(Random(), dir, (IndexWriterConfig)iwConf.Clone()); } } for (int i = 0; i < 10; ++i) { int min = Random().Next(data.Length); int max = min + Random().Next(20); iw.DeleteDocuments(NumericRangeQuery.NewInt32Range("id", min, max, true, false)); } iw.ForceMerge(2); // force merges with deletions iw.Commit(); DirectoryReader ir = DirectoryReader.Open(dir); Assert.IsTrue(ir.NumDocs > 0); int numDocs = 0; for (int i = 0; i < ir.MaxDoc; ++i) { Document doc = ir.Document(i); if (doc == null) { continue; } ++numDocs; int docId = (int)doc.GetField("id").GetInt32Value(); Assert.AreEqual(data[docId].Length + 1, doc.Fields.Count); for (int j = 0; j < data[docId].Length; ++j) { var arr = data[docId][j]; BytesRef arr2Ref = doc.GetBinaryValue("bytes" + j); var arr2 = Arrays.CopyOfRange(arr2Ref.Bytes, arr2Ref.Offset, arr2Ref.Offset + arr2Ref.Length); Assert.AreEqual(arr, arr2); } } Assert.IsTrue(ir.NumDocs <= numDocs); ir.Dispose(); iw.DeleteAll(); iw.Commit(); iw.ForceMerge(1); iw.Dispose(); dir.Dispose(); } // [Test, LongRunningTest, Timeout(int.MaxValue)] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestBigDocuments() { // "big" as "much bigger than the chunk size" // for this test we force a FS dir // we can't just use newFSDirectory, because this test doesn't really index anything. // so if we get NRTCachingDir+SimpleText, we make massive stored fields and OOM (LUCENE-4484) Directory dir = new MockDirectoryWrapper(Random(), new MMapDirectory(CreateTempDir("testBigDocuments"))); IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); iwConf.SetMaxBufferedDocs(RandomInts.NextIntBetween(Random(), 2, 30)); RandomIndexWriter iw = new RandomIndexWriter(Random(), dir, iwConf); if (dir is MockDirectoryWrapper) { ((MockDirectoryWrapper)dir).Throttling = MockDirectoryWrapper.Throttling_e.NEVER; } Document emptyDoc = new Document(); // emptyDoc Document bigDoc1 = new Document(); // lot of small fields Document bigDoc2 = new Document(); // 1 very big field Field idField = new StringField("id", "", Field.Store.NO); emptyDoc.Add(idField); bigDoc1.Add(idField); bigDoc2.Add(idField); FieldType onlyStored = new FieldType(StringField.TYPE_STORED); onlyStored.IsIndexed = false; Field smallField = new Field("fld", RandomByteArray(Random().Next(10), 256), onlyStored); int numFields = RandomInts.NextIntBetween(Random(), 500000, 1000000); for (int i = 0; i < numFields; ++i) { bigDoc1.Add(smallField); } Field bigField = new Field("fld", RandomByteArray(RandomInts.NextIntBetween(Random(), 1000000, 5000000), 2), onlyStored); bigDoc2.Add(bigField); int numDocs = AtLeast(5); Document[] docs = new Document[numDocs]; for (int i = 0; i < numDocs; ++i) { docs[i] = RandomInts.RandomFrom(Random(), Arrays.AsList(emptyDoc, bigDoc1, bigDoc2)); } for (int i = 0; i < numDocs; ++i) { idField.SetStringValue("" + i); iw.AddDocument(docs[i]); if (Random().Next(numDocs) == 0) { iw.Commit(); } } iw.Commit(); iw.ForceMerge(1); // look at what happens when big docs are merged DirectoryReader rd = DirectoryReader.Open(dir); IndexSearcher searcher = new IndexSearcher(rd); for (int i = 0; i < numDocs; ++i) { Query query = new TermQuery(new Term("id", "" + i)); TopDocs topDocs = searcher.Search(query, 1); Assert.AreEqual(1, topDocs.TotalHits, "" + i); Document doc = rd.Document(topDocs.ScoreDocs[0].Doc); Assert.IsNotNull(doc); IIndexableField[] fieldValues = doc.GetFields("fld"); Assert.AreEqual(docs[i].GetFields("fld").Length, fieldValues.Length); if (fieldValues.Length > 0) { Assert.AreEqual(docs[i].GetFields("fld")[0].GetBinaryValue(), fieldValues[0].GetBinaryValue()); } } rd.Dispose(); iw.Dispose(); dir.Dispose(); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestBulkMergeWithDeletes() { int numDocs = AtLeast(200); Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NoMergePolicy.COMPOUND_FILES)); for (int i = 0; i < numDocs; ++i) { Document doc = new Document(); doc.Add(new StringField("id", Convert.ToString(i, CultureInfo.InvariantCulture), Field.Store.YES)); doc.Add(new StoredField("f", TestUtil.RandomSimpleString(Random()))); w.AddDocument(doc); } int deleteCount = TestUtil.NextInt(Random(), 5, numDocs); for (int i = 0; i < deleteCount; ++i) { int id = Random().Next(numDocs); w.DeleteDocuments(new Term("id", Convert.ToString(id, CultureInfo.InvariantCulture))); } w.Commit(); w.Dispose(); w = new RandomIndexWriter(Random(), dir, ClassEnvRule.similarity, ClassEnvRule.timeZone); w.ForceMerge(TestUtil.NextInt(Random(), 1, 3)); w.Commit(); w.Dispose(); TestUtil.CheckIndex(dir); dir.Dispose(); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Workflow.Activities { using System; using System.ComponentModel; using System.Drawing.Design; using System.Diagnostics.CodeAnalysis; using System.Net.Security; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Description; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Compiler; using System.Workflow.Activities.Design; [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class TypedOperationInfo : OperationInfoBase { [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] internal static readonly DependencyProperty ContractTypeProperty = DependencyProperty.Register("ContractType", typeof(Type), typeof(TypedOperationInfo), new PropertyMetadata(null, DependencyPropertyOptions.Metadata)); public TypedOperationInfo() { } public TypedOperationInfo(Type contractType, string operationName) { if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractType"); } if (string.IsNullOrEmpty(operationName)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("operationName", SR2.GetString(SR2.Error_ArgumentValueNullOrEmptyString)); } this.ContractType = contractType; this.Name = operationName; } public Type ContractType { get { return (Type) this.GetValue(TypedOperationInfo.ContractTypeProperty); } set { this.SetValue(TypedOperationInfo.ContractTypeProperty, value); } } public override OperationInfoBase Clone() { TypedOperationInfo clonedOperation = (TypedOperationInfo) base.Clone(); clonedOperation.ContractType = this.ContractType; return clonedOperation; } public override bool Equals(object obj) { if (!base.Equals(obj)) { return false; } TypedOperationInfo operationInfo = obj as TypedOperationInfo; if (operationInfo == null) { return false; } if (this.ContractType != operationInfo.ContractType) { return false; } return true; } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { string returnValue = string.Empty; if (!string.IsNullOrEmpty(this.Name)) { returnValue = this.Name; if (this.ContractType != null) { returnValue = this.ContractType.FullName + "." + returnValue; } } return returnValue; } protected internal override string GetContractFullName(IServiceProvider provider) { if (this.ContractType != null) { return this.ContractType.FullName; } return string.Empty; } internal protected override Type GetContractType(IServiceProvider provider) { if (this.ContractType == null) { return null; } ITypeProvider typeProvider = null; if (provider != null) { typeProvider = provider.GetService(typeof(ITypeProvider)) as ITypeProvider; } Type contractType = this.ContractType; if (!this.IsReadOnly && contractType != null && typeProvider != null) { //Get the type from TypeProvider in case the type definition has changed in the local assembly. // the refresh is needed if contractType is a designtime type or is in the runtime type from the built assembly if (contractType is DesignTimeType || (typeProvider.LocalAssembly != null && typeProvider.LocalAssembly.Equals(contractType.Assembly))) { Type currentDesignTimeType = typeProvider.GetType(contractType.AssemblyQualifiedName); if (currentDesignTimeType != null) { this.ContractType = currentDesignTimeType; this.RemoveProperty(OperationInfoBase.MethodInfoProperty); } } } return this.ContractType; } internal protected override bool GetIsOneWay(IServiceProvider provider) { MethodInfo methodInfo = this.GetMethodInfo(provider); if (methodInfo != null) { object[] operationContractAttribs = methodInfo.GetCustomAttributes(typeof(OperationContractAttribute), true); if (operationContractAttribs != null && operationContractAttribs.Length > 0) { if (operationContractAttribs[0] is OperationContractAttribute) { return ((OperationContractAttribute) operationContractAttribs[0]).IsOneWay; } if (operationContractAttribs[0] is AttributeInfoAttribute) { AttributeInfoAttribute attribInfoAttrib = operationContractAttribs[0] as AttributeInfoAttribute; return GetAttributePropertyValue<bool>(provider, attribInfoAttrib.AttributeInfo, "IsOneWay"); } } } return false; } internal protected override MethodInfo GetMethodInfo(IServiceProvider provider) { if (string.IsNullOrEmpty(this.Name)) { return null; } MethodInfo methodInfo = null; if (this.IsReadOnly) { if (this.UserData.Contains(OperationInfoBase.MethodInfoProperty)) { methodInfo = this.UserData[OperationInfoBase.MethodInfoProperty] as MethodInfo; } if (methodInfo != null) { return methodInfo; } } Type type = this.GetContractType(provider); if (type != null && ServiceOperationHelpers.IsValidServiceContract(type)) { methodInfo = this.InternalGetMethodInfo(provider, type); } if (this.IsReadOnly) { this.UserData[OperationInfoBase.MethodInfoProperty] = methodInfo; } return methodInfo; } internal protected override OperationParameterInfoCollection GetParameters(IServiceProvider provider) { OperationParameterInfoCollection parameters = new OperationParameterInfoCollection(); MethodInfo methodInfo = this.GetMethodInfo(provider); if (methodInfo != null) { foreach (ParameterInfo parameter in methodInfo.GetParameters()) { if (parameters[parameter.Name] == null) { parameters.Add(new OperationParameterInfo(parameter)); } } if (methodInfo.ReturnParameter != null && methodInfo.ReturnParameter.ParameterType != typeof(void)) { if (parameters["(ReturnValue)"] == null) { OperationParameterInfo parameterInfo = new OperationParameterInfo(methodInfo.ReturnParameter); parameterInfo.Name = "(ReturnValue)"; parameters.Add(parameterInfo); } } } return parameters; } private static string[] GetAttributePropertyNames(AttributeInfo attributeInfo) { if (attributeInfo == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("attributeInfo"); } string[] argumentNames = null; BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic; FieldInfo argumentNamesField = typeof(AttributeInfo).GetField("argumentNames", bindingFlags); if (argumentNamesField != null) { argumentNames = argumentNamesField.GetValue(attributeInfo) as string[]; } return argumentNames; } T GetAttributePropertyValue<T>(IServiceProvider provider, AttributeInfo attribInfo, string propertyName) { string[] argumentNames = GetAttributePropertyNames(attribInfo); int argumentIndex = -1; for (int index = 0; index < argumentNames.Length; index++) { // skip unnamed arguments these are constructor arguments if ((argumentNames[index] == null) || (argumentNames[index].Length == 0)) { continue; } else { if (argumentNames[index].Equals(propertyName)) { argumentIndex = index; break; } } } if (argumentIndex != -1) { return (T) attribInfo.GetArgumentValueAs(provider, argumentIndex, typeof(T)); } else { return default(T); } } MethodInfo InternalGetMethodInfo(IServiceProvider provider, Type contractType) { MethodInfo methodInfo = null; if (contractType != null && ServiceOperationHelpers.IsValidServiceContract(contractType)) { foreach (MethodInfo currentMethodInfo in contractType.GetMethods()) { object[] operationContractAttribs = currentMethodInfo.GetCustomAttributes(typeof(OperationContractAttribute), true); if (operationContractAttribs != null && operationContractAttribs.Length > 0) { string operationName = null; if (operationContractAttribs[0] is OperationContractAttribute) { OperationContractAttribute operationContractAttribute = operationContractAttribs[0] as OperationContractAttribute; operationName = operationContractAttribute.Name; } if (operationContractAttribs[0] is AttributeInfoAttribute) { AttributeInfoAttribute attribInfoAttrib = operationContractAttribs[0] as AttributeInfoAttribute; operationName = GetAttributePropertyValue<string>(provider, attribInfoAttrib.AttributeInfo, "Name"); } if (string.IsNullOrEmpty(operationName) && string.Compare(currentMethodInfo.Name, this.Name, StringComparison.Ordinal) == 0) { methodInfo = currentMethodInfo; break; } else if (string.Compare(operationName, this.Name, StringComparison.Ordinal) == 0) { methodInfo = currentMethodInfo; break; } } } } if (methodInfo == null) { foreach (Type parentContract in contractType.GetInterfaces()) { methodInfo = this.InternalGetMethodInfo(provider, parentContract); if (methodInfo != null) { break; } } } return methodInfo; } } }
// 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.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Dictionary operations. /// </summary> public partial class Dictionary : IServiceOperations<AutoRestComplexTestService>, IDictionary { /// <summary> /// Initializes a new instance of the Dictionary class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Dictionary(AutoRestComplexTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types with dictionary property /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<DictionaryWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetValid", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<DictionaryWrapper>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<DictionaryWrapper>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put complex types with dictionary property /// </summary> /// <param name='complexBody'> /// Please put a dictionary with 5 key-value pairs: "txt":"notepad", /// "bmp":"mspaint", "xls":"excel", "exe":"", "":null /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(DictionaryWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutValid", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get complex types with dictionary property which is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<DictionaryWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<DictionaryWrapper>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<DictionaryWrapper>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put complex types with dictionary property which is empty /// </summary> /// <param name='complexBody'> /// Please put an empty dictionary /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(DictionaryWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutEmpty", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get complex types with dictionary property which is null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<DictionaryWrapper>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetNull", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/null").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<DictionaryWrapper>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<DictionaryWrapper>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get complex types with dictionary property while server doesn't provide a /// response payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<DictionaryWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/notprovided").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<DictionaryWrapper>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<DictionaryWrapper>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// // MethodBuilderTest.cs - NUnit Test Cases for the MethodBuilder class // // Zoltan Varga ([email protected]) // // (C) Ximian, Inc. http://www.ximian.com // TODO: // - implement 'Signature' (what the hell it does???) and test it // - implement Equals and test it using System; using System.Threading; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; using NUnit.Framework; namespace MonoTests.System.Reflection.Emit { [TestFixture] public class MethodBuilderTest : Assertion { private TypeBuilder genClass; private ModuleBuilder module; [SetUp] protected void SetUp () { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "MonoTests.System.Reflection.Emit.MethodBuilderTest"; AssemblyBuilder assembly = Thread.GetDomain().DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run); module = assembly.DefineDynamicModule("module1"); genClass = module.DefineType(genTypeName (), TypeAttributes.Public); } static int methodIndexer = 0; static int typeIndexer = 0; // Return a unique method name private string genMethodName () { return "m" + (methodIndexer ++); } // Return a unique type name private string genTypeName () { return "class" + (typeIndexer ++); } [Test] public void TestAttributes () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]); AssertEquals ("Attributes works", MethodAttributes.Public, mb.Attributes); } [Test] public void TestCallingConvention () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type[0]); AssertEquals ("CallingConvetion defaults to Standard+HasThis", CallingConventions.Standard | CallingConventions.HasThis, mb.CallingConvention); MethodBuilder mb3 = genClass.DefineMethod ( genMethodName (), 0, CallingConventions.VarArgs, typeof (void), new Type[0]); AssertEquals ("CallingConvetion works", CallingConventions.VarArgs | CallingConventions.HasThis, mb3.CallingConvention); MethodBuilder mb4 = genClass.DefineMethod ( genMethodName (), MethodAttributes.Static, CallingConventions.Standard, typeof (void), new Type [0]); AssertEquals ("Static implies !HasThis", CallingConventions.Standard, mb4.CallingConvention); } [Test] public void TestDeclaringType () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type[0]); AssertEquals ("DeclaringType works", genClass, mb.DeclaringType); } [Test] public void TestInitLocals () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type[0]); Assert ("InitLocals defaults to true", mb.InitLocals); mb.InitLocals = false; Assert ("InitLocals is settable", !mb.InitLocals); } [Test] [ExpectedException (typeof(NotSupportedException))] public void TestMethodHandleIncomplete () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); RuntimeMethodHandle handle = mb.MethodHandle; } [Test] [ExpectedException (typeof(NotSupportedException))] public void TestMethodHandleComplete () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); mb.CreateMethodBody (new byte[2], 0); genClass.CreateType (); RuntimeMethodHandle handle = mb.MethodHandle; } [Test] public void TestName () { string name = genMethodName (); MethodBuilder mb = genClass.DefineMethod ( name, 0, typeof (void), new Type [0]); AssertEquals ("Name works", name, mb.Name); } [Test] public void TestReflectedType () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); AssertEquals ("ReflectedType works", genClass, mb.ReflectedType); } [Test] public void TestReturnType () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (Console), new Type [0]); AssertEquals ("ReturnType works", typeof (Console), mb.ReturnType); MethodBuilder mb2 = genClass.DefineMethod ( genMethodName (), 0, null, new Type [0]); Assert ("void ReturnType works", (mb2.ReturnType == null) || (mb2.ReturnType == typeof (void))); } [Test] public void TestReturnTypeCustomAttributes () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (Console), new Type [0]); AssertEquals ("ReturnTypeCustomAttributes must be null", null, mb.ReturnTypeCustomAttributes); } /* public void TestSignature () { MethodBuilder mb = genClass.DefineMethod ( "m91", 0, typeof (Console), new Type [1] { typeof (Console) }); Console.WriteLine (mb.Signature); } */ [Test] public void TestCreateMethodBody () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); // Clear body mb.CreateMethodBody (null, 999); // Check arguments 1. try { mb.CreateMethodBody (new byte[1], -1); Fail (); } catch (ArgumentException) { } // Check arguments 2. try { mb.CreateMethodBody (new byte[1], 2); Fail (); } catch (ArgumentException) { } mb.CreateMethodBody (new byte[2], 1); // Could only be called once try { mb.CreateMethodBody (new byte[2], 1); Fail (); } catch (InvalidOperationException) { } // Can not be called on a created type TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb2 = tb.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); ILGenerator ilgen = mb2.GetILGenerator (); ilgen.Emit (OpCodes.Ret); tb.CreateType (); try { mb2.CreateMethodBody (new byte[2], 1); Fail (); } catch (InvalidOperationException) { } } [Test] [ExpectedException (typeof(InvalidOperationException))] public void TestDefineParameterInvalidIndexComplete () { TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( genMethodName (), 0, typeof (void), new Type[2] { typeof(int), typeof(int) }); mb.CreateMethodBody (new byte[2], 0); tb.CreateType (); mb.DefineParameter (-5, ParameterAttributes.None, "param1"); } [Test] [ExpectedException (typeof(InvalidOperationException))] public void TestDefineParameterValidIndexComplete () { TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( genMethodName (), 0, typeof (void), new Type[2] { typeof(int), typeof(int) }); mb.CreateMethodBody (new byte[2], 0); tb.CreateType (); mb.DefineParameter (1, ParameterAttributes.None, "param1"); } [Test] public void TestDefineParameter () { TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( genMethodName (), 0, typeof (void), new Type [2] { typeof(int), typeof(int) }); // index out of range // This fails on mono because the mono version accepts a 0 index /* try { mb.DefineParameter (0, 0, "param1"); Fail (); } catch (ArgumentOutOfRangeException) { } */ try { mb.DefineParameter (3, 0, "param1"); Fail (); } catch (ArgumentOutOfRangeException) { } // Normal usage mb.DefineParameter (1, 0, "param1"); mb.DefineParameter (1, 0, "param1"); mb.DefineParameter (2, 0, null); // Can not be called on a created type mb.CreateMethodBody (new byte[2], 0); tb.CreateType (); try { mb.DefineParameter (1, 0, "param1"); Fail (); } catch (InvalidOperationException) { } } [Test] public void TestHashCode () { TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); string methodName = genMethodName (); MethodBuilder mb = tb.DefineMethod ( methodName, 0, typeof (void), new Type[2] { typeof(int), typeof(int) }); AssertEquals ("Hashcode of method should be equal to hashcode of method name", methodName.GetHashCode (), mb.GetHashCode ()); } [Test] public void TestGetBaseDefinition () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); AssertEquals ("GetBaseDefinition works", mb.GetBaseDefinition (), mb); } [Test] public void TestGetILGenerator () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); // The same instance is returned on the second call ILGenerator ilgen1 = mb.GetILGenerator (); ILGenerator ilgen2 = mb.GetILGenerator (); AssertEquals ("The same ilgen is returned on the second call", ilgen1, ilgen2); // Does not work on unmanaged code MethodBuilder mb2 = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); try { mb2.SetImplementationFlags (MethodImplAttributes.Unmanaged); mb2.GetILGenerator (); Fail (); } catch (InvalidOperationException) { } try { mb2.SetImplementationFlags (MethodImplAttributes.Native); mb2.GetILGenerator (); Fail (); } catch (InvalidOperationException) { } } [Test] public void TestMethodImplementationFlags () { TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); AssertEquals ("MethodImplementationFlags defaults to Managed+IL", MethodImplAttributes.Managed | MethodImplAttributes.IL, mb.GetMethodImplementationFlags ()); mb.SetImplementationFlags (MethodImplAttributes.OPTIL); AssertEquals ("SetImplementationFlags works", MethodImplAttributes.OPTIL, mb.GetMethodImplementationFlags ()); // Can not be called on a created type mb.CreateMethodBody (new byte[2], 0); mb.SetImplementationFlags (MethodImplAttributes.Managed); tb.CreateType (); try { mb.SetImplementationFlags (MethodImplAttributes.OPTIL); Fail (); } catch (InvalidOperationException) { } } [Test] public void TestGetModule () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [0]); AssertEquals ("GetMethod works", module, mb.GetModule ()); } [Test] public void TestGetParameters () { TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( genMethodName (), 0, typeof (void), new Type [1] {typeof(void)}); /* * According to the MSDN docs, this method should fail with a * NotSupportedException. In reality, it throws an * InvalidOperationException under MS .NET, and returns the * requested data under mono. */ /* try { mb.GetParameters (); Fail ("#161"); } catch (InvalidOperationException ex) { Console.WriteLine (ex); } */ } [Test] public void TestGetToken () { TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( genMethodName (), 0, typeof (void), new Type [1] {typeof(void)}); mb.GetToken (); } [Test] public void TestInvoke () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [1] {typeof(int)}); try { mb.Invoke (null, new object [1] { 42 }); Fail (); } catch (NotSupportedException) { } try { mb.Invoke (null, 0, null, new object [1] { 42 }, null); Fail (); } catch (NotSupportedException) { } } [Test] [ExpectedException (typeof (NotSupportedException))] public void TestIsDefined () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [1] {typeof(int)}); mb.IsDefined (null, true); } [Test] public void TestGetCustomAttributes () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), 0, typeof (void), new Type [1] {typeof(int)}); try { mb.GetCustomAttributes (true); Fail (); } catch (NotSupportedException) { } try { mb.GetCustomAttributes (null, true); Fail (); } catch (NotSupportedException) { } } [Test] public void TestSetCustomAttribute () { TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); string name = genMethodName (); MethodBuilder mb = tb.DefineMethod ( name, MethodAttributes.Public, typeof (void), new Type [1] {typeof(int)}); // Null argument try { mb.SetCustomAttribute (null); Fail (); } catch (ArgumentNullException) { } byte[] custAttrData = { 1, 0, 0, 0, 0}; Type attrType = Type.GetType ("System.Reflection.AssemblyKeyNameAttribute"); Type[] paramTypes = new Type[1]; paramTypes[0] = typeof(String); ConstructorInfo ctorInfo = attrType.GetConstructor(paramTypes); mb.SetCustomAttribute (ctorInfo, custAttrData); // Test MethodImplAttribute mb.SetCustomAttribute (new CustomAttributeBuilder (typeof (MethodImplAttribute).GetConstructor (new Type[1] { typeof (short) }), new object[1] {(short)MethodImplAttributes.Synchronized})); mb.GetILGenerator ().Emit (OpCodes.Ret); Type t = tb.CreateType (); AssertEquals ("Setting MethodImplAttributes works", t.GetMethod (name).GetMethodImplementationFlags (), MethodImplAttributes.Synchronized); // Null arguments again try { mb.SetCustomAttribute (null, new byte[2]); Fail (); } catch (ArgumentNullException) { } try { mb.SetCustomAttribute (ctorInfo, null); Fail (); } catch (ArgumentNullException) { } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void TestAddDeclarativeSecurityAlreadyCreated () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]); ILGenerator ilgen = mb.GetILGenerator (); ilgen.Emit (OpCodes.Ret); genClass.CreateType (); PermissionSet set = new PermissionSet (PermissionState.Unrestricted); mb.AddDeclarativeSecurity (SecurityAction.Demand, set); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void TestAddDeclarativeSecurityNullPermissionSet () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]); mb.AddDeclarativeSecurity (SecurityAction.Demand, null); } [Test] public void TestAddDeclarativeSecurityInvalidAction () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]); SecurityAction[] actions = new SecurityAction [] { SecurityAction.RequestMinimum, SecurityAction.RequestOptional, SecurityAction.RequestRefuse }; PermissionSet set = new PermissionSet (PermissionState.Unrestricted); foreach (SecurityAction action in actions) { try { mb.AddDeclarativeSecurity (action, set); Fail (); } catch (ArgumentException) { } } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void TestAddDeclarativeSecurityDuplicateAction () { MethodBuilder mb = genClass.DefineMethod ( genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]); PermissionSet set = new PermissionSet (PermissionState.Unrestricted); mb.AddDeclarativeSecurity (SecurityAction.Demand, set); mb.AddDeclarativeSecurity (SecurityAction.Demand, set); } [AttributeUsage (AttributeTargets.Parameter)] class ParamAttribute : Attribute { public ParamAttribute () { } } [Test] public void TestDynamicParams () { string mname = genMethodName (); MethodBuilder mb = genClass.DefineMethod ( mname, MethodAttributes.Public, typeof (void), new Type [] { typeof (int), typeof (string) }); ParameterBuilder pb = mb.DefineParameter (1, ParameterAttributes.In, "foo"); pb.SetConstant (52); pb.SetCustomAttribute (new CustomAttributeBuilder (typeof (ParamAttribute).GetConstructors () [0], new object [] { })); ParameterBuilder pb2 = mb.DefineParameter (2, 0, "bar"); pb2.SetConstant ("foo"); mb.GetILGenerator ().Emit (OpCodes.Ret); Type t = genClass.CreateType (); MethodInfo m = t.GetMethod (mname); ParameterInfo[] pi = m.GetParameters (); AssertEquals ("foo", pi [0].Name); AssertEquals (true, pi [0].IsIn); AssertEquals (52, pi [0].DefaultValue); object[] cattrs = pi [0].GetCustomAttributes (true); AssertEquals ("foo", pi [1].DefaultValue); /* This test does not run under MS.NET: */ /* AssertEquals (1, cattrs.Length); AssertEquals (typeof (ParamAttribute), cattrs [0].GetType ()); */ } #if NET_2_0 [Test] public void SetCustomAttribute_DllImport1 () { string mname = genMethodName (); TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( mname, MethodAttributes.Public, typeof (void), new Type [] { typeof (int), typeof (string) }); // Create an attribute with default values mb.SetCustomAttribute (new CustomAttributeBuilder(typeof(DllImportAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { "kernel32" })); Type t = tb.CreateType (); DllImportAttribute attr = (DllImportAttribute)((t.GetMethod (mname).GetCustomAttributes (typeof (DllImportAttribute), true)) [0]); AssertEquals (CallingConvention.Winapi, attr.CallingConvention); AssertEquals (mname, attr.EntryPoint); AssertEquals ("kernel32", attr.Value); AssertEquals (false, attr.ExactSpelling); AssertEquals (true, attr.PreserveSig); AssertEquals (false, attr.SetLastError); AssertEquals (false, attr.BestFitMapping); AssertEquals (false, attr.ThrowOnUnmappableChar); } [Test] public void SetCustomAttribute_DllImport2 () { string mname = genMethodName (); TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( mname, MethodAttributes.Public, typeof (void), new Type [] { typeof (int), typeof (string) }); CustomAttributeBuilder cb = new CustomAttributeBuilder (typeof (DllImportAttribute).GetConstructor (new Type [] {typeof (String)}), new object [] { "foo" }, new FieldInfo [] {typeof (DllImportAttribute).GetField ("EntryPoint"), typeof (DllImportAttribute).GetField ("CallingConvention"), typeof (DllImportAttribute).GetField ("CharSet"), typeof (DllImportAttribute).GetField ("ExactSpelling"), typeof (DllImportAttribute).GetField ("PreserveSig")}, new object [] { "bar", CallingConvention.StdCall, CharSet.Unicode, true, false }); mb.SetCustomAttribute (cb); Type t = tb.CreateType (); DllImportAttribute attr = (DllImportAttribute)((t.GetMethod (mname).GetCustomAttributes (typeof (DllImportAttribute), true)) [0]); AssertEquals (CallingConvention.StdCall, attr.CallingConvention); AssertEquals (CharSet.Unicode, attr.CharSet); AssertEquals ("bar", attr.EntryPoint); AssertEquals ("foo", attr.Value); AssertEquals (true, attr.ExactSpelling); AssertEquals (false, attr.PreserveSig); AssertEquals (false, attr.SetLastError); AssertEquals (false, attr.BestFitMapping); AssertEquals (false, attr.ThrowOnUnmappableChar); } [Test] public void SetCustomAttribute_DllImport3 () { string mname = genMethodName (); TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( mname, MethodAttributes.Public, typeof (void), new Type [] { typeof (int), typeof (string) }); // Test attributes with three values (on/off/missing) CustomAttributeBuilder cb = new CustomAttributeBuilder (typeof (DllImportAttribute).GetConstructor (new Type [] {typeof (String)}), new object [] { "foo" }, new FieldInfo [] { typeof (DllImportAttribute).GetField ("BestFitMapping"), typeof (DllImportAttribute).GetField ("ThrowOnUnmappableChar")}, new object [] { false, false }); mb.SetCustomAttribute (cb); Type t = tb.CreateType (); DllImportAttribute attr = (DllImportAttribute)((t.GetMethod (mname).GetCustomAttributes (typeof (DllImportAttribute), true)) [0]); AssertEquals (false, attr.BestFitMapping); AssertEquals (false, attr.ThrowOnUnmappableChar); } [Test] public void SetCustomAttribute_DllImport4 () { string mname = genMethodName (); TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public); MethodBuilder mb = tb.DefineMethod ( mname, MethodAttributes.Public, typeof (void), new Type [] { typeof (int), typeof (string) }); CustomAttributeBuilder cb = new CustomAttributeBuilder (typeof (DllImportAttribute).GetConstructor (new Type [] {typeof (String)}), new object [] { "foo" }, new FieldInfo [] { typeof (DllImportAttribute).GetField ("SetLastError"), typeof (DllImportAttribute).GetField ("BestFitMapping"), typeof (DllImportAttribute).GetField ("ThrowOnUnmappableChar")}, new object [] { true, true, true }); mb.SetCustomAttribute (cb); Type t = tb.CreateType (); DllImportAttribute attr = (DllImportAttribute)((t.GetMethod (mname).GetCustomAttributes (typeof (DllImportAttribute), true)) [0]); AssertEquals (true, attr.SetLastError); AssertEquals (true, attr.BestFitMapping); AssertEquals (true, attr.ThrowOnUnmappableChar); } #endif } }
// 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 Xunit; namespace System.Linq.Tests { public class AggregateTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > int.MinValue select x; Assert.Equal(q.Aggregate((x, y) => x + y), q.Aggregate((x, y) => x + y)); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty } where !string.IsNullOrEmpty(x) select x; Assert.Equal(q.Aggregate((x, y) => x + y), q.Aggregate((x, y) => x + y)); } [Fact] public void EmptySource() { int[] source = { }; Assert.Throws<InvalidOperationException>(() => source.RunOnce().Aggregate((x, y) => x + y)); } [Fact] public void SingleElement() { int[] source = { 5 }; int expected = 5; Assert.Equal(expected, source.Aggregate((x, y) => x + y)); } [Fact] public void SingleElementRunOnce() { int[] source = { 5 }; int expected = 5; Assert.Equal(expected, source.RunOnce().Aggregate((x, y) => x + y)); } [Fact] public void TwoElements() { int[] source = { 5, 6 }; int expected = 11; Assert.Equal(expected, source.Aggregate((x, y) => x + y)); } [Fact] public void MultipleElements() { int[] source = { 5, 6, 0, -4 }; int expected = 7; Assert.Equal(expected, source.Aggregate((x, y) => x + y)); } [Fact] public void MultipleElementsRunOnce() { int[] source = { 5, 6, 0, -4 }; int expected = 7; Assert.Equal(expected, source.RunOnce().Aggregate((x, y) => x + y)); } [Fact] public void EmptySourceAndSeed() { int[] source = { }; long seed = 2; long expected = 2; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y)); } [Fact] public void SingleElementAndSeed() { int[] source = { 5 }; long seed = 2; long expected = 10; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y)); } [Fact] public void TwoElementsAndSeed() { int[] source = { 5, 6 }; long seed = 2; long expected = 60; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y)); } [Fact] public void MultipleElementsAndSeed() { int[] source = { 5, 6, 2, -4 }; long seed = 2; long expected = -480; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y)); } [Fact] public void MultipleElementsAndSeedRunOnce() { int[] source = { 5, 6, 2, -4 }; long seed = 2; long expected = -480; Assert.Equal(expected, source.RunOnce().Aggregate(seed, (x, y) => x * y)); } [Fact] public void NoElementsSeedResultSeletor() { int[] source = { }; long seed = 2; double expected = 7; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void SingleElementSeedResultSelector() { int[] source = { 5 }; long seed = 2; long expected = 15; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void TwoElementsSeedResultSelector() { int[] source = { 5, 6 }; long seed = 2; long expected = 65; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void MultipleElementsSeedResultSelector() { int[] source = { 5, 6, 2, -4 }; long seed = 2; long expected = -475; Assert.Equal(expected, source.Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void MultipleElementsSeedResultSelectorRunOnce() { int[] source = { 5, 6, 2, -4 }; long seed = 2; long expected = -475; Assert.Equal(expected, source.RunOnce().Aggregate(seed, (x, y) => x * y, x => x + 5.0)); } [Fact] public void NullSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Aggregate((x, y) => x + y)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Aggregate(0, (x, y) => x + y)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Aggregate(0, (x, y) => x + y, i => i)); } [Fact] public void NullFunc() { Func<int, int, int> func = null; AssertExtensions.Throws<ArgumentNullException>("func", () => Enumerable.Range(0, 3).Aggregate(func)); AssertExtensions.Throws<ArgumentNullException>("func", () => Enumerable.Range(0, 3).Aggregate(0, func)); AssertExtensions.Throws<ArgumentNullException>("func", () => Enumerable.Range(0, 3).Aggregate(0, func, i => i)); } [Fact] public void NullResultSelector() { Func<int, int> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => Enumerable.Range(0, 3).Aggregate(0, (x, y) => x + y, resultSelector)); } } }
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Primitives; using NBitcoin; using NBitcoin.RPC; using System; using System.Threading; using System.Threading.Tasks; namespace WalletWasabi.BitcoinCore.Rpc { public class CachedRpcClient : RpcClientBase { private CancellationTokenSource _tipChangeCancellationTokenSource; public CachedRpcClient(RPCClient rpc, IMemoryCache cache) : base(rpc) { Cache = cache; } private object CancellationTokenSourceLock { get; } = new object(); public IMemoryCache Cache { get; } private CancellationTokenSource TipChangeCancellationTokenSource { get { lock (CancellationTokenSourceLock) { if (_tipChangeCancellationTokenSource is null || _tipChangeCancellationTokenSource.IsCancellationRequested) { _tipChangeCancellationTokenSource = new CancellationTokenSource(); } } return _tipChangeCancellationTokenSource; } } public override async Task<uint256> GetBestBlockHashAsync() { string cacheKey = nameof(GetBestBlockHashAsync); var cacheOptions = new MemoryCacheEntryOptions { Size = 1, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(4) // The best hash doesn't change so often so, keep in cache for 4 seconds. }; cacheOptions.AddExpirationToken(new CancellationChangeToken(TipChangeCancellationTokenSource.Token)); return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetBestBlockHashAsync()).ConfigureAwait(false); } public override async Task<Block> GetBlockAsync(uint256 blockHash) { string cacheKey = $"{nameof(GetBlockAsync)}:{blockHash}"; var cacheOptions = new MemoryCacheEntryOptions { Size = 10, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(4) // There is a block every 10 minutes on average so, keep in cache for 4 seconds. }; return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetBlockAsync(blockHash)).ConfigureAwait(false); } public override async Task<Block> GetBlockAsync(uint blockHeight) { string cacheKey = $"{nameof(GetBlockAsync)}:{blockHeight}"; var cacheOptions = new MemoryCacheEntryOptions { Size = 10, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(4) // There is a block every 10 minutes on average so, keep in cache for 4 seconds. }; return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetBlockAsync(blockHeight)).ConfigureAwait(false); } public override async Task<BlockHeader> GetBlockHeaderAsync(uint256 blockHash) { string cacheKey = $"{nameof(GetBlockHeaderAsync)}:{blockHash}"; var cacheOptions = new MemoryCacheEntryOptions { Size = 2, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(4) // There is a block every 10 minutes on average so, keep in cache for 4 seconds. }; return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetBlockHeaderAsync(blockHash)).ConfigureAwait(false); } public override async Task<int> GetBlockCountAsync() { string cacheKey = nameof(GetBlockCountAsync); var cacheOptions = new MemoryCacheEntryOptions { Size = 1, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(2) // The blockchain info does not change frequently. }; cacheOptions.AddExpirationToken(new CancellationChangeToken(TipChangeCancellationTokenSource.Token)); return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetBlockCountAsync()).ConfigureAwait(false); } public override async Task<PeerInfo[]> GetPeersInfoAsync() { string cacheKey = nameof(GetPeersInfoAsync); var cacheOptions = new MemoryCacheEntryOptions { Size = 2, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(0.5) }; return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetPeersInfoAsync()).ConfigureAwait(false); } public override async Task<MempoolEntry> GetMempoolEntryAsync(uint256 txid, bool throwIfNotFound = true) { string cacheKey = $"{nameof(GetMempoolEntryAsync)}:{txid}"; var cacheOptions = new MemoryCacheEntryOptions { Size = 20, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(2) }; cacheOptions.AddExpirationToken(new CancellationChangeToken(TipChangeCancellationTokenSource.Token)); return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetMempoolEntryAsync(txid, throwIfNotFound)).ConfigureAwait(false); } public override async Task<MemPoolInfo> GetMempoolInfoAsync() { string cacheKey = nameof(GetMempoolInfoAsync); var cacheOptions = new MemoryCacheEntryOptions { Size = 1, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10) }; return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetMempoolInfoAsync()).ConfigureAwait(false); } public override async Task<EstimateSmartFeeResponse> EstimateSmartFeeAsync(int confirmationTarget, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative) { string cacheKey = $"{nameof(EstimateSmartFeeAsync)}:{confirmationTarget}:{estimateMode}"; var cacheOptions = new MemoryCacheEntryOptions { Size = 1, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(4) }; cacheOptions.AddExpirationToken(new CancellationChangeToken(TipChangeCancellationTokenSource.Token)); return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.EstimateSmartFeeAsync(confirmationTarget, estimateMode)).ConfigureAwait(false); } public override async Task<uint256[]> GetRawMempoolAsync() { string cacheKey = nameof(GetRawMempoolAsync); var cacheOptions = new MemoryCacheEntryOptions { Size = 20, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(2) }; cacheOptions.AddExpirationToken(new CancellationChangeToken(TipChangeCancellationTokenSource.Token)); return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetRawMempoolAsync()).ConfigureAwait(false); } public override async Task<GetTxOutResponse> GetTxOutAsync(uint256 txid, int index, bool includeMempool = true) { string cacheKey = $"{nameof(GetTxOutAsync)}:{txid}:{index}:{includeMempool}"; var cacheOptions = new MemoryCacheEntryOptions { Size = 2, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(2) }; return await Cache.AtomicGetOrCreateAsync( cacheKey, cacheOptions, () => base.GetTxOutAsync(txid, index, includeMempool)).ConfigureAwait(false); } public override async Task<uint256[]> GenerateAsync(int blockCount) { TipChangeCancellationTokenSource.Cancel(); return await base.GenerateAsync(blockCount).ConfigureAwait(false); } public override async Task InvalidateBlockAsync(uint256 blockHash) { TipChangeCancellationTokenSource.Cancel(); await base.InvalidateBlockAsync(blockHash).ConfigureAwait(false); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcsv = Google.Cloud.SecurityCenter.V1; using sys = System; namespace Google.Cloud.SecurityCenter.V1 { /// <summary>Resource name for the <c>SecurityMarks</c> resource.</summary> public sealed partial class SecurityMarksName : gax::IResourceName, sys::IEquatable<SecurityMarksName> { /// <summary>The possible contents of <see cref="SecurityMarksName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>organizations/{organization}/assets/{asset}/securityMarks</c>. /// </summary> OrganizationAsset = 1, /// <summary> /// A resource name with pattern /// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>. /// </summary> OrganizationSourceFinding = 2, /// <summary>A resource name with pattern <c>folders/{folder}/assets/{asset}/securityMarks</c>.</summary> FolderAsset = 3, /// <summary>A resource name with pattern <c>projects/{project}/assets/{asset}/securityMarks</c>.</summary> ProjectAsset = 4, /// <summary> /// A resource name with pattern <c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c>. /// </summary> FolderSourceFinding = 5, /// <summary> /// A resource name with pattern <c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c> /// . /// </summary> ProjectSourceFinding = 6, } private static gax::PathTemplate s_organizationAsset = new gax::PathTemplate("organizations/{organization}/assets/{asset}/securityMarks"); private static gax::PathTemplate s_organizationSourceFinding = new gax::PathTemplate("organizations/{organization}/sources/{source}/findings/{finding}/securityMarks"); private static gax::PathTemplate s_folderAsset = new gax::PathTemplate("folders/{folder}/assets/{asset}/securityMarks"); private static gax::PathTemplate s_projectAsset = new gax::PathTemplate("projects/{project}/assets/{asset}/securityMarks"); private static gax::PathTemplate s_folderSourceFinding = new gax::PathTemplate("folders/{folder}/sources/{source}/findings/{finding}/securityMarks"); private static gax::PathTemplate s_projectSourceFinding = new gax::PathTemplate("projects/{project}/sources/{source}/findings/{finding}/securityMarks"); /// <summary>Creates a <see cref="SecurityMarksName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SecurityMarksName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static SecurityMarksName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SecurityMarksName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SecurityMarksName"/> with the pattern /// <c>organizations/{organization}/assets/{asset}/securityMarks</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns> public static SecurityMarksName FromOrganizationAsset(string organizationId, string assetId) => new SecurityMarksName(ResourceNameType.OrganizationAsset, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId))); /// <summary> /// Creates a <see cref="SecurityMarksName"/> with the pattern /// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns> public static SecurityMarksName FromOrganizationSourceFinding(string organizationId, string sourceId, string findingId) => new SecurityMarksName(ResourceNameType.OrganizationSourceFinding, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId))); /// <summary> /// Creates a <see cref="SecurityMarksName"/> with the pattern <c>folders/{folder}/assets/{asset}/securityMarks</c> /// . /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns> public static SecurityMarksName FromFolderAsset(string folderId, string assetId) => new SecurityMarksName(ResourceNameType.FolderAsset, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId))); /// <summary> /// Creates a <see cref="SecurityMarksName"/> with the pattern /// <c>projects/{project}/assets/{asset}/securityMarks</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns> public static SecurityMarksName FromProjectAsset(string projectId, string assetId) => new SecurityMarksName(ResourceNameType.ProjectAsset, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId))); /// <summary> /// Creates a <see cref="SecurityMarksName"/> with the pattern /// <c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns> public static SecurityMarksName FromFolderSourceFinding(string folderId, string sourceId, string findingId) => new SecurityMarksName(ResourceNameType.FolderSourceFinding, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId))); /// <summary> /// Creates a <see cref="SecurityMarksName"/> with the pattern /// <c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns> public static SecurityMarksName FromProjectSourceFinding(string projectId, string sourceId, string findingId) => new SecurityMarksName(ResourceNameType.ProjectSourceFinding, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>organizations/{organization}/assets/{asset}/securityMarks</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>organizations/{organization}/assets/{asset}/securityMarks</c>. /// </returns> public static string Format(string organizationId, string assetId) => FormatOrganizationAsset(organizationId, assetId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>organizations/{organization}/assets/{asset}/securityMarks</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>organizations/{organization}/assets/{asset}/securityMarks</c>. /// </returns> public static string FormatOrganizationAsset(string organizationId, string assetId) => s_organizationAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>. /// </returns> public static string FormatOrganizationSourceFinding(string organizationId, string sourceId, string findingId) => s_organizationSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>folders/{folder}/assets/{asset}/securityMarks</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>folders/{folder}/assets/{asset}/securityMarks</c>. /// </returns> public static string FormatFolderAsset(string folderId, string assetId) => s_folderAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>projects/{project}/assets/{asset}/securityMarks</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>projects/{project}/assets/{asset}/securityMarks</c>. /// </returns> public static string FormatProjectAsset(string projectId, string assetId) => s_projectAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c>. /// </returns> public static string FormatFolderSourceFinding(string folderId, string sourceId, string findingId) => s_folderSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SecurityMarksName"/> with pattern /// <c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c>. /// </returns> public static string FormatProjectSourceFinding(string projectId, string sourceId, string findingId) => s_projectSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId))); /// <summary> /// Parses the given resource name string into a new <see cref="SecurityMarksName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/assets/{asset}/securityMarks</c></description></item> /// <item> /// <description> /// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c> /// </description> /// </item> /// <item><description><c>folders/{folder}/assets/{asset}/securityMarks</c></description></item> /// <item><description><c>projects/{project}/assets/{asset}/securityMarks</c></description></item> /// <item> /// <description><c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c></description> /// </item> /// <item> /// <description><c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c></description> /// </item> /// </list> /// </remarks> /// <param name="securityMarksName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SecurityMarksName"/> if successful.</returns> public static SecurityMarksName Parse(string securityMarksName) => Parse(securityMarksName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SecurityMarksName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/assets/{asset}/securityMarks</c></description></item> /// <item> /// <description> /// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c> /// </description> /// </item> /// <item><description><c>folders/{folder}/assets/{asset}/securityMarks</c></description></item> /// <item><description><c>projects/{project}/assets/{asset}/securityMarks</c></description></item> /// <item> /// <description><c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c></description> /// </item> /// <item> /// <description><c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="securityMarksName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SecurityMarksName"/> if successful.</returns> public static SecurityMarksName Parse(string securityMarksName, bool allowUnparsed) => TryParse(securityMarksName, allowUnparsed, out SecurityMarksName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SecurityMarksName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/assets/{asset}/securityMarks</c></description></item> /// <item> /// <description> /// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c> /// </description> /// </item> /// <item><description><c>folders/{folder}/assets/{asset}/securityMarks</c></description></item> /// <item><description><c>projects/{project}/assets/{asset}/securityMarks</c></description></item> /// <item> /// <description><c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c></description> /// </item> /// <item> /// <description><c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c></description> /// </item> /// </list> /// </remarks> /// <param name="securityMarksName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SecurityMarksName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string securityMarksName, out SecurityMarksName result) => TryParse(securityMarksName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SecurityMarksName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/assets/{asset}/securityMarks</c></description></item> /// <item> /// <description> /// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c> /// </description> /// </item> /// <item><description><c>folders/{folder}/assets/{asset}/securityMarks</c></description></item> /// <item><description><c>projects/{project}/assets/{asset}/securityMarks</c></description></item> /// <item> /// <description><c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c></description> /// </item> /// <item> /// <description><c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="securityMarksName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SecurityMarksName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string securityMarksName, bool allowUnparsed, out SecurityMarksName result) { gax::GaxPreconditions.CheckNotNull(securityMarksName, nameof(securityMarksName)); gax::TemplatedResourceName resourceName; if (s_organizationAsset.TryParseName(securityMarksName, out resourceName)) { result = FromOrganizationAsset(resourceName[0], resourceName[1]); return true; } if (s_organizationSourceFinding.TryParseName(securityMarksName, out resourceName)) { result = FromOrganizationSourceFinding(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_folderAsset.TryParseName(securityMarksName, out resourceName)) { result = FromFolderAsset(resourceName[0], resourceName[1]); return true; } if (s_projectAsset.TryParseName(securityMarksName, out resourceName)) { result = FromProjectAsset(resourceName[0], resourceName[1]); return true; } if (s_folderSourceFinding.TryParseName(securityMarksName, out resourceName)) { result = FromFolderSourceFinding(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_projectSourceFinding.TryParseName(securityMarksName, out resourceName)) { result = FromProjectSourceFinding(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(securityMarksName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SecurityMarksName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetId = null, string findingId = null, string folderId = null, string organizationId = null, string projectId = null, string sourceId = null) { Type = type; UnparsedResource = unparsedResourceName; AssetId = assetId; FindingId = findingId; FolderId = folderId; OrganizationId = organizationId; ProjectId = projectId; SourceId = sourceId; } /// <summary> /// Constructs a new instance of a <see cref="SecurityMarksName"/> class from the component parts of pattern /// <c>organizations/{organization}/assets/{asset}/securityMarks</c> /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> public SecurityMarksName(string organizationId, string assetId) : this(ResourceNameType.OrganizationAsset, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Asset</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string AssetId { get; } /// <summary> /// The <c>Finding</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string FindingId { get; } /// <summary> /// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string FolderId { get; } /// <summary> /// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string OrganizationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Source</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string SourceId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.OrganizationAsset: return s_organizationAsset.Expand(OrganizationId, AssetId); case ResourceNameType.OrganizationSourceFinding: return s_organizationSourceFinding.Expand(OrganizationId, SourceId, FindingId); case ResourceNameType.FolderAsset: return s_folderAsset.Expand(FolderId, AssetId); case ResourceNameType.ProjectAsset: return s_projectAsset.Expand(ProjectId, AssetId); case ResourceNameType.FolderSourceFinding: return s_folderSourceFinding.Expand(FolderId, SourceId, FindingId); case ResourceNameType.ProjectSourceFinding: return s_projectSourceFinding.Expand(ProjectId, SourceId, FindingId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SecurityMarksName); /// <inheritdoc/> public bool Equals(SecurityMarksName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SecurityMarksName a, SecurityMarksName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SecurityMarksName a, SecurityMarksName b) => !(a == b); } public partial class SecurityMarks { /// <summary> /// <see cref="gcsv::SecurityMarksName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::SecurityMarksName SecurityMarksName { get => string.IsNullOrEmpty(Name) ? null : gcsv::SecurityMarksName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Sockets; using System.Net.Security; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public class HttpClientHandlerTest { readonly ITestOutputHelper _output; private const string ExpectedContent = "Test contest"; private const string Username = "testuser"; private const string Password = "password"; private readonly NetworkCredential _credential = new NetworkCredential(Username, Password); public readonly static object[][] EchoServers = Configuration.Http.EchoServers; public readonly static object[][] VerifyUploadServers = Configuration.Http.VerifyUploadServers; public readonly static object[][] CompressedServers = Configuration.Http.CompressedServers; public readonly static object[][] HeaderValueAndUris = { new object[] { "X-CustomHeader", "x-value", Configuration.Http.RemoteEchoServer }, new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RemoteEchoServer }, new object[] { "X-CustomHeader", "x-value", Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:Configuration.Http.RemoteEchoServer, hops:1) }, new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:Configuration.Http.RemoteEchoServer, hops:1) }, }; public readonly static object[][] Http2Servers = Configuration.Http.Http2Servers; public readonly static object[][] RedirectStatusCodes = { new object[] { 300 }, new object[] { 301 }, new object[] { 302 }, new object[] { 303 }, new object[] { 307 } }; // Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3 // "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE" public readonly static IEnumerable<object[]> HttpMethods = GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1"); public readonly static IEnumerable<object[]> HttpMethodsThatAllowContent = GetMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "CUSTOM1"); public readonly static IEnumerable<object[]> HttpMethodsThatDontAllowContent = GetMethods("HEAD", "TRACE"); private static IEnumerable<object[]> GetMethods(params string[] methods) { foreach (string method in methods) { foreach (bool secure in new[] { true, false }) { yield return new object[] { method, secure }; } } } public HttpClientHandlerTest(ITestOutputHelper output) { _output = output; } [Fact] public void Ctor_ExpectedDefaultPropertyValues() { using (var handler = new HttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.True(handler.AllowAutoRedirect); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions); CookieContainer cookies = handler.CookieContainer; Assert.NotNull(cookies); Assert.Equal(0, cookies.Count); Assert.Null(handler.Credentials); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.False(handler.PreAuthenticate); Assert.Equal(null, handler.Proxy); Assert.True(handler.SupportsAutomaticDecompression); Assert.True(handler.SupportsProxy); Assert.True(handler.SupportsRedirectConfiguration); Assert.True(handler.UseCookies); Assert.False(handler.UseDefaultCredentials); Assert.True(handler.UseProxy); // Changes from .NET Framework (Desktop). Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression); Assert.Equal(0, handler.MaxRequestContentBufferSize); Assert.NotNull(handler.Properties); } } [Fact] public void MaxRequestContentBufferSize_Get_ReturnsZero() { using (var handler = new HttpClientHandler()) { Assert.Equal(0, handler.MaxRequestContentBufferSize); } } [Fact] public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException() { using (var handler = new HttpClientHandler()) { Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy) { var handler = new HttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.NegotiateAuthUriForDefaultCreds(secure:false); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Fact] public void Properties_Get_CountIsZero() { var handler = new HttpClientHandler(); IDictionary<String, object> dict = handler.Properties; Assert.Same(dict, handler.Properties); Assert.Equal(0, dict.Count); } [Fact] public void Properties_AddItemToDictionary_ItemPresent() { var handler = new HttpClientHandler(); IDictionary<String, object> dict = handler.Properties; var item = new Object(); dict.Add("item", item); object value; Assert.True(dict.TryGetValue("item", out value)); Assert.Equal(item, value); } [Theory, MemberData(nameof(EchoServers))] public async Task SendAsync_SimpleGet_Success(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(remoteServer)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory] [MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))] public async Task GetAsync_IPBasedUri_Success(IPAddress address) { using (var client = new HttpClient()) { var options = new LoopbackServer.Options { Address = address }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options), client.GetAsync(url)); }, options); } } public static IEnumerable<object[]> GetAsync_IPBasedUri_Success_MemberData() { foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback, LoopbackServer.GetIPv6LinkLocalAddress() }) { if (addr != null) { yield return new object[] { addr }; } } } [Fact] public async Task SendAsync_MultipleRequestsReusingSameClient_Success() { using (var client = new HttpClient()) { HttpResponseMessage response; for (int i = 0; i < 3; i++) { response = await client.GetAsync(Configuration.Http.RemoteEchoServer); Assert.Equal(HttpStatusCode.OK, response.StatusCode); response.Dispose(); } } } [Fact] public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success() { HttpResponseMessage response = null; using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer); } Assert.NotNull(response); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } [Fact] public async Task SendAsync_Cancel_CancellationTokenPropagates() { var cts = new CancellationTokenSource(); cts.Cancel(); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer); TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, cts.Token)); Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested"); Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested"); } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(server)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_HeadersRemoved(Uri server) { using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found"); Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found"); } } [Fact] public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized() { using (var client = new HttpClient()) { Uri uri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:statusCode, destinationUri:Configuration.Http.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(statusCode, (int)response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:statusCode, destinationUri:Configuration.Http.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:Configuration.Http.SecureRemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.SecureRemoteEchoServer, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure:true, statusCode:302, destinationUri:Configuration.Http.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; Uri targetUri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:targetUri, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(targetUri, response.RequestMessage.RequestUri); } } } [ActiveIssue(8945, PlatformID.Windows)] [Theory] [InlineData(3, 2)] [InlineData(3, 3)] [InlineData(3, 4)] public async Task GetAsync_MaxAutomaticRedirectionsNServerHops_ThrowsIfTooMany(int maxHops, int hops) { using (var client = new HttpClient(new HttpClientHandler() { MaxAutomaticRedirections = maxHops })) { Task<HttpResponseMessage> t = client.GetAsync(Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: hops)); if (hops <= maxHops) { using (HttpResponseMessage response = await t) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } else { await Assert.ThrowsAsync<HttpRequestException>(() => t); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithRelativeLocation() { using (var client = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = true })) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure: false, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1, relative: true); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } } [Theory] [InlineData(200)] [InlineData(201)] [InlineData(400)] public async Task GetAsync_AllowAutoRedirectTrue_NonRedirectStatusCode_LocationHeader_NoRedirect(int statusCode) { using (var handler = new HttpClientHandler() { AllowAutoRedirect = true }) using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { await LoopbackServer.CreateServerAsync(async (redirectServer, redirectUrl) => { Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl); Task redirectTask = LoopbackServer.ReadRequestAndSendResponseAsync(redirectServer); await LoopbackServer.ReadRequestAndSendResponseAsync(origServer, $"HTTP/1.1 {statusCode} OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Location: {redirectUrl}\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(statusCode, (int)response.StatusCode); Assert.Equal(origUrl, response.RequestMessage.RequestUri); Assert.False(redirectTask.IsCompleted, "Should not have redirected to Location"); } }); }); } } [Theory] [PlatformSpecific(PlatformID.AnyUnix)] [InlineData("#origFragment", "", "#origFragment", false)] [InlineData("#origFragment", "", "#origFragment", true)] [InlineData("", "#redirFragment", "#redirFragment", false)] [InlineData("", "#redirFragment", "#redirFragment", true)] [InlineData("#origFragment", "#redirFragment", "#redirFragment", false)] [InlineData("#origFragment", "#redirFragment", "#redirFragment", true)] public async Task GetAsync_AllowAutoRedirectTrue_RetainsOriginalFragmentIfAppropriate( string origFragment, string redirFragment, string expectedFragment, bool useRelativeRedirect) { using (var handler = new HttpClientHandler() { AllowAutoRedirect = true }) using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { origUrl = new Uri(origUrl.ToString() + origFragment); Uri redirectUrl = useRelativeRedirect ? new Uri(origUrl.PathAndQuery + redirFragment, UriKind.Relative) : new Uri(origUrl.ToString() + redirFragment); Uri expectedUrl = new Uri(origUrl.ToString() + expectedFragment); Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl); Task firstRequest = LoopbackServer.ReadRequestAndSendResponseAsync(origServer, $"HTTP/1.1 302 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Location: {redirectUrl}\r\n" + "\r\n"); Assert.Equal(firstRequest, await Task.WhenAny(firstRequest, getResponse)); Task secondRequest = LoopbackServer.ReadRequestAndSendResponseAsync(origServer, $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "\r\n"); await TestHelper.WhenAllCompletedOrAnyFailed(secondRequest, getResponse); using (HttpResponseMessage response = await getResponse) { Assert.Equal(200, (int)response.StatusCode); Assert.Equal(expectedUrl, response.RequestMessage.RequestUri); } }); } } [Fact] public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri redirectUri = Configuration.Http.RedirectUriForCreds( secure:false, statusCode:302, userName:Username, password:Password); using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode) { Uri uri = Configuration.Http.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); Uri redirectUri = Configuration.Http.RedirectUriForCreds( secure:false, statusCode:statusCode, userName:Username, password:Password); _output.WriteLine(uri.AbsoluteUri); _output.WriteLine(redirectUri.AbsoluteUri); var credentialCache = new CredentialCache(); credentialCache.Add(uri, "Basic", _credential); var handler = new HttpClientHandler(); handler.Credentials = credentialCache; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [Fact] public async Task GetAsync_DefaultCoookieContainer_NoCookieSent() { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie")); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue) { var handler = new HttpClientHandler(); var cookieContainer = new CookieContainer(); cookieContainer.Add(Configuration.Http.RemoteEchoServer, new Cookie(cookieName, cookieValue)); handler.CookieContainer = cookieContainer; using (var client = new HttpClient(handler)) { using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue) { Uri uri = Configuration.Http.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:Configuration.Http.RemoteEchoServer, hops:1); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add( "X-SetCookie", string.Format("{0}={1};Path=/", cookieName, cookieValue)); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory, MemberData(nameof(HeaderValueAndUris))] public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add(name, value); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value)); } } } private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length); int valueCount = overallHeaderValueLength - emptyHeaderValue.Length; string value = new string(repeat, valueCount); return new KeyValuePair<string, string>(name, value); } public static object[][] CookieNameValues = { // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257) }, new object[] { new KeyValuePair<string, string>( ".AspNetCore.Antiforgery.Xam7_OeLcN4", "CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM") } }; [Theory] [MemberData(nameof(CookieNameValues))] public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1) { var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM"); var cookie3 = new KeyValuePair<string, string>("name", "value"); await LoopbackServer.CreateServerAsync(async (server, url) => { using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponse = client.GetAsync(url); await LoopbackServer.ReadRequestAndSendResponseAsync(server, $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Set-Cookie: {cookie1.Key}={cookie1.Value}; Path=/\r\n" + $"Set-Cookie : {cookie2.Key}={cookie2.Value}; Path=/\r\n" + // space before colon to verify header is trimmed and recognized $"Set-Cookie: {cookie3.Key}={cookie3.Value}; Path=/\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); CookieCollection cookies = handler.CookieContainer.GetCookies(url); Assert.Equal(3, cookies.Count); Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value); Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value); Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value); } } }); } [Fact] public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock() { using (var client = new HttpClient()) { const int NumGets = 5; Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets) select client.GetAsync(Configuration.Http.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray(); for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available { using (HttpResponseMessage response = await responseTasks[i]) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } } [Fact] public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer); using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Fact] public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(reader.ReadLine())) ; await writer.WriteAsync( "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 16000\r\n" + "\r\n" + "less than 16000 bytes"); using (HttpResponseMessage response = await getResponse) { var buffer = new byte[8000]; using (Stream clientStream = await response.Content.ReadAsStreamAsync()) { int bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length); _output.WriteLine($"Bytes read from stream: {bytesRead}"); Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length"); } } }); } }); } [Fact] public async Task Dispose_DisposingHandlerCancelsActiveOperationsWithoutResponses() { await LoopbackServer.CreateServerAsync(async (socket1, url1) => { await LoopbackServer.CreateServerAsync(async (socket2, url2) => { await LoopbackServer.CreateServerAsync(async (socket3, url3) => { var unblockServers = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously); // First server connects but doesn't send any response yet Task server1 = LoopbackServer.AcceptSocketAsync(socket1, async (s, stream, reader, writer) => { await unblockServers.Task; }); // Second server connects and sends some but not all headers Task server2 = LoopbackServer.AcceptSocketAsync(socket2, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync($"HTTP/1.1 200 OK\r\n"); await unblockServers.Task; }); // Third server connects and sends all headers and some but not all of the body Task server3 = LoopbackServer.AcceptSocketAsync(socket3, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 20\r\n\r\n"); await writer.WriteAsync("1234567890"); await unblockServers.Task; await writer.WriteAsync("1234567890"); s.Shutdown(SocketShutdown.Send); }); // Make three requests Task<HttpResponseMessage> get1, get2; HttpResponseMessage response3; using (var client = new HttpClient()) { get1 = client.GetAsync(url1, HttpCompletionOption.ResponseHeadersRead); get2 = client.GetAsync(url2, HttpCompletionOption.ResponseHeadersRead); response3 = await client.GetAsync(url3, HttpCompletionOption.ResponseHeadersRead); } // Requests 1 and 2 should be canceled as we haven't finished receiving their headers await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get1); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get2); // Request 3 should still be active, and we should be able to receive all of the data. unblockServers.SetResult(true); using (response3) { Assert.Equal("12345678901234567890", await response3.Content.ReadAsStringAsync()); } }); }); }); } #region Post Methods Tests [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "Test String"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); HttpResponseMessage response; using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Repeat call. content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))] public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData) { using (var client = new HttpClient()) { content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } private sealed class StreamContentWithSyncAsyncCopy : StreamContent { private readonly Stream _stream; private readonly bool _syncCopy; public StreamContentWithSyncAsyncCopy(Stream stream, bool syncCopy) : base(stream) { _stream = stream; _syncCopy = syncCopy; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { if (_syncCopy) { try { _stream.CopyTo(stream, 128); // arbitrary size likely to require multiple read/writes return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } } return base.SerializeToStreamAsync(stream, context); } } public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData { get { foreach (object[] serverArr in VerifyUploadServers) // target server foreach (bool syncCopy in new[] { true, false }) // force the content copy to happen via Read/Write or ReadAsync/WriteAsync { Uri server = (Uri)serverArr[0]; byte[] data = new byte[1234]; new Random(42).NextBytes(data); // A MemoryStream { var memStream = new MemoryStream(data, writable: false); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(memStream, syncCopy: syncCopy), data }; } // A multipart content that provides its own stream from CreateContentReadStreamAsync { var mc = new MultipartContent(); mc.Add(new ByteArrayContent(data)); var memStream = new MemoryStream(); mc.CopyToAsync(memStream).GetAwaiter().GetResult(); yield return new object[] { server, mc, memStream.ToArray() }; } // A stream that provides the data synchronously and has a known length { var wrappedMemStream = new MemoryStream(data, writable: false); var syncKnownLengthStream = new DelegateStream( canReadFunc: () => wrappedMemStream.CanRead, canSeekFunc: () => wrappedMemStream.CanSeek, lengthFunc: () => wrappedMemStream.Length, positionGetFunc: () => wrappedMemStream.Position, positionSetFunc: p => wrappedMemStream.Position = p, readFunc: (buffer, offset, count) => wrappedMemStream.Read(buffer, offset, count), readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token)); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncKnownLengthStream, syncCopy: syncCopy), data }; } // A stream that provides the data synchronously and has an unknown length { int syncUnknownLengthStreamOffset = 0; Func<byte[], int, int, int> readFunc = (buffer, offset, count) => { int bytesRemaining = data.Length - syncUnknownLengthStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, count); Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy); syncUnknownLengthStreamOffset += bytesToCopy; return bytesToCopy; }; var syncUnknownLengthStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readFunc: readFunc, readAsyncFunc: (buffer, offset, count, token) => Task.FromResult(readFunc(buffer, offset, count))); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncUnknownLengthStream, syncCopy: syncCopy), data }; } // A stream that provides the data asynchronously { int asyncStreamOffset = 0, maxDataPerRead = 100; Func<byte[], int, int, int> readFunc = (buffer, offset, count) => { int bytesRemaining = data.Length - asyncStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count)); Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy); asyncStreamOffset += bytesToCopy; return bytesToCopy; }; var asyncStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readFunc: readFunc, readAsyncFunc: async (buffer, offset, count, token) => { await Task.Delay(1).ConfigureAwait(false); return readFunc(buffer, offset, count); }); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(asyncStream, syncCopy: syncCopy), data }; } // Providing data from a FormUrlEncodedContent's stream { var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("key", "val") }); yield return new object[] { server, formContent, Encoding.GetEncoding("iso-8859-1").GetBytes("key=val") }; } } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_NullContent(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, null)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer) { using (var client = new HttpClient()) { var content = new StringContent(string.Empty); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure) { const string ContentString = "This is the content string."; var content = new StringContent(ContentString); Uri redirectUri = Configuration.Http.RedirectUriForDestinationUri( secure, 302, secure ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain(ContentString, responseContent); Assert.DoesNotContain("Content-Length", responseContent); } } [OuterLoop] // takes several seconds [Theory] [InlineData(302, false)] [InlineData(307, true)] public async Task PostAsync_Redirect_LargePayload(int statusCode, bool expectRedirectToPost) { using (var fs = new FileStream(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x1000, FileOptions.DeleteOnClose)) { string contentString = string.Join("", Enumerable.Repeat("Content", 100000)); byte[] contentBytes = Encoding.UTF32.GetBytes(contentString); fs.Write(contentBytes, 0, contentBytes.Length); fs.Flush(flushToDisk: true); fs.Position = 0; Uri redirectUri = Configuration.Http.RedirectUriForDestinationUri(false, statusCode, Configuration.Http.SecureRemoteEchoServer, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, new StreamContent(fs))) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (expectRedirectToPost) { Assert.InRange(response.Content.Headers.ContentLength.GetValueOrDefault(), contentBytes.Length, int.MaxValue); } } } } [Fact] public async Task PostAsync_ResponseContentRead_RequestContentDisposedAfterResponseBuffered() { using (var client = new HttpClient()) { await LoopbackServer.CreateServerAsync(async (server, url) => { bool contentDisposed = false; Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new DelegateContent { SerializeToStreamAsyncDelegate = (contentStream, contentTransport) => contentStream.WriteAsync(new byte[100], 0, 100), TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100), DisposeDelegate = _ => contentDisposed = true } }, HttpCompletionOption.ResponseContentRead); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { // Read headers from client while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; // Send back all headers and some but not all of the response await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n"); await writer.WriteAsync("abcd"); // less than contentLength // The request content should not be disposed of until all of the response has been sent await Task.Delay(1); // a little time to let data propagate Assert.False(contentDisposed, "Expected request content not to be disposed"); // Send remaining response content await writer.WriteAsync("efghij"); s.Shutdown(SocketShutdown.Send); // The task should complete and the request content should be disposed using (HttpResponseMessage response = await post) { Assert.True(contentDisposed, "Expected request content to be disposed"); Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync()); } }); }); } } [Fact] public async Task PostAsync_ResponseHeadersRead_RequestContentDisposedAfterRequestFullySentAndResponseHeadersReceived() { using (var client = new HttpClient()) { await LoopbackServer.CreateServerAsync(async (server, url) => { var trigger = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); bool contentDisposed = false; Task<HttpResponseMessage> post = client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new DelegateContent { SerializeToStreamAsyncDelegate = async (contentStream, contentTransport) => { await contentStream.WriteAsync(new byte[50], 0, 50); await trigger.Task; await contentStream.WriteAsync(new byte[50], 0, 50); }, TryComputeLengthDelegate = () => Tuple.Create<bool, long>(true, 100), DisposeDelegate = _ => contentDisposed = true } }, HttpCompletionOption.ResponseHeadersRead); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { // Read headers from client while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; // Send back all headers and some but not all of the response await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 10\r\n\r\n"); await writer.WriteAsync("abcd"); // less than contentLength if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.False(contentDisposed, "Expected request content to not be disposed while request data still being sent"); } else // [ActiveIssue(9006, PlatformID.AnyUnix)] { await post; Assert.True(contentDisposed, "Current implementation will dispose of the request content once response headers arrive"); } // Allow request content to complete trigger.SetResult(true); // Send remaining response content await writer.WriteAsync("efghij"); s.Shutdown(SocketShutdown.Send); // The task should complete and the request content should be disposed using (HttpResponseMessage response = await post) { Assert.True(contentDisposed, "Expected request content to be disposed"); Assert.Equal("abcdefghij", await response.Content.ReadAsStringAsync()); } }); }); } } private sealed class DelegateContent : HttpContent { internal Func<Stream, TransportContext, Task> SerializeToStreamAsyncDelegate; internal Func<Tuple<bool, long>> TryComputeLengthDelegate; internal Action<bool> DisposeDelegate; protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { return SerializeToStreamAsyncDelegate != null ? SerializeToStreamAsyncDelegate(stream, context) : Task.CompletedTask; } protected override bool TryComputeLength(out long length) { if (TryComputeLengthDelegate != null) { var result = TryComputeLengthDelegate(); length = result.Item2; return result.Item1; } length = 0; return false; } protected override void Dispose(bool disposing) => DisposeDelegate?.Invoke(disposing); } [Theory] [InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")] [InlineData(HttpStatusCode.MethodNotAllowed, "")] public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.StatusCodeUri( false, (int)statusCode, reasonPhrase))) { Assert.Equal(statusCode, response.StatusCode); Assert.Equal(reasonPhrase, response.ReasonPhrase); } } } [PlatformSpecific(PlatformID.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix [Fact] public async Task PostAsync_Post_ChannelBindingHasExpectedValue() { using (var client = new HttpClient()) { string expectedContent = "Test contest"; var content = new ChannelBindingAwareContent(expectedContent); using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); ChannelBinding channelBinding = content.ChannelBinding; Assert.NotNull(channelBinding); _output.WriteLine("Channel Binding: {0}", channelBinding); } } } #endregion #region Various HTTP Method Tests [Theory, MemberData(nameof(HttpMethods))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); } } } [Theory, MemberData(nameof(HttpMethodsThatAllowContent))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer); request.Content = new StringContent(ExpectedContent); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, ExpectedContent); } } } [Theory] [InlineData("12345678910", 0)] [InlineData("12345678910", 5)] public async Task SendAsync_SendSameRequestMultipleTimesDirectlyOnHandler_Success(string stringContent, int startingPosition) { using (var handler = new HttpMessageInvoker(new HttpClientHandler())) { byte[] byteContent = Encoding.ASCII.GetBytes(stringContent); var content = new MemoryStream(); content.Write(byteContent, 0, byteContent.Length); content.Position = startingPosition; var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer) { Content = new StreamContent(content) }; for (int iter = 0; iter < 2; iter++) { using (HttpResponseMessage response = await handler.SendAsync(request, CancellationToken.None)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); Assert.Contains(stringContent.Substring(startingPosition), responseContent); if (startingPosition != 0) { Assert.DoesNotContain(stringContent.Substring(0, startingPosition), responseContent); } } } } } [Theory, MemberData(nameof(HttpMethodsThatDontAllowContent))] public async Task SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer) { Content = new StringContent(ExpectedContent) }; using (HttpResponseMessage response = await client.SendAsync(request)) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && method == "TRACE") { // [ActiveIssue(9023, PlatformID.Windows)] Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } else { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); Assert.False(responseContent.Contains(ExpectedContent)); } } } } #endregion #region Version tests [Fact] public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request() { Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 0)); Assert.Equal(new Version(1, 0), receivedRequestVersion); } [Fact] public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request() { Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 1)); Assert.Equal(new Version(1, 1), receivedRequestVersion); } [Fact] public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request() { // The default value for HttpRequestMessage.Version is Version(1,1). // So, we need to set something different (0,0), to test the "unknown" version. Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(0,0)); Assert.Equal(new Version(1, 1), receivedRequestVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server) { // We don't currently have a good way to test whether HTTP/2 is supported without // using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses. var request = new HttpRequestMessage(HttpMethod.Get, server); request.Version = new Version(2, 0); using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler, false)) { // It is generally expected that the test hosts will be trusted, so we don't register a validation // callback in the usual case. // // However, on our Debian 8 test machines, a combination of a server side TLS chain, // the client chain processor, and the distribution's CA bundle results in an incomplete/untrusted // certificate chain. See https://github.com/dotnet/corefx/issues/9244 for more details. if (PlatformDetection.IsDebian8) { // Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => { Assert.InRange(chain.ChainStatus.Length, 0, 1); if (chain.ChainStatus.Length > 0) { Assert.Equal(X509ChainStatusFlags.PartialChain, chain.ChainStatus[0].Status); } return true; }; } using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True( response.Version == new Version(2, 0) || response.Version == new Version(1, 1), "Response version " + response.Version); } } } private async Task<Version> SendRequestAndGetRequestVersionAsync(Version requestVersion) { Version receivedRequestVersion = null; await LoopbackServer.CreateServerAsync(async (server, url) => { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Version = requestVersion; using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.SendAsync(request); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { string statusLine = reader.ReadLine(); while (!string.IsNullOrEmpty(reader.ReadLine())) ; if (statusLine.Contains("/1.0")) { receivedRequestVersion = new Version(1, 0); } else if (statusLine.Contains("/1.1")) { receivedRequestVersion = new Version(1, 1); } else { Assert.True(false, "Invalid HTTP request version"); } await writer.WriteAsync( $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 0\r\n" + "\r\n"); s.Shutdown(SocketShutdown.Send); }); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }); return receivedRequestVersion; } #endregion #region Proxy tests [Theory] [MemberData(nameof(CredentialsForProxy))] public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache) { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: creds != null && creds != CredentialCache.DefaultCredentials, expectCreds: true); Uri proxyUrl = new Uri($"http://localhost:{port}"); const string BasicAuth = "Basic"; if (wrapCredsInCache) { Assert.IsAssignableFrom<NetworkCredential>(creds); var cache = new CredentialCache(); cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds); creds = cache; } using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer); Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap(); Task.WaitAll(proxyTask, responseTask, responseStringTask); TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null); Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result); NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth); string expectedAuth = nc == null || nc == CredentialCache.DefaultCredentials ? null : string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" : $"{nc.Domain}\\{nc.UserName}:{nc.Password}"; Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue); } } [Theory] [MemberData(nameof(BypassedProxies))] public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy) { using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy })) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } [Fact] public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode() { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: true, expectCreds: false); Uri proxyUrl = new Uri($"http://localhost:{port}"); using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer); Task.WaitAll(proxyTask, responseTask); Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode); } } private static IEnumerable<object[]> BypassedProxies() { yield return new object[] { null }; yield return new object[] { new PlatformNotSupportedWebProxy() }; yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) }; } private static IEnumerable<object[]> CredentialsForProxy() { yield return new object[] { null, false }; foreach (bool wrapCredsInCache in new[] { true, false }) { yield return new object[] { CredentialCache.DefaultCredentials, wrapCredsInCache }; yield return new object[] { new NetworkCredential("user:name", "password"), wrapCredsInCache }; yield return new object[] { new NetworkCredential("username", "password", "dom:\\ain"), wrapCredsInCache }; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// BackupEnginesOperations operations. /// </summary> internal partial class BackupEnginesOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupEnginesOperations { /// <summary> /// Initializes a new instance of the BackupEnginesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BackupEnginesOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Backup management servers registered to Recovery Services Vault. Returns a /// pageable list of servers. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<BackupEngineBaseResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, ODataQuery<BMSBackupEnginesQueryObject> odataQuery = default(ODataQuery<BMSBackupEnginesQueryObject>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupEngines").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<BackupEngineBaseResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<BackupEngineBaseResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns backup management server registered to Recovery Services Vault. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='backupEngineName'> /// Name of the backup management server. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BackupEngineBaseResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string backupEngineName, ODataQuery<BMSBackupEngineQueryObject> odataQuery = default(ODataQuery<BMSBackupEngineQueryObject>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (backupEngineName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "backupEngineName"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("backupEngineName", backupEngineName); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupEngines/{backupEngineName}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{backupEngineName}", System.Uri.EscapeDataString(backupEngineName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BackupEngineBaseResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupEngineBaseResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Backup management servers registered to Recovery Services Vault. Returns a /// pageable list of servers. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<BackupEngineBaseResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<BackupEngineBaseResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<BackupEngineBaseResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Text; using lpsolve55; using System.IO; using System.Diagnostics; namespace ICSimulator { public interface MemSched { void tick(); MemoryRequest get_next_req(MemCtlr mem); bool issue_req(MemoryRequest req); void remove_req(MemoryRequest req); bool is_empty(); bool is_full(int threadID); void flush_reads(); } public abstract class AbstractMemSched : MemSched { /**************************************************************** * ------ Scheduler parameters ----- ***************************************************************/ public int bank_max; //total number of banks public int buf_size; //sum of size of all bank-specific buffers and remaining shared buffer public int shared_size; //size of shared buffer that is shared among all banks when their own buffers overflow /**************************************************************** * ------ Statistics and reporting ----- ***************************************************************/ public MemSchedStat stat; /**************************************************************** * ------ Components ----- ***************************************************************/ public Bank[] bank; //array of banks public MemoryRequest[,] buf; //buffer for memory requests; [bank_index, buffer_index] public int[] buf_load; //for each buffer, the number of memory requests in it /**************************************************************** * ------ Scheduler status ----- ***************************************************************/ //load public int cur_load; //number of current requests public int cur_nonwb_load; //number of curent non-writeback requests public int cur_shared_load; //number of current requests in shared buffer //load per proc public int[] cur_load_per_proc; //number of current requests per processor public int[,] cur_load_per_procbank; //number of current requests per processor for each bank [proc, bank] public int[] cur_nonwb_per_proc; //number of current non-writeback requests per processor public int[,] cur_nonwb_per_procbank; //number of current non-writeback requests per processor for each bank [proc, bank] //max-load per proc public int[] cur_max_load_per_proc; //maximum load across banks per processor /**************************************************************** * ------ Scheduling algorithm helper ----- ***************************************************************/ public MemSchedHelper helper; /**************************************************************** * ------ Etc ----- ***************************************************************/ public const ulong EMPTY_SLOT = ulong.MaxValue; public int[] bankRank; public int[,] bankRankPerThread; /** * Constructor */ protected AbstractMemSched(int buf_size, Bank[] bank) { //parameters bank_max = bank.Length; //shared MC see global, non-shared this.buf_size = buf_size; shared_size = buf_size - Config.N * Config.memory.buf_size_per_proc; Debug.Assert(shared_size >= 0); //components this.bank = bank; buf = new MemoryRequest[bank_max, buf_size]; buf_load = new int[bank_max]; //load cur_load = 0; cur_nonwb_load = 0; cur_shared_load = 0; //load per proc cur_load_per_proc = new int[Config.N]; cur_load_per_procbank = new int[Config.N, bank_max]; cur_nonwb_per_proc = new int[Config.N]; cur_nonwb_per_procbank = new int[Config.N, bank_max]; bankRank = new int[Config.N]; bankRankPerThread = new int[Config.memory.mem_max * Config.memory.bank_max_per_mem,Config.N]; //max-load per proc cur_max_load_per_proc = new int[Config.N]; //helper helper = new MemSchedHelper(bank, bank_max, cur_max_load_per_proc); //stat stat = new MemSchedStat(Config.N, bank, bank_max); } /** * This method returns the next request to be scheduled (sent over the bus). * Each memory request scheduler needs to implement its own function */ abstract public MemoryRequest get_next_req(MemCtlr mem); /** * This function can be implemented if the scheduler needs to make updates in every cycle */ virtual public void tick() { //----- STATS START ----- for (int p = 0; p < Config.N; p++) { stat.inc(p, ref stat.tick_load_per_proc[p], (ulong)cur_load_per_proc[p]); if (BankStat.req_cnt[p] > 0) { stat.inc(p, ref stat.tick_req[p]); stat.inc(p, ref stat.tick_req_cnt[p], (ulong)BankStat.req_cnt[p]); } if (BankStat.marked_req_cnt[p] > 0) { stat.inc(p, ref stat.tick_marked[p]); stat.inc(p, ref stat.tick_marked_req[p], (ulong)BankStat.marked_req_cnt[p]); } if (BankStat.unmarked_req_cnt[p] > 0) { stat.inc(p, ref stat.tick_unmarked[p]); stat.inc(p, ref stat.tick_unmarked_req[p], (ulong)BankStat.unmarked_req_cnt[p]); } } //----- STATS END ----- } /** * Removes a request from the memory request buffer when it is finished. The implementation * removes this request from the memory request buffer and updates all statistic * variables. If some data structure needs to be updated for the scheduler, this * method should be overriden */ virtual public void remove_req(MemoryRequest req) { int bank_index = req.glob_b_index; int slot = req.buf_index; Debug.Assert(buf[bank_index, slot] == req); //overwrite last req to the req to be removed int buf_last_index = buf_load[bank_index] - 1; buf[bank_index, buf_last_index].buf_index = slot; buf[bank_index, slot] = buf[bank_index, buf_last_index]; //clear the last buffer entry buf[bank_index, buf_last_index] = null; buf_load[bank_index]--; Debug.Assert(buf_load[bank_index] >= 0); //----- STATS START ----- //shared load needs to be updated before cur_load_per_proc if (cur_load_per_proc[req.request.requesterID] > Config.memory.buf_size_per_proc) { cur_shared_load--; } cur_load--; cur_load_per_proc[req.request.requesterID]--; cur_load_per_procbank[req.request.requesterID, req.glob_b_index]--; Debug.Assert(cur_load >= 0); Debug.Assert(cur_load_per_proc[req.request.requesterID] >= 0); Debug.Assert(cur_load_per_procbank[req.request.requesterID, req.glob_b_index] >= 0); if (req.type != MemoryRequestType.WB) { cur_nonwb_load--; cur_nonwb_per_proc[req.request.requesterID]--; cur_nonwb_per_procbank[req.request.requesterID, req.glob_b_index]--; } //----- STATS END ------ //find maximum load for any bank for this request cur_max_load_per_proc[req.request.requesterID] = 0; for (int b = 0; b < bank_max; b++) if (cur_max_load_per_proc[req.request.requesterID] < cur_load_per_procbank[req.request.requesterID, b]) cur_max_load_per_proc[req.request.requesterID] = cur_load_per_procbank[req.request.requesterID, b]; } /** * This method is called when a new request is inserted into the memory request buffer. * If the buffer is full, an exception is thrown. If the scheduler needs to maintain * some extra data structures, it should override this method */ virtual public bool issue_req(MemoryRequest req) { Debug.Assert(cur_load != buf_size); //time of arrival req.timeOfArrival = MemCtlr.cycle; //----- STATS START ----- stat.inc(req.request.requesterID, ref stat.total_req_per_procbank[req.request.requesterID, req.glob_b_index]); cur_load++; cur_load_per_proc[req.request.requesterID]++; cur_load_per_procbank[req.request.requesterID, req.glob_b_index]++; //shared load needs to be updated after cur_load_per_proc if (cur_load_per_proc[req.request.requesterID] > Config.memory.buf_size_per_proc) cur_shared_load++; if (req.type != MemoryRequestType.WB) { cur_nonwb_load++; cur_nonwb_per_proc[req.request.requesterID]++; cur_nonwb_per_procbank[req.request.requesterID, req.glob_b_index]++; } //----- STATS END ------ //set maximum load for any bank for this request if (cur_max_load_per_proc[req.request.requesterID] < cur_load_per_procbank[req.request.requesterID, req.glob_b_index]) cur_max_load_per_proc[req.request.requesterID] = cur_load_per_procbank[req.request.requesterID, req.glob_b_index]; //add request to end of the request buffer buf[req.glob_b_index, buf_load[req.glob_b_index]] = req; req.buf_index = buf_load[req.glob_b_index]; buf_load[req.glob_b_index]++; return true; } virtual public void flush_reads() { for (int i = 0; i < bank_max; i++) for (int j = 0; j < buf_size; j++) if (buf[i, j] != null && buf[i, j].type != MemoryRequestType.WB) remove_req(buf[i, j]); for (int i = 0; i < bank_max; i++) if (bank[i].cur_req != null && bank[i].cur_req.type != MemoryRequestType.WB) bank[i].cur_req = null; } /** * Returns true if the buffer is empty */ virtual public bool is_empty() { return cur_load == 0; } /** * Returns true if the buffer is full */ virtual public bool is_full(int threadID) { return (cur_shared_load >= buf_size - Config.N * Config.memory.buf_size_per_proc) && (cur_load_per_proc[threadID] >= Config.memory.buf_size_per_proc); } /** * Returns the fraction of Writebacks in the request buffer */ protected double get_wb_fraction() { return (double)(cur_load - cur_nonwb_load) / buf_size; } /** * Collects statistics from thread procID */ public virtual void freeze_stat(int threadID) { stat.freeze_stat(threadID); } /** * Collects statistics from thread procID */ public virtual void report(TextWriter writer, int threadID) { stat.report(writer, threadID); } public virtual void report_verbose(TextWriter writer, int procID, string trace_name) { stat.report_verbose(writer, procID, trace_name); } public virtual void report_excel(TextWriter writer) { stat.report_excel(writer); } /** * Write the output for Memory Schedulers here! */ public virtual void report(TextWriter writer) { stat.report(writer); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities; using System; using UnityEngine; /// <summary> /// Provides per-frame data access to simulated hand data /// /// Controls for mouse/keyboard simulation: /// - Press spacebar to turn right hand on/off /// - Left mouse button brings index and thumb together /// - Mouse moves left and right hand. /// </summary> namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Internal class to define current gesture and smoothly animate hand data points. /// </summary> internal class SimulatedHandState : SimulatedControllerState { // Activate the pinch gesture // Pinch is a special gesture that triggers the Select and TriggerPress input actions // The pinch action doesn't occur until the gesture is completed. public bool IsPinching => gesture == ArticulatedHandPose.GestureId.Pinch && gestureBlending == 1.0f; private ArticulatedHandPose.GestureId gesture = ArticulatedHandPose.GestureId.None; public ArticulatedHandPose.GestureId Gesture { get { return gesture; } set { if (value != ArticulatedHandPose.GestureId.None && value != gesture) { gesture = value; gestureBlending = 0.0f; } } } // Interpolation between current pose and target gesture private float gestureBlending = 0.0f; public float GestureBlending { get { return gestureBlending; } set { gestureBlending = Mathf.Clamp(value, gestureBlending, 1.0f); } } private float poseBlending = 0.0f; private ArticulatedHandPose pose = new ArticulatedHandPose(); public SimulatedHandState(Handedness _handedness) : base(_handedness) { } public void ResetGesture() { gestureBlending = 1.0f; ArticulatedHandPose gesturePose = SimulatedArticulatedHandPoses.GetGesturePose(gesture); if (gesturePose != null) { pose.Copy(gesturePose); } } public override void ResetRotation() { ViewportRotation = Vector3.zero; } internal void FillCurrentFrame(MixedRealityPose[] jointsOut) { ArticulatedHandPose gesturePose = SimulatedArticulatedHandPoses.GetGesturePose(gesture); if (gesturePose != null) { if (gestureBlending > poseBlending) { float range = Mathf.Clamp01(1.0f - poseBlending); float lerpFactor = range > 0.0f ? (gestureBlending - poseBlending) / range : 1.0f; pose.InterpolateOffsets(pose, gesturePose, lerpFactor); } } poseBlending = gestureBlending; Vector3 screenPosition = CameraCache.Main.ViewportToScreenPoint(ViewportPosition); Vector3 worldPosition = CameraCache.Main.ScreenToWorldPoint(screenPosition + JitterOffset); Quaternion worldRotation = CameraCache.Main.transform.rotation * Quaternion.Euler(ViewportRotation); pose.ComputeJointPoses(handedness, worldRotation, worldPosition, jointsOut); } } /// <summary> /// Produces simulated data every frame that defines joint positions. /// </summary> public class SimulatedHandDataProvider : SimulatedControllerDataProvider { // Cached delegates for hand joint generation private SimulatedHandData.HandJointDataGenerator generatorLeft; private SimulatedHandData.HandJointDataGenerator generatorRight; private SimulatedHandData.HandJointDataGenerator generatorGaze; public SimulatedHandDataProvider(MixedRealityInputSimulationProfile _profile) : base(_profile) { InputStateLeft = new SimulatedHandState(Handedness.Left); InputStateRight = new SimulatedHandState(Handedness.Right); InputStateGaze = new SimulatedHandState(Handedness.None); SimulatedHandState handStateLeft = InputStateLeft as SimulatedHandState; SimulatedHandState handStateRight = InputStateRight as SimulatedHandState; SimulatedHandState handStateGaze = InputStateGaze as SimulatedHandState; handStateLeft.Gesture = profile.DefaultHandGesture; handStateRight.Gesture = profile.DefaultHandGesture; handStateGaze.Gesture = profile.DefaultHandGesture; } /// <summary> /// Capture a snapshot of simulated hand data based on current state. /// </summary> public bool UpdateHandData(SimulatedHandData handDataLeft, SimulatedHandData handDataRight, SimulatedHandData handDataGaze, MouseDelta mouseDelta) { SimulateUserInput(mouseDelta); SimulatedHandState handStateLeft = InputStateLeft as SimulatedHandState; SimulatedHandState handStateRight = InputStateRight as SimulatedHandState; SimulatedHandState handStateGaze = InputStateGaze as SimulatedHandState; handStateLeft.Update(); handStateRight.Update(); handStateGaze.Update(); bool handDataChanged = false; // Cache the generator delegates so we don't gc alloc every frame if (generatorLeft == null) { generatorLeft = handStateLeft.FillCurrentFrame; } if (generatorRight == null) { generatorRight = handStateRight.FillCurrentFrame; } if (generatorGaze == null) { generatorGaze = handStateGaze.FillCurrentFrame; } handDataChanged |= handDataLeft.Update(handStateLeft.IsTracked, handStateLeft.IsPinching, generatorLeft); handDataChanged |= handDataRight.Update(handStateRight.IsTracked, handStateRight.IsPinching, generatorRight); handDataChanged |= handDataGaze.Update(handStateGaze.IsTracked, handStateGaze.IsPinching, generatorGaze); return handDataChanged; } /// <summary> /// Update hand state based on keyboard and mouse input /// </summary> protected override void SimulateUserInput(MouseDelta mouseDelta) { base.SimulateUserInput(mouseDelta); SimulatedHandState handStateLeft = InputStateLeft as SimulatedHandState; SimulatedHandState handStateRight = InputStateRight as SimulatedHandState; SimulatedHandState handStateGaze = InputStateGaze as SimulatedHandState; // This line explicitly uses unscaledDeltaTime because we don't want input simulation // to lag when the time scale is set to a value other than 1. Input should still continue // to move freely. float gestureAnimDelta = profile.HandGestureAnimationSpeed * Time.unscaledDeltaTime; handStateLeft.GestureBlending += gestureAnimDelta; handStateRight.GestureBlending += gestureAnimDelta; handStateGaze.GestureBlending = 1.0f; } /// Apply changes to one hand and update tracking internal override void SimulateInput( ref long lastHandTrackedTimestamp, SimulatedControllerState state, bool isSimulating, bool isAlwaysVisible, MouseDelta mouseDelta, bool useMouseRotation) { var handState = state as SimulatedHandState; bool enableTracking = isAlwaysVisible || isSimulating; if (!handState.IsTracked && enableTracking) { ResetInput(handState, isSimulating); } if (isSimulating) { handState.SimulateInput(mouseDelta, useMouseRotation, profile.MouseRotationSensitivity, profile.MouseControllerRotationSpeed, profile.ControllerJitterAmount); if (isAlwaysVisible) { // Toggle gestures on/off handState.Gesture = ToggleGesture(handState.Gesture); } else { // Enable gesture while mouse button is pressed handState.Gesture = SelectGesture(); } } // Update tracked state of a hand. // If hideTimeout value is null, hands will stay visible after tracking stops. // TODO: DateTime.UtcNow can be quite imprecise, better use Stopwatch.GetTimestamp // https://stackoverflow.com/questions/2143140/c-sharp-datetime-now-precision DateTime currentTime = DateTime.UtcNow; if (enableTracking) { handState.IsTracked = true; lastHandTrackedTimestamp = currentTime.Ticks; } else { float timeSinceTracking = (float)currentTime.Subtract(new DateTime(lastHandTrackedTimestamp)).TotalSeconds; if (timeSinceTracking > profile.ControllerHideTimeout) { handState.IsTracked = false; } } } internal override void ResetInput(SimulatedControllerState state, bool isSimulating) { base.ResetInput(state, isSimulating); var handState = state as SimulatedHandState; handState.Gesture = profile.DefaultHandGesture; handState.ResetGesture(); handState.ResetRotation(); } /// <summary> /// Gets the currently active gesture, according to the mouse configuration and mouse button that is down. /// </summary> private ArticulatedHandPose.GestureId SelectGesture() { // Each check needs to verify that both: // 1) The corresponding mouse button is down (meaning the gesture, if defined, should be used) // 2) The gesture is defined. // If only #1 is checked and #2 is not checked, it's possible to "miss" transitions in cases where the user has // the left mouse button down and then while it is down, presses the right button, and then lifts the left. // It's not until both mouse buttons lift in that case, that the state finally "rests" to the DefaultHandGesture. if (KeyInputSystem.GetKey(profile.InteractionButton) && profile.LeftMouseHandGesture != ArticulatedHandPose.GestureId.None) { return profile.LeftMouseHandGesture; } else if (KeyInputSystem.GetKey(profile.MouseLookButton) && profile.RightMouseHandGesture != ArticulatedHandPose.GestureId.None) { return profile.RightMouseHandGesture; } else if (KeyInputSystem.GetKey(KeyBinding.FromMouseButton(KeyBinding.MouseButton.Middle)) && profile.MiddleMouseHandGesture != ArticulatedHandPose.GestureId.None) { return profile.MiddleMouseHandGesture; } else { return profile.DefaultHandGesture; } } private ArticulatedHandPose.GestureId ToggleGesture(ArticulatedHandPose.GestureId gesture) { // See comments in SelectGesture for why both the button down and gesture are checked. if (KeyInputSystem.GetKeyDown(profile.InteractionButton) && profile.LeftMouseHandGesture != ArticulatedHandPose.GestureId.None) { return (gesture != profile.LeftMouseHandGesture ? profile.LeftMouseHandGesture : profile.DefaultHandGesture); } else if (KeyInputSystem.GetKeyDown(profile.MouseLookButton) && profile.RightMouseHandGesture != ArticulatedHandPose.GestureId.None) { return (gesture != profile.RightMouseHandGesture ? profile.RightMouseHandGesture : profile.DefaultHandGesture); } else if (KeyInputSystem.GetKeyDown(KeyBinding.FromMouseButton(KeyBinding.MouseButton.Middle)) && profile.MiddleMouseHandGesture != ArticulatedHandPose.GestureId.None) { return (gesture != profile.MiddleMouseHandGesture ? profile.MiddleMouseHandGesture : profile.DefaultHandGesture); } else { // 'None' will not change the gesture return ArticulatedHandPose.GestureId.None; } } #region Obsolete Fields [Obsolete("Use InputStateLeft instead.")] internal SimulatedHandState HandStateLeft { get => InputStateLeft as SimulatedHandState; set { InputStateLeft = value; } } [Obsolete("Use InputStateRight instead.")] internal SimulatedHandState HandStateRight { get => InputStateRight as SimulatedHandState; set { InputStateRight = value; } } [Obsolete("Use InputStateGaze instead.")] internal SimulatedHandState HandStateGaze { get => InputStateGaze as SimulatedHandState; set { InputStateGaze = value; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace System.Net { [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public enum CookieVariant { Unknown, Plain, Rfc2109, Rfc2965, Default = Rfc2109 } // Cookie class // // Adheres to RFC 2965 // // Currently, only represents client-side cookies. The cookie classes know // how to parse a set-cookie format string, but not a cookie format string // (e.g. "Cookie: $Version=1; name=value; $Path=/foo; $Secure") [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class Cookie { // NOTE: these two constants must change together. internal const int MaxSupportedVersion = 1; internal const string MaxSupportedVersionString = "1"; internal const string SeparatorLiteral = "; "; internal const string EqualsLiteral = "="; internal const string QuotesLiteral = "\""; internal const string SpecialAttributeLiteral = "$"; internal static readonly char[] PortSplitDelimiters = new char[] { ' ', ',', '\"' }; internal static readonly char[] ReservedToName = new char[] { ' ', '\t', '\r', '\n', '=', ';', ',' }; internal static readonly char[] ReservedToValue = new char[] { ';', ',' }; private string m_comment = string.Empty; // Do not rename (binary serialization) private Uri m_commentUri = null; // Do not rename (binary serialization) private CookieVariant m_cookieVariant = CookieVariant.Plain; // Do not rename (binary serialization) private bool m_discard = false; // Do not rename (binary serialization) private string m_domain = string.Empty; // Do not rename (binary serialization) private bool m_domain_implicit = true; // Do not rename (binary serialization) private DateTime m_expires = DateTime.MinValue; // Do not rename (binary serialization) private string m_name = string.Empty; // Do not rename (binary serialization) private string m_path = string.Empty; // Do not rename (binary serialization) private bool m_path_implicit = true; // Do not rename (binary serialization) private string m_port = string.Empty; // Do not rename (binary serialization) private bool m_port_implicit = true; // Do not rename (binary serialization) private int[] m_port_list = null; // Do not rename (binary serialization) private bool m_secure = false; // Do not rename (binary serialization) [System.Runtime.Serialization.OptionalField] private bool m_httpOnly = false; // Do not rename (binary serialization) private DateTime m_timeStamp = DateTime.Now; // Do not rename (binary serialization) private string m_value = string.Empty; // Do not rename (binary serialization) private int m_version = 0; // Do not rename (binary serialization) private string m_domainKey = string.Empty; // Do not rename (binary serialization) /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif bool IsQuotedVersion = false; /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif bool IsQuotedDomain = false; #if DEBUG static Cookie() { Debug.Assert(MaxSupportedVersion.ToString(NumberFormatInfo.InvariantInfo).Equals(MaxSupportedVersionString, StringComparison.Ordinal)); } #endif public Cookie() { } public Cookie(string name, string value) { Name = name; Value = value; } public Cookie(string name, string value, string path) : this(name, value) { Path = path; } public Cookie(string name, string value, string path, string domain) : this(name, value, path) { Domain = domain; } public string Comment { get { return m_comment; } set { m_comment = value ?? string.Empty; } } public Uri CommentUri { get { return m_commentUri; } set { m_commentUri = value; } } public bool HttpOnly { get { return m_httpOnly; } set { m_httpOnly = value; } } public bool Discard { get { return m_discard; } set { m_discard = value; } } public string Domain { get { return m_domain; } set { m_domain = value ?? string.Empty; m_domain_implicit = false; m_domainKey = string.Empty; // _domainKey will be set when adding this cookie to a container. } } internal bool DomainImplicit { get { return m_domain_implicit; } set { m_domain_implicit = value; } } public bool Expired { get { return (m_expires != DateTime.MinValue) && (m_expires.ToLocalTime() <= DateTime.Now); } set { if (value == true) { m_expires = DateTime.Now; } } } public DateTime Expires { get { return m_expires; } set { m_expires = value; } } public string Name { get { return m_name; } set { if (string.IsNullOrEmpty(value) || !InternalSetName(value)) { throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", value == null ? "<null>" : value)); } } } /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif bool InternalSetName(string value) { if (string.IsNullOrEmpty(value) || value[0] == '$' || value.IndexOfAny(ReservedToName) != -1) { m_name = string.Empty; return false; } m_name = value; return true; } public string Path { get { return m_path; } set { m_path = value ?? string.Empty; m_path_implicit = false; } } internal bool Plain { get { return Variant == CookieVariant.Plain; } } /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif Cookie Clone() { Cookie clonedCookie = new Cookie(m_name, m_value); // Copy over all the properties from the original cookie if (!m_port_implicit) { clonedCookie.Port = m_port; } if (!m_path_implicit) { clonedCookie.Path = m_path; } clonedCookie.Domain = m_domain; // If the domain in the original cookie was implicit, we should preserve that property clonedCookie.DomainImplicit = m_domain_implicit; clonedCookie.m_timeStamp = m_timeStamp; clonedCookie.Comment = m_comment; clonedCookie.CommentUri = m_commentUri; clonedCookie.HttpOnly = m_httpOnly; clonedCookie.Discard = m_discard; clonedCookie.Expires = m_expires; clonedCookie.Version = m_version; clonedCookie.Secure = m_secure; // The variant is set when we set properties like port/version. So, // we should copy over the variant from the original cookie after // we set all other properties clonedCookie.m_cookieVariant = m_cookieVariant; return clonedCookie; } private static bool IsDomainEqualToHost(string domain, string host) { // +1 in the host length is to account for the leading dot in domain return (host.Length + 1 == domain.Length) && (string.Compare(host, 0, domain, 1, host.Length, StringComparison.OrdinalIgnoreCase) == 0); } // According to spec we must assume default values for attributes but still // keep in mind that we must not include them into the requests. // We also check the validity of all attributes based on the version and variant (read RFC) // // To work properly this function must be called after cookie construction with // default (response) URI AND setDefault == true // // Afterwards, the function can be called many times with other URIs and // setDefault == false to check whether this cookie matches given uri internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDomain, string localDomain, bool setDefault, bool shouldThrow) { string host = uri.Host; int port = uri.Port; string path = uri.AbsolutePath; bool valid = true; if (setDefault) { // Set Variant. If version is zero => reset cookie to Version0 style if (Version == 0) { variant = CookieVariant.Plain; } else if (Version == 1 && variant == CookieVariant.Unknown) { // Since we don't expose Variant to an app, set it to Default variant = CookieVariant.Default; } m_cookieVariant = variant; } // Check the name if (m_name == null || m_name.Length == 0 || m_name[0] == '$' || m_name.IndexOfAny(ReservedToName) != -1) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", m_name == null ? "<null>" : m_name)); } return false; } // Check the value if (m_value == null || (!(m_value.Length > 2 && m_value[0] == '\"' && m_value[m_value.Length - 1] == '\"') && m_value.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, "Value", m_value == null ? "<null>" : m_value)); } return false; } // Check Comment syntax if (Comment != null && !(Comment.Length > 2 && Comment[0] == '\"' && Comment[Comment.Length - 1] == '\"') && (Comment.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.CommentAttributeName, Comment)); } return false; } // Check Path syntax if (Path != null && !(Path.Length > 2 && Path[0] == '\"' && Path[Path.Length - 1] == '\"') && (Path.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PathAttributeName, Path)); } return false; } // Check/set domain // // If domain is implicit => assume a) uri is valid, b) just set domain to uri hostname. if (setDefault && m_domain_implicit == true) { m_domain = host; } else { if (!m_domain_implicit) { // Forwarding note: If Uri.Host is of IP address form then the only supported case // is for IMPLICIT domain property of a cookie. // The code below (explicit cookie.Domain value) will try to parse Uri.Host IP string // as a fqdn and reject the cookie. // Aliasing since we might need the KeyValue (but not the original one). string domain = m_domain; // Syntax check for Domain charset plus empty string. if (!DomainCharsTest(domain)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, domain == null ? "<null>" : domain)); } return false; } // Domain must start with '.' if set explicitly. if (domain[0] != '.') { if (!(variant == CookieVariant.Rfc2965 || variant == CookieVariant.Plain)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, m_domain)); } return false; } domain = '.' + domain; } int host_dot = host.IndexOf('.'); // First quick check is for pushing a cookie into the local domain. if (isLocalDomain && string.Equals(localDomain, domain, StringComparison.OrdinalIgnoreCase)) { valid = true; } else if (domain.IndexOf('.', 1, domain.Length - 2) == -1) { // A single label domain is valid only if the domain is exactly the same as the host specified in the URI. if (!IsDomainEqualToHost(domain, host)) { valid = false; } } else if (variant == CookieVariant.Plain) { // We distinguish between Version0 cookie and other versions on domain issue. // According to Version0 spec a domain must be just a substring of the hostname. if (!IsDomainEqualToHost(domain, host)) { if (host.Length <= domain.Length || (string.Compare(host, host.Length - domain.Length, domain, 0, domain.Length, StringComparison.OrdinalIgnoreCase) != 0)) { valid = false; } } } else if (host_dot == -1 || domain.Length != host.Length - host_dot || (string.Compare(host, host_dot, domain, 0, domain.Length, StringComparison.OrdinalIgnoreCase) != 0)) { // Starting from the first dot, the host must match the domain. // // For null hosts, the host must match the domain exactly. if (!IsDomainEqualToHost(domain, host)) { valid = false; } } if (valid) { m_domainKey = domain.ToLowerInvariant(); } } else { // For implicitly set domain AND at the set_default == false time // we simply need to match uri.Host against m_domain. if (!string.Equals(host, m_domain, StringComparison.OrdinalIgnoreCase)) { valid = false; } } if (!valid) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, m_domain)); } return false; } } // Check/Set Path if (setDefault && m_path_implicit == true) { // This code assumes that the URI path is always valid and contains at least one '/'. switch (m_cookieVariant) { case CookieVariant.Plain: m_path = path; break; case CookieVariant.Rfc2109: m_path = path.Substring(0, path.LastIndexOf('/')); // May be empty break; case CookieVariant.Rfc2965: default: // NOTE: this code is not resilient against future versions with different 'Path' semantics. m_path = path.Substring(0, path.LastIndexOf('/') + 1); break; } } else { // Check current path (implicit/explicit) against given URI. if (!path.StartsWith(CookieParser.CheckQuoted(m_path))) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PathAttributeName, m_path)); } return false; } } // Set the default port if Port attribute was present but had no value. if (setDefault && (m_port_implicit == false && m_port.Length == 0)) { m_port_list = new int[1] { port }; } if (m_port_implicit == false) { // Port must match against the one from the uri. valid = false; foreach (int p in m_port_list) { if (p == port) { valid = true; break; } } if (!valid) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, m_port)); } return false; } } return true; } // Very primitive test to make sure that the name does not have illegal characters // as per RFC 952 (relaxed on first char could be a digit and string can have '_'). private static bool DomainCharsTest(string name) { if (name == null || name.Length == 0) { return false; } for (int i = 0; i < name.Length; ++i) { char ch = name[i]; if (!((ch >= '0' && ch <= '9') || (ch == '.' || ch == '-') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '_'))) { return false; } } return true; } public string Port { get { return m_port; } set { m_port_implicit = false; if (string.IsNullOrEmpty(value)) { // "Port" is present but has no value. m_port = string.Empty; } else { // Parse port list if (value[0] != '\"' || value[value.Length - 1] != '\"') { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value)); } string[] ports = value.Split(PortSplitDelimiters); List<int> portList = new List<int>(); int port; for (int i = 0; i < ports.Length; ++i) { // Skip spaces if (ports[i] != string.Empty) { if (!int.TryParse(ports[i], out port)) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value)); } // valid values for port 0 - 0xFFFF if ((port < 0) || (port > 0xFFFF)) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value)); } portList.Add(port); } } m_port_list = portList.ToArray(); m_port = value; m_version = MaxSupportedVersion; m_cookieVariant = CookieVariant.Rfc2965; } } } internal int[] PortList { get { // PortList will be null if Port Attribute was omitted in the response. return m_port_list; } } public bool Secure { get { return m_secure; } set { m_secure = value; } } public DateTime TimeStamp { get { return m_timeStamp; } } public string Value { get { return m_value; } set { m_value = value ?? string.Empty; } } /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif CookieVariant Variant { get { return m_cookieVariant; } set { // Only set by HttpListenerRequest::Cookies_get() if (value != CookieVariant.Rfc2965) { NetEventSource.Fail(this, $"value != Rfc2965:{value}"); } m_cookieVariant = value; } } // _domainKey member is set internally in VerifySetDefaults(). // If it is not set then verification function was not called; // this should never happen. internal string DomainKey { get { return m_domain_implicit ? Domain : m_domainKey; } } public int Version { get { return m_version; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } m_version = value; if (value > 0 && m_cookieVariant < CookieVariant.Rfc2109) { m_cookieVariant = CookieVariant.Rfc2109; } } } public override bool Equals(object comparand) { Cookie other = comparand as Cookie; return other != null && string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(Value, other.Value, StringComparison.Ordinal) && string.Equals(Path, other.Path, StringComparison.Ordinal) && string.Equals(Domain, other.Domain, StringComparison.OrdinalIgnoreCase) && (Version == other.Version); } public override int GetHashCode() { return (Name + "=" + Value + ";" + Path + "; " + Domain + "; " + Version).GetHashCode(); } public override string ToString() { StringBuilder sb = StringBuilderCache.Acquire(); ToString(sb); return StringBuilderCache.GetStringAndRelease(sb); } internal void ToString(StringBuilder sb) { int beforeLength = sb.Length; // Add the Cookie version if necessary. if (Version != 0) { sb.Append(SpecialAttributeLiteral + CookieFields.VersionAttributeName + EqualsLiteral); // const strings if (IsQuotedVersion) sb.Append('"'); sb.Append(m_version.ToString(NumberFormatInfo.InvariantInfo)); if (IsQuotedVersion) sb.Append('"'); sb.Append(SeparatorLiteral); } // Add the Cookie Name=Value pair. sb.Append(Name).Append(EqualsLiteral).Append(Value); if (!Plain) { // Add the Path if necessary. if (!m_path_implicit && m_path.Length > 0) { sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.PathAttributeName + EqualsLiteral); // const strings sb.Append(m_path); } // Add the Domain if necessary. if (!m_domain_implicit && m_domain.Length > 0) { sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.DomainAttributeName + EqualsLiteral); // const strings if (IsQuotedDomain) sb.Append('"'); sb.Append(m_domain); if (IsQuotedDomain) sb.Append('"'); } } // Add the Port if necessary. if (!m_port_implicit) { sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.PortAttributeName); // const strings if (m_port.Length > 0) { sb.Append(EqualsLiteral); sb.Append(m_port); } } // Check to see whether the only thing we added was "=", and if so, // remove it so that we leave the StringBuilder unchanged in contents. int afterLength = sb.Length; if (afterLength == (1 + beforeLength) && sb[beforeLength] == '=') { sb.Length = beforeLength; } } /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif string ToServerString() { string result = Name + EqualsLiteral + Value; if (m_comment != null && m_comment.Length > 0) { result += SeparatorLiteral + CookieFields.CommentAttributeName + EqualsLiteral + m_comment; } if (m_commentUri != null) { result += SeparatorLiteral + CookieFields.CommentUrlAttributeName + EqualsLiteral + QuotesLiteral + m_commentUri.ToString() + QuotesLiteral; } if (m_discard) { result += SeparatorLiteral + CookieFields.DiscardAttributeName; } if (!m_domain_implicit && m_domain != null && m_domain.Length > 0) { result += SeparatorLiteral + CookieFields.DomainAttributeName + EqualsLiteral + m_domain; } if (Expires != DateTime.MinValue) { int seconds = (int)(Expires.ToLocalTime() - DateTime.Now).TotalSeconds; if (seconds < 0) { // This means that the cookie has already expired. Set Max-Age to 0 // so that the client will discard the cookie immediately. seconds = 0; } result += SeparatorLiteral + CookieFields.MaxAgeAttributeName + EqualsLiteral + seconds.ToString(NumberFormatInfo.InvariantInfo); } if (!m_path_implicit && m_path != null && m_path.Length > 0) { result += SeparatorLiteral + CookieFields.PathAttributeName + EqualsLiteral + m_path; } if (!Plain && !m_port_implicit && m_port != null && m_port.Length > 0) { // QuotesLiteral are included in _port. result += SeparatorLiteral + CookieFields.PortAttributeName + EqualsLiteral + m_port; } if (m_version > 0) { result += SeparatorLiteral + CookieFields.VersionAttributeName + EqualsLiteral + m_version.ToString(NumberFormatInfo.InvariantInfo); } return result == EqualsLiteral ? null : result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Transactions.Diagnostics; using System.Transactions.Distributed; namespace System.Transactions { public class TransactionEventArgs : EventArgs { internal Transaction _transaction; public Transaction Transaction => _transaction; } public delegate void TransactionCompletedEventHandler(object sender, TransactionEventArgs e); public enum IsolationLevel { Serializable = 0, RepeatableRead = 1, ReadCommitted = 2, ReadUncommitted = 3, Snapshot = 4, Chaos = 5, Unspecified = 6, } public enum TransactionStatus { Active = 0, Committed = 1, Aborted = 2, InDoubt = 3 } public enum DependentCloneOption { BlockCommitUntilComplete = 0, RollbackIfNotComplete = 1, } [Flags] public enum EnlistmentOptions { None = 0x0, EnlistDuringPrepareRequired = 0x1, } // When we serialize a Transaction, we specify the type DistributedTransaction, so a Transaction never // actually gets deserialized. [Serializable] public class Transaction : IDisposable, ISerializable { // UseServiceDomain // // Property tells parts of system.transactions if it should use a // service domain for current. [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static bool UseServiceDomainForCurrent() => false; // InteropMode // // This property figures out the current interop mode based on the // top of the transaction scope stack as well as the default mode // from config. internal static EnterpriseServicesInteropOption InteropMode(TransactionScope currentScope) { if (currentScope != null) { return currentScope.InteropMode; } return EnterpriseServicesInteropOption.None; } internal static Transaction FastGetTransaction(TransactionScope currentScope, ContextData contextData, out Transaction contextTransaction) { Transaction current = null; contextTransaction = null; contextTransaction = contextData.CurrentTransaction; switch (InteropMode(currentScope)) { case EnterpriseServicesInteropOption.None: current = contextTransaction; // If there is a transaction in the execution context or if there is a current transaction scope // then honer the transaction context. if (current == null && currentScope == null) { // Otherwise check for an external current. if (TransactionManager.s_currentDelegateSet) { current = TransactionManager.s_currentDelegate(); } else { current = EnterpriseServices.GetContextTransaction(contextData); } } break; case EnterpriseServicesInteropOption.Full: current = EnterpriseServices.GetContextTransaction(contextData); break; case EnterpriseServicesInteropOption.Automatic: if (EnterpriseServices.UseServiceDomainForCurrent()) { current = EnterpriseServices.GetContextTransaction(contextData); } else { current = contextData.CurrentTransaction; } break; } return current; } // GetCurrentTransactionAndScope // // Returns both the current transaction and scope. This is implemented for optimizations // in TransactionScope because it is required to get both of them in several cases. internal static void GetCurrentTransactionAndScope( TxLookup defaultLookup, out Transaction current, out TransactionScope currentScope, out Transaction contextTransaction) { current = null; currentScope = null; contextTransaction = null; ContextData contextData = ContextData.LookupContextData(defaultLookup); if (contextData != null) { currentScope = contextData.CurrentScope; current = FastGetTransaction(currentScope, contextData, out contextTransaction); } } public static Transaction Current { get { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceBase, "Transaction.get_Current"); } Transaction current = null; TransactionScope currentScope = null; Transaction contextValue = null; GetCurrentTransactionAndScope(TxLookup.Default, out current, out currentScope, out contextValue); if (currentScope != null) { if (currentScope.ScopeComplete) { throw new InvalidOperationException(SR.TransactionScopeComplete); } } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceBase, "Transaction.get_Current"); } return current; } set { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceBase, "Transaction.set_Current"); } // Bring your own Transaction(BYOT) is supported only for legacy scenarios. // This transaction won't be flown across thread continuations. if (InteropMode(ContextData.TLSCurrentData.CurrentScope) != EnterpriseServicesInteropOption.None) { if (DiagnosticTrace.Error) { InvalidOperationExceptionTraceRecord.Trace(SR.TraceSourceBase, SR.CannotSetCurrent); } throw new InvalidOperationException(SR.CannotSetCurrent); } // Support only legacy scenarios using TLS. ContextData.TLSCurrentData.CurrentTransaction = value; // Clear CallContext data. CallContextCurrentData.ClearCurrentData(null, false); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceBase, "Transaction.set_Current"); } } } // Storage for the transaction isolation level internal IsolationLevel _isoLevel; // Storage for the consistent flag internal bool _complete = false; // Record an identifier for this clone internal int _cloneId; // Storage for a disposed flag internal const int _disposedTrueValue = 1; internal int _disposed = 0; internal bool Disposed { get { return _disposed == Transaction._disposedTrueValue; } } internal Guid DistributedTxId { get { Guid returnValue = Guid.Empty; if (_internalTransaction != null) { returnValue = _internalTransaction.DistributedTxId; } return returnValue; } } // Internal synchronization object for transactions. It is not safe to lock on the // transaction object because it is public and users of the object may lock it for // other purposes. internal InternalTransaction _internalTransaction; // The TransactionTraceIdentifier for the transaction instance. internal TransactionTraceIdentifier _traceIdentifier; // Not used by anyone private Transaction() { } // Create a transaction with the given settings // internal Transaction(IsolationLevel isoLevel, InternalTransaction internalTransaction) { TransactionManager.ValidateIsolationLevel(isoLevel); _isoLevel = isoLevel; // Never create a transaction with an IsolationLevel of Unspecified. if (IsolationLevel.Unspecified == _isoLevel) { _isoLevel = TransactionManager.DefaultIsolationLevel; } if (internalTransaction != null) { _internalTransaction = internalTransaction; _cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount); } else { // Null is passed from the constructor of a CommittableTransaction. That // constructor will fill in the traceIdentifier because it has allocated the // internal transaction. } } internal Transaction(DistributedTransaction distributedTransaction) { _isoLevel = distributedTransaction.IsolationLevel; _internalTransaction = new InternalTransaction(this, distributedTransaction); _cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount); } internal Transaction(IsolationLevel isoLevel, ISimpleTransactionSuperior superior) { TransactionManager.ValidateIsolationLevel(isoLevel); if (superior == null) { throw new ArgumentNullException(nameof(superior)); } _isoLevel = isoLevel; // Never create a transaction with an IsolationLevel of Unspecified. if (IsolationLevel.Unspecified == _isoLevel) { _isoLevel = TransactionManager.DefaultIsolationLevel; } _internalTransaction = new InternalTransaction(this, superior); // ISimpleTransactionSuperior is defined to also promote to MSDTC. _internalTransaction.SetPromoterTypeToMSDTC(); _cloneId = 1; } #region System.Object Overrides // Don't use the identifier for the hash code. // public override int GetHashCode() { return _internalTransaction.TransactionHash; } // Don't allow equals to get the identifier // public override bool Equals(object obj) { Transaction transaction = obj as Transaction; // If we can't cast the object as a Transaction, it must not be equal // to this, which is a Transaction. if (null == transaction) { return false; } // Check the internal transaction object for equality. return _internalTransaction.TransactionHash == transaction._internalTransaction.TransactionHash; } public static bool operator ==(Transaction x, Transaction y) { if (((object)x) != null) { return x.Equals(y); } return ((object)y) == null; } public static bool operator !=(Transaction x, Transaction y) { if (((object)x) != null) { return !x.Equals(y); } return ((object)y) != null; } #endregion public TransactionInformation TransactionInformation { get { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.get_TransactionInformation"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } TransactionInformation txInfo = _internalTransaction._transactionInformation; if (txInfo == null) { // A race would only result in an extra allocation txInfo = new TransactionInformation(_internalTransaction); _internalTransaction._transactionInformation = txInfo; } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.get_TransactionInformation"); } return txInfo; } } // Return the Isolation Level for the given transaction // public IsolationLevel IsolationLevel { get { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.get_IsolationLevel"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.get_IsolationLevel"); } return _isoLevel; } } /// <summary> /// Gets the PromoterType value for the transaction. /// </summary> /// <value> /// If the transaction has not yet been promoted and does not yet have a promotable single phase enlistment, /// this property value will be Guid.Empty. /// /// If the transaction has been promoted or has a promotable single phase enlistment, this will return the /// promoter type specified by the transaction promoter. /// /// If the transaction is, or will be, promoted to MSDTC, the value will be TransactionInterop.PromoterTypeDtc. /// </value> public Guid PromoterType { get { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.get_PromoterType"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } lock (_internalTransaction) { return _internalTransaction._promoterType; } } } /// <summary> /// Gets the PromotedToken for the transaction. /// /// If the transaction has not already been promoted, retrieving this value will cause promotion. Before retrieving the /// PromotedToken, the Transaction.PromoterType value should be checked to see if it is a promoter type (Guid) that the /// caller understands. If the caller does not recognize the PromoterType value, retreiving the PromotedToken doesn't /// have much value because the caller doesn't know how to utilize it. But if the PromoterType is recognized, the /// caller should know how to utilize the PromotedToken to communicate with the promoting distributed transaction /// coordinator to enlist on the distributed transaction. /// /// If the value of a transaction's PromoterType is TransactionInterop.PromoterTypeDtc, then that transaction's /// PromotedToken will be an MSDTC-based TransmitterPropagationToken. /// </summary> /// <returns> /// The byte[] that can be used to enlist with the distributed transaction coordinator used to promote the transaction. /// The format of the byte[] depends upon the value of Transaction.PromoterType. /// </returns> public byte[] GetPromotedToken() { // We need to ask the current transaction state for the PromotedToken because depending on the state // we may need to induce a promotion. if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.GetPromotedToken"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } // We always make a copy of the promotedToken stored in the internal transaction. byte[] internalPromotedToken; lock (_internalTransaction) { internalPromotedToken = _internalTransaction.State.PromotedToken(_internalTransaction); } byte[] toReturn = new byte[internalPromotedToken.Length]; Array.Copy(internalPromotedToken, toReturn, toReturn.Length); return toReturn; } public Enlistment EnlistDurable( Guid resourceManagerIdentifier, IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistDurable( IEnlistmentNotification )"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (resourceManagerIdentifier == Guid.Empty) { throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } if (enlistmentNotification == null) { throw new ArgumentNullException(nameof(enlistmentNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction, resourceManagerIdentifier, enlistmentNotification, enlistmentOptions, this); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistDurable( IEnlistmentNotification )"); } return enlistment; } } // Forward request to the state machine to take the appropriate action. // public Enlistment EnlistDurable( Guid resourceManagerIdentifier, ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistDurable( ISinglePhaseNotification )"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (resourceManagerIdentifier == Guid.Empty) { throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } if (singlePhaseNotification == null) { throw new ArgumentNullException(nameof(singlePhaseNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction, resourceManagerIdentifier, singlePhaseNotification, enlistmentOptions, this); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistDurable( ISinglePhaseNotification )"); } return enlistment; } } public void Rollback() { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.Rollback"); } if (DiagnosticTrace.Warning) { TransactionRollbackCalledTraceRecord.Trace(SR.TraceSourceLtm, TransactionTraceId); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } lock (_internalTransaction) { Debug.Assert(_internalTransaction.State != null); _internalTransaction.State.Rollback(_internalTransaction, null); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.Rollback"); } } public void Rollback(Exception e) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.Rollback"); } if (DiagnosticTrace.Warning) { TransactionRollbackCalledTraceRecord.Trace(SR.TraceSourceLtm, TransactionTraceId); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } lock (_internalTransaction) { Debug.Assert(_internalTransaction.State != null); _internalTransaction.State.Rollback(_internalTransaction, e); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.Rollback"); } } // Forward request to the state machine to take the appropriate action. // public Enlistment EnlistVolatile(IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistVolatile( IEnlistmentNotification )"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (enlistmentNotification == null) { throw new ArgumentNullException(nameof(enlistmentNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction, enlistmentNotification, enlistmentOptions, this); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistVolatile( IEnlistmentNotification )" ); } return enlistment; } } // Forward request to the state machine to take the appropriate action. // public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistVolatile( ISinglePhaseNotification )"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (singlePhaseNotification == null) { throw new ArgumentNullException(nameof(singlePhaseNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction, singlePhaseNotification, enlistmentOptions, this); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistVolatile( ISinglePhaseNotification )" ); } return enlistment; } } // Create a clone of the transaction that forwards requests to this object. // public Transaction Clone() { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.Clone"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } Transaction clone = InternalClone(); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.Clone"); } return clone; } internal Transaction InternalClone() { Transaction clone = new Transaction(_isoLevel, _internalTransaction); if (DiagnosticTrace.Verbose) { CloneCreatedTraceRecord.Trace(SR.TraceSourceLtm, clone.TransactionTraceId); } return clone; } // Create a dependent clone of the transaction that forwards requests to this object. // public DependentTransaction DependentClone( DependentCloneOption cloneOption ) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.DependentClone"); } if (cloneOption != DependentCloneOption.BlockCommitUntilComplete && cloneOption != DependentCloneOption.RollbackIfNotComplete) { throw new ArgumentOutOfRangeException(nameof(cloneOption)); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } DependentTransaction clone = new DependentTransaction( _isoLevel, _internalTransaction, cloneOption == DependentCloneOption.BlockCommitUntilComplete); if (DiagnosticTrace.Information) { DependentCloneCreatedTraceRecord.Trace(SR.TraceSourceLtm, clone.TransactionTraceId, cloneOption); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.DependentClone"); } return clone; } internal TransactionTraceIdentifier TransactionTraceId { get { if (_traceIdentifier == TransactionTraceIdentifier.Empty) { lock (_internalTransaction) { if (_traceIdentifier == TransactionTraceIdentifier.Empty) { TransactionTraceIdentifier temp = new TransactionTraceIdentifier( _internalTransaction.TransactionTraceId.TransactionIdentifier, _cloneId); Interlocked.MemoryBarrier(); _traceIdentifier = temp; } } } return _traceIdentifier; } } // Forward request to the state machine to take the appropriate action. // public event TransactionCompletedEventHandler TransactionCompleted { add { if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } lock (_internalTransaction) { // Register for completion with the inner transaction _internalTransaction.State.AddOutcomeRegistrant(_internalTransaction, value); } } remove { lock (_internalTransaction) { _internalTransaction._transactionCompletedDelegate = (TransactionCompletedEventHandler) System.Delegate.Remove(_internalTransaction._transactionCompletedDelegate, value); } } } public void Dispose() { InternalDispose(); } // Handle Transaction Disposal. // internal virtual void InternalDispose() { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "IDisposable.Dispose"); } if (Interlocked.Exchange(ref _disposed, Transaction._disposedTrueValue) == Transaction._disposedTrueValue) { return; } // Attempt to clean up the internal transaction long remainingITx = Interlocked.Decrement(ref _internalTransaction._cloneCount); if (remainingITx == 0) { _internalTransaction.Dispose(); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "IDisposable.Dispose"); } } // Ask the state machine for serialization info. // void ISerializable.GetObjectData( SerializationInfo serializationInfo, StreamingContext context) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "ISerializable.GetObjectData"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (serializationInfo == null) { throw new ArgumentNullException(nameof(serializationInfo)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } lock (_internalTransaction) { _internalTransaction.State.GetObjectData(_internalTransaction, serializationInfo, context); } if (DiagnosticTrace.Information) { TransactionSerializedTraceRecord.Trace(SR.TraceSourceLtm, TransactionTraceId); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "ISerializable.GetObjectData"); } } /// <summary> /// Create a promotable single phase enlistment that promotes to MSDTC. /// </summary> /// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param> /// <returns> /// True if the enlistment is successful. /// /// False if the transaction already has a durable enlistment or promotable single phase enlistment or /// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other /// means, such as Transaction.EnlistDurable or retreive the MSDTC export cookie or propagation token to enlist with MSDTC. /// </returns> // We apparently didn't spell Promotable like FXCop thinks it should be spelled. public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification) { return EnlistPromotableSinglePhase(promotableSinglePhaseNotification, TransactionInterop.PromoterTypeDtc); } /// <summary> /// Create a promotable single phase enlistment that promotes to a distributed transaction manager other than MSDTC. /// </summary> /// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param> /// <param name="promoterType"> /// The promoter type Guid that identifies the format of the byte[] that is returned by the ITransactionPromoter.Promote /// call that is implemented by the IPromotableSinglePhaseNotificationObject, and thus the promoter of the transaction. /// </param> /// <returns> /// True if the enlistment is successful. /// /// False if the transaction already has a durable enlistment or promotable single phase enlistment or /// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other /// means. /// /// If the Transaction.PromoterType matches the promoter type supported by the caller, then the /// Transaction.PromotedToken can be retrieved and used to enlist directly with the identified distributed transaction manager. /// /// How the enlistment is created with the distributed transaction manager identified by the Transaction.PromoterType /// is defined by that distributed transaction manager. /// </returns> public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistPromotableSinglePhase"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (promotableSinglePhaseNotification == null) { throw new ArgumentNullException(nameof(promotableSinglePhaseNotification)); } if (promoterType == Guid.Empty) { throw new ArgumentException(SR.PromoterTypeInvalid, nameof(promoterType)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } bool succeeded = false; lock (_internalTransaction) { succeeded = _internalTransaction.State.EnlistPromotableSinglePhase(_internalTransaction, promotableSinglePhaseNotification, this, promoterType); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.EnlistPromotableSinglePhase"); } return succeeded; } public Enlistment PromoteAndEnlistDurable(Guid resourceManagerIdentifier, IPromotableSinglePhaseNotification promotableNotification, ISinglePhaseNotification enlistmentNotification, EnlistmentOptions enlistmentOptions) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceDistributed, "Transaction.PromoteAndEnlistDurable"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (resourceManagerIdentifier == Guid.Empty) { throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } if (promotableNotification == null) { throw new ArgumentNullException(nameof(promotableNotification)); } if (enlistmentNotification == null) { throw new ArgumentNullException(nameof(enlistmentNotification)); } if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { throw new ArgumentOutOfRangeException(nameof(enlistmentOptions)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } lock (_internalTransaction) { Enlistment enlistment = _internalTransaction.State.PromoteAndEnlistDurable(_internalTransaction, resourceManagerIdentifier, promotableNotification, enlistmentNotification, enlistmentOptions, this); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceDistributed, "Transaction.PromoteAndEnlistDurable"); } return enlistment; } } public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification promotableNotification, Guid distributedTransactionIdentifier) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.SetDistributedTransactionIdentifier"); } if (Disposed) { throw new ObjectDisposedException(nameof(Transaction)); } if (promotableNotification == null) { throw new ArgumentNullException(nameof(promotableNotification)); } if (distributedTransactionIdentifier == Guid.Empty) { throw new ArgumentException(null, nameof(distributedTransactionIdentifier)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(SR.TraceSourceLtm, DistributedTxId); } lock (_internalTransaction) { _internalTransaction.State.SetDistributedTransactionId(_internalTransaction, promotableNotification, distributedTransactionIdentifier); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceLtm, "Transaction.SetDistributedTransactionIdentifier" ); } return; } } internal DistributedTransaction Promote() { lock (_internalTransaction) { // This method is only called when we expect to be promoting to MSDTC. _internalTransaction.ThrowIfPromoterTypeIsNotMSDTC(); _internalTransaction.State.Promote(_internalTransaction); return _internalTransaction.PromotedTransaction; } } } // // The following code & data is related to management of Transaction.Current // internal enum DefaultComContextState { Unknown = 0, Unavailable = -1, Available = 1 } // // The TxLookup enum is used internally to detect where the ambient context needs to be stored or looked up. // Default - Used internally when looking up Transaction.Current. // DefaultCallContext - Used when TransactionScope with async flow option is enabled. Internally we will use CallContext to store the ambient transaction. // Default TLS - Used for legacy/syncronous TransactionScope. Internally we will use TLS to store the ambient transaction. // internal enum TxLookup { Default, DefaultCallContext, DefaultTLS, } // // CallContextCurrentData holds the ambient transaction and uses CallContext and ConditionalWeakTable to track the ambient transaction. // For async flow scenarios, we should not allow flowing of transaction across app domains. To prevent transaction from flowing across // AppDomain/Remoting boundaries, we are using ConditionalWeakTable to hold the actual ambient transaction and store only a object reference // in CallContext. When TransactionScope is used to invoke a call across AppDomain/Remoting boundaries, only the object reference will be sent // across and not the actaul ambient transaction which is stashed away in the ConditionalWeakTable. // internal static class CallContextCurrentData { private static AsyncLocal<ContextKey> s_currentTransaction = new AsyncLocal<ContextKey>(); // ConditionalWeakTable is used to automatically remove the entries that are no longer referenced. This will help prevent leaks in async nested TransactionScope // usage and when child nested scopes are not syncronized properly. private static readonly ConditionalWeakTable<ContextKey, ContextData> s_contextDataTable = new ConditionalWeakTable<ContextKey, ContextData>(); // // Set CallContext data with the given contextKey. // return the ContextData if already present in contextDataTable, otherwise return the default value. // public static ContextData CreateOrGetCurrentData(ContextKey contextKey) { s_currentTransaction.Value = contextKey; return s_contextDataTable.GetValue(contextKey, (env) => new ContextData(true)); } public static void ClearCurrentData(ContextKey contextKey, bool removeContextData) { // Get the current ambient CallContext. ContextKey key = s_currentTransaction.Value; if (contextKey != null || key != null) { // removeContextData flag is used for perf optimization to avoid removing from the table in certain nested TransactionScope usage. if (removeContextData) { // if context key is passed in remove that from the contextDataTable, otherwise remove the default context key. s_contextDataTable.Remove(contextKey ?? key); } if (key != null) { s_currentTransaction.Value = null; } } } public static bool TryGetCurrentData(out ContextData currentData) { currentData = null; ContextKey contextKey = s_currentTransaction.Value; if (contextKey == null) { return false; } else { return s_contextDataTable.TryGetValue(contextKey, out currentData); } } } // // MarshalByRefObject is needed for cross AppDomain scenarios where just using object will end up with a different reference when call is made across serialization boundary. // internal class ContextKey // : MarshalByRefObject { } internal class ContextData { internal TransactionScope CurrentScope; internal Transaction CurrentTransaction; internal DefaultComContextState DefaultComContextState; internal WeakReference WeakDefaultComContext; internal bool _asyncFlow; [ThreadStatic] private static ContextData s_staticData; internal ContextData(bool asyncFlow) { _asyncFlow = asyncFlow; } internal static ContextData TLSCurrentData { get { ContextData data = s_staticData; if (data == null) { data = new ContextData(false); s_staticData = data; } return data; } set { if (value == null && s_staticData != null) { // set each property to null to retain one TLS ContextData copy. s_staticData.CurrentScope = null; s_staticData.CurrentTransaction = null; s_staticData.DefaultComContextState = DefaultComContextState.Unknown; s_staticData.WeakDefaultComContext = null; } else { s_staticData = value; } } } internal static ContextData LookupContextData(TxLookup defaultLookup) { ContextData currentData = null; if (CallContextCurrentData.TryGetCurrentData(out currentData)) { if (currentData.CurrentScope == null && currentData.CurrentTransaction == null && defaultLookup != TxLookup.DefaultCallContext) { // Clear Call Context Data CallContextCurrentData.ClearCurrentData(null, true); return TLSCurrentData; } return currentData; } else { return TLSCurrentData; } } } }
/* * 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 java = biz.ritter.javapi; namespace biz.ritter.javapi.io { /** * A specialized {@link Reader} that reads characters from a {@code String} in * a sequential manner. * * @see StringWriter */ public class StringReader : Reader { private String str; private int markpos = -1; private int pos; private int count; /** * Construct a new {@code StringReader} with {@code str} as source. The size * of the reader is set to the {@code length()} of the string and the Object * to synchronize access through is set to {@code str}. * * @param str * the source string for this reader. */ public StringReader (String str) : base() { this.str = str; this.count = str.length (); } /** * Closes this reader. Once it is closed, read operations on this reader * will throw an {@code IOException}. Only the first invocation of this * method has any effect. */ public override void close () { str = null; } /** * Returns a boolean indicating whether this reader is closed. * * @return {@code true} if closed, otherwise {@code false}. */ private bool isClosed () { return str == null; } /** * Sets a mark position in this reader. The parameter {@code readLimit} is * ignored for this class. Calling {@code reset()} will reposition the * reader back to the marked position. * * @param readLimit * ignored for {@code StringReader} instances. * @throws IllegalArgumentException * if {@code readLimit < 0}. * @throws IOException * if this reader is closed. * @see #markSupported() * @see #reset() */ public override void mark (int readLimit) {//throws IOException { if (readLimit < 0) { throw new java.lang.IllegalArgumentException (); } lock (lockJ) { if (isClosed ()) { throw new IOException ("StringReader is closed."); //$NON-NLS-1$ } markpos = pos; } } /** * Indicates whether this reader supports the {@code mark()} and {@code * reset()} methods. This implementation returns {@code true}. * * @return always {@code true}. */ public override bool markSupported () { return true; } /** * Reads a single character from the source string and returns it as an * integer with the two higher-order bytes set to 0. Returns -1 if the end * of the source string has been reached. * * @return the character read or -1 if the end of the source string has been * reached. * @throws IOException * if this reader is closed. */ public override int read () {//throws IOException { lock (lockJ) { if (isClosed ()) { throw new IOException ("StringReader is closed."); //$NON-NLS-1$ } if (pos != count) { return str.charAt (pos++); } return -1; } } /** * Reads at most {@code len} characters from the source string and stores * them at {@code offset} in the character array {@code buf}. Returns the * number of characters actually read or -1 if the end of the source string * has been reached. * * @param buf * the character array to store the characters read. * @param offset * the initial position in {@code buffer} to store the characters * read from this reader. * @param len * the maximum number of characters to read. * @return the number of characters read or -1 if the end of the reader has * been reached. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code len < 0}, or if * {@code offset + len} is greater than the size of {@code buf}. * @throws IOException * if this reader is closed. */ public override int read (char[] buf, int offset, int len) {//throws IOException { lock (lockJ) { if (isClosed ()) { // luni.D6=StringReader is closed. throw new IOException ("StringReader is closed."); //$NON-NLS-1$ } if (offset < 0 || offset > buf.Length) { // luni.12=Offset out of bounds \: {0} throw new java.lang.ArrayIndexOutOfBoundsException ("Offset out of bounds : {"+offset); //$NON-NLS-1$ } if (len < 0 || len > buf.Length - offset) { // luni.18=Length out of bounds \: {0} throw new java.lang.ArrayIndexOutOfBoundsException ("Length out of bounds : "+ len); //$NON-NLS-1$ } if (len == 0) { return 0; } if (pos == this.count) { return -1; } int end = pos + len > this.count ? this.count : pos + len; str.getChars (pos, end, buf, offset); int read = end - pos; pos = end; return read; } } /** * Indicates whether this reader is ready to be read without blocking. This * implementation always returns {@code true}. * * @return always {@code true}. * @throws IOException * if this reader is closed. * @see #read() * @see #read(char[], int, int) */ public override bool ready () {//throws IOException { lock (lockJ) { if (isClosed ()) { throw new IOException ("StringReader is closed."); //$NON-NLS-1$ } return true; } } /** * Resets this reader's position to the last {@code mark()} location. * Invocations of {@code read()} and {@code skip()} will occur from this new * location. If this reader has not been marked, it is reset to the * beginning of the source string. * * @throws IOException * if this reader is closed. * @see #mark(int) * @see #markSupported() */ public override void reset () {//throws IOException { lock (lockJ) { if (isClosed ()) { throw new IOException ("StringReader is closed."); //$NON-NLS-1$ } pos = markpos != -1 ? markpos : 0; } } /** * Moves {@code ns} characters in the source string. Unlike the {@link * Reader#skip(long) overridden method}, this method may skip negative skip * distances: this rewinds the input so that characters may be read again. * When the end of the source string has been reached, the input cannot be * rewound. * * @param ns * the maximum number of characters to skip. Positive values skip * forward; negative values skip backward. * @return the number of characters actually skipped. This is bounded below * by the number of characters already read and above by the * number of characters remaining:<br> {@code -(num chars already * read) <= distance skipped <= num chars remaining}. * @throws IOException * if this reader is closed. * @see #mark(int) * @see #markSupported() * @see #reset() */ public override long skip (long ns) {//throws IOException { lock (lockJ) { if (isClosed ()) { throw new IOException ("StringReader is closed."); //$NON-NLS-1$ } int minSkip = -pos; int maxSkip = count - pos; if (maxSkip == 0 || ns > maxSkip) { ns = maxSkip; // no rewinding if we're at the end } else if (ns < minSkip) { ns = minSkip; } pos += (int)ns; return ns; } } } }
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 StudentSystem.Services.Areas.HelpPage.ModelDescriptions; using StudentSystem.Services.Areas.HelpPage.Models; namespace StudentSystem.Services.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace eBayAPI.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 UnityEngine; // Debug.Log, Mathf using System; // String, StringSplitOptions using System.Collections.Generic; // Dictionary, List public class Model { public ViewModel view = new ViewModel(); public int columnCountMax = 3; public int columnCount = -1; public string invisible = "."; public bool isSelecting; public bool isSwapLettersMode = false; public string message; public int rowCountMax = 5; public int rowCount = -1; public int levelCountMax = 21; public int levelCount; public int tileCountMax = 15; public string[] tileLetters; public bool[] tileSelecteds; public string submission; public string[] levelButtonNames; public string[] levelButtonTexts; public string[] wishButtonNames; public string[] wishButtonTexts; public int gridsComplete; public int gridsTotal; public string gridsCompleteText; public string stateChange = null; private string stateNext = null; private string gridDelimiter = "\n\n"; private Dictionary <string, string[][]> wishGrids; private Dictionary <string, string[]> wishMessages; public Dictionary <string, bool[]> wishIsCompletes; public bool[] wishesIsCompletes; public string namesText; public string creditsText; public string wordsText; public string messagesText; public string[] gridTexts; public string[] gridNames; private string[] messages; private Dictionary<string, bool> credits; private Dictionary<string, bool> words; private WordGrid wordGrid; /** * grid: * line */ private string[][] grids; public string[] grid; public int gridIndex = -1; public string levelText; public string wishName; public int wishIndex; public void ReadTexts() { string directory = isSwapLettersMode ? "swap" : "spell"; creditsText = Toolkit.Read(directory + "/word_credits.txt"); wordsText = Toolkit.Read(directory + "/word_list_moby_crossword.flat.txt"); if (isSwapLettersMode) { wordGrid = new WordGrid(); wordGrid.SetDictionary(wordsText + "\n" + creditsText); } messagesText = Toolkit.Read(directory + "/tutorial_messages.txt"); gridNames = new string[]{ "tutorial_grids.txt", "love_grids.txt", "health_grids.txt", "money_grids.txt", "charm_grids.txt", "success_grids.txt", "skill_grids.txt", "healing_grids.txt", "relaxation_grids.txt", "grief_grids.txt", "banishing_grids.txt", "credits_grids.txt" }; gridTexts = new string[gridNames.Length]; for (int index = 0; index < gridNames.Length; index++) { gridTexts[index] = Toolkit.Read(directory + "/" + gridNames[index]); } } /** * Each line is a string, which may be accessed by index. * Allows jagged arrays. */ public string[][] ParseGrids(string gridsText) { string[] gridStrings = Toolkit.Split(gridsText, gridDelimiter); string[][] grids = new string[gridStrings.Length][]; for (int i = 0; i < gridStrings.Length; i++) { string text = gridStrings[i]; string[] lines = Toolkit.Split(text, Toolkit.lineDelimiter); grids[i] = lines; // Debug.Log("Model.ParseGrids: " + i + ": " + Join(grids[i])); } return grids; } public string Join(string[] grid) { return String.Join(Toolkit.lineDelimiter, grid); } public Dictionary<string, bool> ParseWords(string wordsText) { Dictionary<string, bool> words = new Dictionary<string, bool>(); string[] wordList = Toolkit.Split(wordsText, Toolkit.lineDelimiter); for (int wordIndex = 0; wordIndex < wordList.Length; wordIndex++) { string word = wordList[wordIndex]; words[word] = true; } return words; } private void SetupLevelButtons(int levelCountMax) { levelButtonNames = new string[levelCountMax]; levelButtonTexts = new string[levelCountMax]; for (int tileIndex = 0; tileIndex < levelCountMax; tileIndex++) { levelButtonNames[tileIndex] = "level_" + tileIndex; levelButtonTexts[tileIndex] = (tileIndex + 1).ToString(); } } private void SetupWishButtons(string[] wishButtonTexts) { wishButtonNames = new string[wishButtonTexts.Length]; for (int tileIndex = 0; tileIndex < wishButtonTexts.Length; tileIndex++) { wishButtonNames[tileIndex] = "wish_" + tileIndex; } } public string[] LoadAllWishes() { gridsTotal = 0; wishGrids = new Dictionary<string, string[][]>(); wishMessages = new Dictionary<string, string[]>(); wishIsCompletes = new Dictionary<string, bool[]>(); string[] wishNames = new string[gridTexts.Length]; wishesIsCompletes = new bool[wishNames.Length]; for (int wishIndex = 0; wishIndex < wishNames.Length; wishIndex++) { string gridsFileName = gridNames[wishIndex]; string name = Toolkit.Split(gridsFileName, "_grids")[0]; name = name.ToUpper()[0] + name.Substring(1); wishNames[wishIndex] = name; // Debug.Log("Model.LoadAllWishes: <" + name + ">"); string gridsText = gridTexts[wishIndex]; string[][] grids = ParseGrids(gridsText); wishGrids[name] = grids; wishIsCompletes[name] = new bool[grids.Length]; gridsTotal += grids.Length; for (int gridIndex = 0; gridIndex < grids.Length; gridIndex++) { wishIsCompletes[name][gridIndex] = false; } wishesIsCompletes[wishIndex] = false; string[] messages; if (0 == wishIndex) { messages = Toolkit.Split(messagesText, Toolkit.lineDelimiter); } else { messages = new string[0]; } wishMessages[name] = messages; } // Debug.Log("Model.LoadAllWishes: " + gridsTotal + " grids"); gridsComplete = 0; formatGridsComplete(); return wishNames; } private void formatGridsComplete() { gridsCompleteText = "Spells cast: " + gridsComplete + " of " + gridsTotal; } public void SetupWish(int index) { wishIndex = index; wishName = wishButtonTexts[index]; grids = wishGrids[wishName]; messages = wishMessages[wishName]; PopulateGrid(0); levelCount = grids.Length; } public void Start() { ReadTexts(); words = ParseWords(wordsText); credits = ParseWords(creditsText); wishButtonTexts = LoadAllWishes(); SetupWishButtons(wishButtonTexts); SetupLevelButtons(levelCountMax); SetupWish(0); } public void PopulateGrid(int newGridIndex) { gridIndex = newGridIndex % grids.Length; grid = grids[gridIndex]; columnCount = columnCountMax; rowCount = grid.Length; // Debug.Log("Model.PopulateGrid: index " + gridIndex + ": " + Join(grid)); tileLetters = GetTileLetters(grid); tileSelecteds = new bool[tileCountMax]; isSelecting = false; submission = ""; if (gridIndex < messages.Length) { message = messages[gridIndex]; } else { message = ""; } levelText = wishName + " " + (gridIndex + 1).ToString() + " of " + grids.Length.ToString(); } /** * A period denotes an invisible tile. */ public string[] GetTileLetters(string[] grid) { string[] letters = new string[tileCountMax]; for (int tileIndex = 0; tileIndex < tileCountMax; tileIndex++) { string character = null; int lineIndex = tileIndex / columnCountMax; bool isVisible = lineIndex < grid.Length; if (isVisible) { string line = grid[lineIndex]; int stringIndex = tileIndex % columnCountMax; isVisible = stringIndex < line.Length; if (isVisible) { character = line[stringIndex].ToString(); } } letters[tileIndex] = character; } return letters; } private int[] swapIndexes = new int[2]{-1, -1}; public void Select(string tileName) { int tileIndex = Toolkit.ParseIndex(tileName); bool wasSelected = tileSelecteds[tileIndex]; if (wasSelected) { submission = submission.Substring(0, submission.Length - 1); } else { if (isSwapLettersMode) { if (2 <= submission.Length) { return; } swapIndexes[submission.Length] = tileIndex; } submission += tileLetters[tileIndex]; } tileSelecteds[tileIndex] = !wasSelected; } public void SelectAll(bool isSelected) { for (int tileIndex = 0; tileIndex < tileSelecteds.Length; tileIndex++) { tileSelecteds[tileIndex] = isSelected; } } public void RemoveSelected() { for (int tileIndex = 0; tileIndex < tileSelecteds.Length; tileIndex++) { bool isSelected = tileSelecteds[tileIndex]; if (isSelected) { tileSelecteds[tileIndex] = false; tileLetters[tileIndex] = invisible; } } } public void RemovePath(List<int> path) { for (int step = 0; step < path.Count; step++) { int tileIndex = path[step]; bool isSelected = tileSelecteds[tileIndex]; if (isSelected) { tileSelecteds[tileIndex] = false; } tileLetters[tileIndex] = invisible; } } public string OnMouseDown(string tileName) { stateNext = null; if (0 == tileName.IndexOf("level_")) { stateNext = "levelEnter"; gridIndex = Toolkit.ParseIndex(tileName); PopulateGrid(gridIndex); } else if ("LevelExit" == tileName) { stateNext = "levelExit"; } else if ("Wishes" == tileName) { stateNext = "wishes"; } else if ("Restart" == tileName) { PopulateGrid(gridIndex); } else if (0 == tileName.IndexOf("wish_")) { stateNext = "levelExit"; int wishIndex = Toolkit.ParseIndex(tileName); SetupWish(wishIndex); } else { if (!isSelecting) { isSelecting = true; } Select(tileName); } return stateNext; } public void OnMouseEnter(string tileName) { if (isSelecting) { Select(tileName); } } public void OnMouseUp() { if (isSelecting) { isSelecting = false; Submit(); } } private bool IsEmpty() { int count = 0; for (int tileIndex = 0; tileIndex < tileCountMax; tileIndex++) { string letter = tileLetters[tileIndex]; if (null != letter && invisible != letter) { count++; } } return 0 == count; } private bool IsWord(string submission) { return words.ContainsKey(submission) || credits.ContainsKey(submission); } public bool SetComplete(int gridIndex) { bool[] isCompletes = wishIsCompletes[wishName]; if (!isCompletes[gridIndex]) { gridsComplete++; formatGridsComplete(); isCompletes[gridIndex] = true; } bool isAllComplete = true; for (int tileIndex = 0; tileIndex < isCompletes.Length; tileIndex++) { isAllComplete = isAllComplete && isCompletes[tileIndex]; } wishesIsCompletes[wishIndex] = isAllComplete; return isAllComplete; } private void SubmitWord() { if (IsWord(submission)) { RemoveSelected(); } else { SelectAll(false); } // Debug.Log("Model.SubmitWord: " + submission); } private void SwapLettersSelecteds() { int previous = -1; string letter = invisible; for (int tileIndex = 0; tileIndex < tileSelecteds.Length; tileIndex++) { bool isSelected = tileSelecteds[tileIndex]; if (isSelected) { if (invisible == letter) { letter = tileLetters[tileIndex]; previous = tileIndex; } else { tileLetters[previous] = tileLetters[tileIndex]; tileLetters[tileIndex] = letter; break; } } } } /** * Example @see TestModel */ public bool SwapLetters(int[] swapIndexes) { int a = swapIndexes[0]; int b = swapIndexes[1]; bool isSwap = 0 <= a && 0 <= b && tileSelecteds[a] && tileSelecteds[b]; if (isSwap) { string letter = tileLetters[a]; tileLetters[a] = tileLetters[b]; tileLetters[b] = letter; } return isSwap; } private void Submit() { if (isSwapLettersMode) { if (SwapLetters(swapIndexes)) { wordGrid.cellLetters = tileLetters; wordGrid.SetSize(columnCount, rowCount); string word = wordGrid.FindLongestWord(swapIndexes); if ("" != word) { message = word; RemovePath(wordGrid.wordPaths[word]); } } SelectAll(false); } else { SubmitWord(); } if (IsEmpty()) { SetComplete(gridIndex); ++gridIndex; if (gridIndex < levelCount) { PopulateGrid(gridIndex); } else { stateNext = "wishes"; } } submission = ""; } public string Update() { stateChange = stateNext; stateNext = null; return stateChange; } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT #define DEBUG namespace NLog.UnitTests { using System; using System.Globalization; using System.Threading; using System.Diagnostics; using Xunit; public class NLogTraceListenerTests : NLogTestBase, IDisposable { private readonly CultureInfo previousCultureInfo; public NLogTraceListenerTests() { this.previousCultureInfo = Thread.CurrentThread.CurrentCulture; // set the culture info with the decimal separator (comma) different from InvariantCulture separator (point) Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); } public void Dispose() { // restore previous culture info Thread.CurrentThread.CurrentCulture = this.previousCultureInfo; } [Fact] public void TraceWriteTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.Write("Hello"); AssertDebugLastMessage("debug", "Logger1 Debug Hello"); Debug.Write("Hello", "Cat1"); AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello"); Debug.Write(3.1415); AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415)); Debug.Write(3.1415, "Cat2"); AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415)); } [Fact] public void TraceWriteLineTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.WriteLine("Hello"); AssertDebugLastMessage("debug", "Logger1 Debug Hello"); Debug.WriteLine("Hello", "Cat1"); AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello"); Debug.WriteLine(3.1415); AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415)); Debug.WriteLine(3.1415, "Cat2"); AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415)); } [Fact] public void TraceWriteNonDefaultLevelTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); Debug.Write("Hello"); AssertDebugLastMessage("debug", "Logger1 Trace Hello"); } [Fact] public void TraceConfiguration() { var listener = new NLogTraceListener(); listener.Attributes.Add("defaultLogLevel", "Warn"); listener.Attributes.Add("forceLogLevel", "Error"); listener.Attributes.Add("autoLoggerName", "1"); Assert.Equal(LogLevel.Warn, listener.DefaultLogLevel); Assert.Equal(LogLevel.Error, listener.ForceLogLevel); Assert.True(listener.AutoLoggerName); } [Fact] public void TraceFailTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.Fail("Message"); AssertDebugLastMessage("debug", "Logger1 Error Message"); Debug.Fail("Message", "Detailed Message"); AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message"); } [Fact] public void AutoLoggerNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true }); Debug.Write("Hello"); AssertDebugLastMessage("debug", this.GetType().FullName + " Debug Hello"); } [Fact] public void TraceDataTests() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceData(TraceEventType.Critical, 123, 42); AssertDebugLastMessage("debug", "MySource1 Fatal 42 123"); ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo"); AssertDebugLastMessage("debug", string.Format("MySource1 Fatal 42, {0}, foo 145", 3.14.ToString(System.Globalization.CultureInfo.CurrentCulture))); } [Fact] public void LogInformationTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceInformation("Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0"); } [Fact] public void TraceEventTests() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog"); AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123"); ts.TraceEvent(TraceEventType.Information, 123); AssertDebugLastMessage("debug", "MySource1 Info 123"); ts.TraceEvent(TraceEventType.Verbose, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Trace Bar 145"); ts.TraceEvent(TraceEventType.Error, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Error Foo 145"); ts.TraceEvent(TraceEventType.Suspend, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Debug Bar 145"); ts.TraceEvent(TraceEventType.Resume, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Debug Foo 145"); ts.TraceEvent(TraceEventType.Warning, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Warn Bar 145"); ts.TraceEvent(TraceEventType.Critical, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145"); } [Fact] public void ForceLogLevelTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn }); // force all logs to be Warn, DefaultLogLevel has no effect on TraceSource ts.TraceInformation("Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0"); } private static TraceSource CreateTraceSource() { var ts = new TraceSource("MySource1", SourceLevels.All); #if MONO // for some reason needed on Mono ts.Switch = new SourceSwitch("MySource1", "Verbose"); ts.Switch.Level = SourceLevels.All; #endif return ts; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.Security.Cryptography { public class CryptoConfig { private const string AssemblyName_Cng = "System.Security.Cryptography.Cng"; private const string AssemblyName_Csp = "System.Security.Cryptography.Csp"; private const string AssemblyName_Pkcs = "System.Security.Cryptography.Pkcs"; private const string AssemblyName_X509Certificates = "System.Security.Cryptography.X509Certificates"; private const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; private const string OID_RSA_SMIMEalgCMS3DESwrap = "1.2.840.113549.1.9.16.3.6"; private const string OID_RSA_MD5 = "1.2.840.113549.2.5"; private const string OID_RSA_RC2CBC = "1.2.840.113549.3.2"; private const string OID_RSA_DES_EDE3_CBC = "1.2.840.113549.3.7"; private const string OID_OIWSEC_desCBC = "1.3.14.3.2.7"; private const string OID_OIWSEC_SHA1 = "1.3.14.3.2.26"; private const string OID_OIWSEC_SHA256 = "2.16.840.1.101.3.4.2.1"; private const string OID_OIWSEC_SHA384 = "2.16.840.1.101.3.4.2.2"; private const string OID_OIWSEC_SHA512 = "2.16.840.1.101.3.4.2.3"; private const string OID_OIWSEC_RIPEMD160 = "1.3.36.3.2.1"; private static volatile Dictionary<string, string> s_defaultOidHT = null; private static volatile Dictionary<string, object> s_defaultNameHT = null; private static volatile Dictionary<string, Type> appNameHT = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); private static volatile Dictionary<string, string> appOidHT = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private static readonly char[] SepArray = { '.' }; // valid ASN.1 separators // CoreFx does not support AllowOnlyFipsAlgorithms public static bool AllowOnlyFipsAlgorithms => false; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject = new Object(); private static Dictionary<string, string> DefaultOidHT { get { if (s_defaultOidHT != null) { return s_defaultOidHT; } Dictionary<string, string> ht = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); ht.Add("SHA", OID_OIWSEC_SHA1); ht.Add("SHA1", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1CryptoServiceProvider", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1Cng", OID_OIWSEC_SHA1); ht.Add("System.Security.Cryptography.SHA1Managed", OID_OIWSEC_SHA1); ht.Add("SHA256", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256CryptoServiceProvider", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256Cng", OID_OIWSEC_SHA256); ht.Add("System.Security.Cryptography.SHA256Managed", OID_OIWSEC_SHA256); ht.Add("SHA384", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384CryptoServiceProvider", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384Cng", OID_OIWSEC_SHA384); ht.Add("System.Security.Cryptography.SHA384Managed", OID_OIWSEC_SHA384); ht.Add("SHA512", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512CryptoServiceProvider", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512Cng", OID_OIWSEC_SHA512); ht.Add("System.Security.Cryptography.SHA512Managed", OID_OIWSEC_SHA512); ht.Add("RIPEMD160", OID_OIWSEC_RIPEMD160); ht.Add("System.Security.Cryptography.RIPEMD160", OID_OIWSEC_RIPEMD160); ht.Add("System.Security.Cryptography.RIPEMD160Managed", OID_OIWSEC_RIPEMD160); ht.Add("MD5", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5CryptoServiceProvider", OID_RSA_MD5); ht.Add("System.Security.Cryptography.MD5Managed", OID_RSA_MD5); ht.Add("TripleDESKeyWrap", OID_RSA_SMIMEalgCMS3DESwrap); ht.Add("RC2", OID_RSA_RC2CBC); ht.Add("System.Security.Cryptography.RC2CryptoServiceProvider", OID_RSA_RC2CBC); ht.Add("DES", OID_OIWSEC_desCBC); ht.Add("System.Security.Cryptography.DESCryptoServiceProvider", OID_OIWSEC_desCBC); ht.Add("TripleDES", OID_RSA_DES_EDE3_CBC); ht.Add("System.Security.Cryptography.TripleDESCryptoServiceProvider", OID_RSA_DES_EDE3_CBC); s_defaultOidHT = ht; return s_defaultOidHT; } } private static Dictionary<string, object> DefaultNameHT { get { if (s_defaultNameHT != null) { return s_defaultNameHT; } Dictionary<string, object> ht = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); Type HMACMD5Type = typeof(System.Security.Cryptography.HMACMD5); Type HMACSHA1Type = typeof(System.Security.Cryptography.HMACSHA1); Type HMACSHA256Type = typeof(System.Security.Cryptography.HMACSHA256); Type HMACSHA384Type = typeof(System.Security.Cryptography.HMACSHA384); Type HMACSHA512Type = typeof(System.Security.Cryptography.HMACSHA512); Type RijndaelManagedType = typeof(System.Security.Cryptography.RijndaelManaged); Type AesManagedType = typeof(System.Security.Cryptography.AesManaged); Type SHA256DefaultType = typeof(System.Security.Cryptography.SHA256Managed); Type SHA384DefaultType = typeof(System.Security.Cryptography.SHA384Managed); Type SHA512DefaultType = typeof(System.Security.Cryptography.SHA512Managed); string SHA1CryptoServiceProviderType = "System.Security.Cryptography.SHA1CryptoServiceProvider, " + AssemblyName_Csp; string MD5CryptoServiceProviderType = "System.Security.Cryptography.MD5CryptoServiceProvider," + AssemblyName_Csp; string RSACryptoServiceProviderType = "System.Security.Cryptography.RSACryptoServiceProvider, " + AssemblyName_Csp; string DSACryptoServiceProviderType = "System.Security.Cryptography.DSACryptoServiceProvider, " + AssemblyName_Csp; string DESCryptoServiceProviderType = "System.Security.Cryptography.DESCryptoServiceProvider, " + AssemblyName_Csp; string TripleDESCryptoServiceProviderType = "System.Security.Cryptography.TripleDESCryptoServiceProvider, " + AssemblyName_Csp; string RC2CryptoServiceProviderType = "System.Security.Cryptography.RC2CryptoServiceProvider, " + AssemblyName_Csp; string RNGCryptoServiceProviderType = "System.Security.Cryptography.RNGCryptoServiceProvider, " + AssemblyName_Csp; string AesCryptoServiceProviderType = "System.Security.Cryptography.AesCryptoServiceProvider, " + AssemblyName_Csp; string ECDsaCngType = "System.Security.Cryptography.ECDsaCng, " + AssemblyName_Cng; // Random number generator ht.Add("RandomNumberGenerator", RNGCryptoServiceProviderType); ht.Add("System.Security.Cryptography.RandomNumberGenerator", RNGCryptoServiceProviderType); // Hash functions ht.Add("SHA", SHA1CryptoServiceProviderType); ht.Add("SHA1", SHA1CryptoServiceProviderType); ht.Add("System.Security.Cryptography.SHA1", SHA1CryptoServiceProviderType); ht.Add("System.Security.Cryptography.HashAlgorithm", SHA1CryptoServiceProviderType); ht.Add("MD5", MD5CryptoServiceProviderType); ht.Add("System.Security.Cryptography.MD5", MD5CryptoServiceProviderType); ht.Add("SHA256", SHA256DefaultType); ht.Add("SHA-256", SHA256DefaultType); ht.Add("System.Security.Cryptography.SHA256", SHA256DefaultType); ht.Add("SHA384", SHA384DefaultType); ht.Add("SHA-384", SHA384DefaultType); ht.Add("System.Security.Cryptography.SHA384", SHA384DefaultType); ht.Add("SHA512", SHA512DefaultType); ht.Add("SHA-512", SHA512DefaultType); ht.Add("System.Security.Cryptography.SHA512", SHA512DefaultType); // Keyed Hash Algorithms ht.Add("System.Security.Cryptography.HMAC", HMACSHA1Type); ht.Add("System.Security.Cryptography.KeyedHashAlgorithm", HMACSHA1Type); ht.Add("HMACMD5", HMACMD5Type); ht.Add("System.Security.Cryptography.HMACMD5", HMACMD5Type); ht.Add("HMACSHA1", HMACSHA1Type); ht.Add("System.Security.Cryptography.HMACSHA1", HMACSHA1Type); ht.Add("HMACSHA256", HMACSHA256Type); ht.Add("System.Security.Cryptography.HMACSHA256", HMACSHA256Type); ht.Add("HMACSHA384", HMACSHA384Type); ht.Add("System.Security.Cryptography.HMACSHA384", HMACSHA384Type); ht.Add("HMACSHA512", HMACSHA512Type); ht.Add("System.Security.Cryptography.HMACSHA512", HMACSHA512Type); // Asymmetric algorithms ht.Add("RSA", RSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.RSA", RSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.AsymmetricAlgorithm", RSACryptoServiceProviderType); ht.Add("DSA", DSACryptoServiceProviderType); ht.Add("System.Security.Cryptography.DSA", DSACryptoServiceProviderType); ht.Add("ECDsa", ECDsaCngType); ht.Add("ECDsaCng", ECDsaCngType); ht.Add("System.Security.Cryptography.ECDsaCng", ECDsaCngType); // Symmetric algorithms ht.Add("DES", DESCryptoServiceProviderType); ht.Add("System.Security.Cryptography.DES", DESCryptoServiceProviderType); ht.Add("3DES", TripleDESCryptoServiceProviderType); ht.Add("TripleDES", TripleDESCryptoServiceProviderType); ht.Add("Triple DES", TripleDESCryptoServiceProviderType); ht.Add("System.Security.Cryptography.TripleDES", TripleDESCryptoServiceProviderType); ht.Add("RC2", RC2CryptoServiceProviderType); ht.Add("System.Security.Cryptography.RC2", RC2CryptoServiceProviderType); ht.Add("Rijndael", RijndaelManagedType); ht.Add("System.Security.Cryptography.Rijndael", RijndaelManagedType); // Rijndael is the default symmetric cipher because (a) it's the strongest and (b) we know we have an implementation everywhere ht.Add("System.Security.Cryptography.SymmetricAlgorithm", RijndaelManagedType); ht.Add("AES", AesCryptoServiceProviderType); ht.Add("AesCryptoServiceProvider", AesCryptoServiceProviderType); ht.Add("System.Security.Cryptography.AesCryptoServiceProvider", AesCryptoServiceProviderType); ht.Add("AesManaged", AesManagedType); ht.Add("System.Security.Cryptography.AesManaged", AesManagedType); // Xml Dsig/ Enc Hash algorithms ht.Add("http://www.w3.org/2000/09/xmldsig#sha1", SHA1CryptoServiceProviderType); // Add the other hash algorithms introduced with XML Encryption ht.Add("http://www.w3.org/2001/04/xmlenc#sha256", SHA256DefaultType); ht.Add("http://www.w3.org/2001/04/xmlenc#sha512", SHA512DefaultType); // Xml Encryption symmetric keys ht.Add("http://www.w3.org/2001/04/xmlenc#des-cbc", DESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", TripleDESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-tripledes", TripleDESCryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes128-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes128", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes192-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes192", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#aes256-cbc", RijndaelManagedType); ht.Add("http://www.w3.org/2001/04/xmlenc#kw-aes256", RijndaelManagedType); // Xml Dsig HMAC URIs from http://www.w3.org/TR/xmldsig-core/ ht.Add("http://www.w3.org/2000/09/xmldsig#hmac-sha1", HMACSHA1Type); // Xml Dsig-more Uri's as defined in http://www.ietf.org/rfc/rfc4051.txt ht.Add("http://www.w3.org/2001/04/xmldsig-more#md5", MD5CryptoServiceProviderType); ht.Add("http://www.w3.org/2001/04/xmldsig-more#sha384", SHA384DefaultType); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-md5", HMACMD5Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", HMACSHA256Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", HMACSHA384Type); ht.Add("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", HMACSHA512Type); // X509 Extensions (custom decoders) // Basic Constraints OID value ht.Add("2.5.29.10", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates); ht.Add("2.5.29.19", "System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension, " + AssemblyName_X509Certificates); // Subject Key Identifier OID value ht.Add("2.5.29.14", "System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension, " + AssemblyName_X509Certificates); // Key Usage OID value ht.Add("2.5.29.15", "System.Security.Cryptography.X509Certificates.X509KeyUsageExtension, " + AssemblyName_X509Certificates); // Enhanced Key Usage OID value ht.Add("2.5.29.37", "System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension, " + AssemblyName_X509Certificates); // X509Chain class can be overridden to use a different chain engine. ht.Add("X509Chain", "System.Security.Cryptography.X509Certificates.X509Chain, " + AssemblyName_X509Certificates); // PKCS9 attributes ht.Add("1.2.840.113549.1.9.3", "System.Security.Cryptography.Pkcs.Pkcs9ContentType, " + AssemblyName_Pkcs); ht.Add("1.2.840.113549.1.9.4", "System.Security.Cryptography.Pkcs.Pkcs9MessageDigest, " + AssemblyName_Pkcs); ht.Add("1.2.840.113549.1.9.5", "System.Security.Cryptography.Pkcs.Pkcs9SigningTime, " + AssemblyName_Pkcs); ht.Add("1.3.6.1.4.1.311.88.2.1", "System.Security.Cryptography.Pkcs.Pkcs9DocumentName, " + AssemblyName_Pkcs); ht.Add("1.3.6.1.4.1.311.88.2.2", "System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription, " + AssemblyName_Pkcs); s_defaultNameHT = ht; return s_defaultNameHT; // Types in Desktop but currently unsupported in CoreFx: // Type HMACRIPEMD160Type = typeof(System.Security.Cryptography.HMACRIPEMD160); // Type MAC3DESType = typeof(System.Security.Cryptography.MACTripleDES); // Type DSASignatureDescriptionType = typeof(System.Security.Cryptography.DSASignatureDescription); // Type RSAPKCS1SHA1SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription); // Type RSAPKCS1SHA256SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA256SignatureDescription); // Type RSAPKCS1SHA384SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA384SignatureDescription); // Type RSAPKCS1SHA512SignatureDescriptionType = typeof(System.Security.Cryptography.RSAPKCS1SHA512SignatureDescription); // string RIPEMD160ManagedType = "System.Security.Cryptography.RIPEMD160Managed" + AssemblyName_Encoding; // string ECDiffieHellmanCngType = "System.Security.Cryptography.ECDiffieHellmanCng, " + AssemblyName_Cng; // string MD5CngType = "System.Security.Cryptography.MD5Cng, " + AssemblyName_Cng; // string SHA1CngType = "System.Security.Cryptography.SHA1Cng, " + AssemblyName_Cng; // string SHA256CngType = "System.Security.Cryptography.SHA256Cng, " + AssemblyName_Cng; // string SHA384CngType = "System.Security.Cryptography.SHA384Cng, " + AssemblyName_Cng; // string SHA512CngType = "System.Security.Cryptography.SHA512Cng, " + AssemblyName_Cng; // string SHA256CryptoServiceProviderType = "System.Security.Cryptography.SHA256CryptoServiceProvider, " + AssemblyName_Csp; // string SHA384CryptoSerivceProviderType = "System.Security.Cryptography.SHA384CryptoServiceProvider, " + AssemblyName_Csp; // string SHA512CryptoServiceProviderType = "System.Security.Cryptography.SHA512CryptoServiceProvider, " + AssemblyName_Csp; // string DpapiDataProtectorType = "System.Security.Cryptography.DpapiDataProtector, " + AssemblyRef.SystemSecurity; } } public static void AddAlgorithm(Type algorithm, params string[] names) { if (algorithm == null) throw new ArgumentNullException(nameof(algorithm)); if (!algorithm.IsVisible) throw new ArgumentException(SR.Cryptography_AlgorithmTypesMustBeVisible, nameof(algorithm)); if (names == null) throw new ArgumentNullException(nameof(names)); string[] algorithmNames = new string[names.Length]; Array.Copy(names, algorithmNames, algorithmNames.Length); // Pre-check the algorithm names for validity so that we don't add a few of the names and then // throw an exception if we find an invalid name partway through the list. foreach (string name in algorithmNames) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException(SR.Cryptography_AddNullOrEmptyName); } } // Everything looks valid, so we're safe to take the table lock and add the name mappings. lock (s_InternalSyncObject) { foreach (string name in algorithmNames) { appNameHT[name] = algorithm; } } } public static object CreateFromName(string name, params object[] args) { if (name == null) throw new ArgumentNullException(nameof(name)); Type retvalType = null; // Check to see if we have an application defined mapping lock (s_InternalSyncObject) { if (!appNameHT.TryGetValue(name, out retvalType)) { retvalType = null; } } // We allow the default table to Types and Strings // Types get used for types in .Algorithms assembly. // strings get used for delay-loaded stuff in other assemblies such as .Csp. object retvalObj; if (retvalType == null && DefaultNameHT.TryGetValue(name, out retvalObj)) { if (retvalObj is Type) { retvalType = (Type)retvalObj; } else if (retvalObj is string) { retvalType = Type.GetType((string)retvalObj, false, false); if (retvalType != null && !retvalType.IsVisible) { retvalType = null; } } else { Debug.Fail("Unsupported Dictionary value:" + retvalObj.ToString()); } } // Maybe they gave us a classname. if (retvalType == null) { retvalType = Type.GetType(name, false, false); if (retvalType != null && !retvalType.IsVisible) { retvalType = null; } } // Still null? Then we didn't find it. if (retvalType == null) { return null; } // Locate all constructors. MethodBase[] cons = retvalType.GetConstructors(ConstructorDefault); if (cons == null) { return null; } if (args == null) { args = new object[] { }; } List<MethodBase> candidates = new List<MethodBase>(); for (int i = 0; i < cons.Length; i++) { MethodBase con = cons[i]; if (con.GetParameters().Length == args.Length) { candidates.Add(con); } } if (candidates.Count == 0) { return null; } cons = candidates.ToArray(); // Bind to matching ctor. object state; ConstructorInfo rci = Type.DefaultBinder.BindToMethod( ConstructorDefault, cons, ref args, null, null, null, out state) as ConstructorInfo; // Check for ctor we don't like (non-existent, delegate or decorated with declarative linktime demand). if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType)) { return null; } // Ctor invoke and allocation. object retval = rci.Invoke(ConstructorDefault, Type.DefaultBinder, args, null); // Reset any parameter re-ordering performed by the binder. if (state != null) { Type.DefaultBinder.ReorderArgumentArray(ref args, state); } return retval; } public static object CreateFromName(string name) { return CreateFromName(name, null); } public static void AddOID(string oid, params string[] names) { if (oid == null) throw new ArgumentNullException(nameof(oid)); if (names == null) throw new ArgumentNullException(nameof(names)); string[] oidNames = new string[names.Length]; Array.Copy(names, oidNames, oidNames.Length); // Pre-check the input names for validity, so that we don't add a few of the names and throw an // exception if an invalid name is found further down the array. foreach (string name in oidNames) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException(SR.Cryptography_AddNullOrEmptyName); } } // Everything is valid, so we're good to lock the hash table and add the application mappings lock (s_InternalSyncObject) { foreach (string name in oidNames) { appOidHT[name] = oid; } } } public static string MapNameToOID(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); string oidName; // Check to see if we have an application defined mapping lock (s_InternalSyncObject) { if (!appOidHT.TryGetValue(name, out oidName)) { oidName = null; } } if (string.IsNullOrEmpty(oidName) && !DefaultOidHT.TryGetValue(name, out oidName)) { try { Oid oid = Oid.FromFriendlyName(name, OidGroup.All); oidName = oid.Value; } catch (CryptographicException) { } } return oidName; } public static byte[] EncodeOID(string str) { if (str == null) throw new ArgumentNullException(nameof(str)); string[] oidString = str.Split(SepArray); uint[] oidNums = new uint[oidString.Length]; for (int i = 0; i < oidString.Length; i++) { oidNums[i] = unchecked((uint)int.Parse(oidString[i], CultureInfo.InvariantCulture)); } // Handle the first two oidNums special if (oidNums.Length < 2) throw new CryptographicUnexpectedOperationException(SR.Cryptography_InvalidOID); uint firstTwoOidNums = unchecked((oidNums[0] * 40) + oidNums[1]); // Determine length of output array int encodedOidNumsLength = 2; // Reserve first two bytes for later EncodeSingleOidNum(firstTwoOidNums, null, ref encodedOidNumsLength); for (int i = 2; i < oidNums.Length; i++) { EncodeSingleOidNum(oidNums[i], null, ref encodedOidNumsLength); } // Allocate the array to receive encoded oidNums byte[] encodedOidNums = new byte[encodedOidNumsLength]; int encodedOidNumsIndex = 2; // Encode each segment EncodeSingleOidNum(firstTwoOidNums, encodedOidNums, ref encodedOidNumsIndex); for (int i = 2; i < oidNums.Length; i++) { EncodeSingleOidNum(oidNums[i], encodedOidNums, ref encodedOidNumsIndex); } Debug.Assert(encodedOidNumsIndex == encodedOidNumsLength); // Final return value is 06 <length> encodedOidNums[] if (encodedOidNumsIndex - 2 > 0x7f) throw new CryptographicUnexpectedOperationException(SR.Cryptography_Config_EncodedOIDError); encodedOidNums[0] = (byte)0x06; encodedOidNums[1] = (byte)(encodedOidNumsIndex - 2); return encodedOidNums; } private static void EncodeSingleOidNum(uint value, byte[] destination, ref int index) { // Write directly to destination starting at index, and update index based on how many bytes written. // If destination is null, just return updated index. if (unchecked((int)value) < 0x80) { if (destination != null) { destination[index++] = unchecked((byte)value); } else { index += 1; } } else if (value < 0x4000) { if (destination != null) { destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } else { index += 2; } } else if (value < 0x200000) { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 3; } } else if (value < 0x10000000) { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 21) | 0x80); destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 4; } } else { if (destination != null) { unchecked { destination[index++] = (byte)((value >> 28) | 0x80); destination[index++] = (byte)((value >> 21) | 0x80); destination[index++] = (byte)((value >> 14) | 0x80); destination[index++] = (byte)((value >> 7) | 0x80); destination[index++] = (byte)(value & 0x7f); } } else { index += 5; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Java.Text; using Java.Util; using SQLite; using Android.Graphics; namespace ENVision { [Activity(Label = "Sales Report")] public class ReportActivity : ParentActivity, DatePickerDialog.IOnDateSetListener { Button b_startDate; Button b_endDate; Button b_selected; SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.Us); List<DataTwoItems> items; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.ReportActivity); initMenu(); initDates(); updateListBox(); Button b_share = FindViewById<Button>(Resource.Id.b_share); b_share.Click += delegate { View rootView = FindViewById(Resource.Id.ll_report); Bitmap bitmap = getScreenShot(rootView); String filePath = store(bitmap, "screenshot-" + Guid.NewGuid() + ".png"); shareImage(filePath); }; } private void initDates() { b_startDate = FindViewById<Button>(Resource.Id.b_start); b_endDate = FindViewById<Button>(Resource.Id.b_end); b_endDate.Text = dateFormatter.Format(Calendar.GetInstance(Locale.Us).Time); DateTime today = DateTime.Parse(b_endDate.Text); //int dateSubtractor = ((int)today.DayOfWeek - 1) * -1; DateTime start = today.AddDays(-7); Calendar newDate = Calendar.GetInstance(Locale.Us); newDate.Set(start.Year, start.Month - 1, start.Day); b_startDate.Text = dateFormatter.Format(newDate.Time); b_startDate.Click += delegate { DateTime currently = DateTime.Parse(b_startDate.Text); DatePickerDialog datePicker = new DatePickerDialog(this, this, currently.Year, currently.Month - 1, currently.Day); b_selected = b_startDate; datePicker.Show(); }; b_endDate.Click += delegate { DateTime currently = DateTime.Parse(b_endDate.Text); DatePickerDialog datePicker = new DatePickerDialog(this, this, currently.Year, currently.Month - 1, currently.Day); b_selected = b_endDate; datePicker.Show(); }; } public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.Us); Calendar newDate = Calendar.GetInstance(Locale.Us); newDate.Set(year, monthOfYear, dayOfMonth); b_selected.Text = dateFormatter.Format(newDate.Time); updateListBox(); } private void updateListBox() { DBHandle handle = new DBHandle(); SQLiteConnection connection = handle.getConnection(); var q = connection.Query<Sales>("SELECT * FROM Sales WHERE SaleDate >= ? AND SaleDate <= ?", b_startDate.Text + " 00:00:00", b_endDate.Text + " 00:00:00"); float totalEarned = 0; float totalSpent = 0; float profit = 0; double growth = 0; double loss = 0; if (q.Count > 0) { foreach(Sales sale in q) { totalEarned += sale.SalePrice * sale.SaleQuantity; //totalSpent += sale.SaleCost * sale.SaleQuantity; //profit += ((sale.SalePrice - sale.SaleCost) * sale.SaleQuantity); //double figure = Math.Round(profit / totalEarned * 100, 2); //if (profit < 0) // loss = figure; //else // growth = figure; } } var q2 = connection.Query<Product>("SELECT * FROM Product"); if(q.Count > 0) { foreach(Product product in q2) { totalSpent += product.ProductCost * product.ProductStock; } } TextView tvearned = FindViewById<TextView>(Resource.Id.tv_earned); tvearned.Text = totalEarned + ""; TextView tvspent = FindViewById<TextView>(Resource.Id.tv_spent); tvspent.Text = totalSpent + ""; TextView tvprofit = FindViewById<TextView>(Resource.Id.tv_profit); tvprofit.Text = (totalEarned - totalSpent) + ""; TextView tvgrowth = FindViewById<TextView>(Resource.Id.tv_growth); tvgrowth.Text = growth + "%"; TextView tvloss = FindViewById<TextView>(Resource.Id.tv_loss); tvloss.Text = loss + "%"; } public Bitmap getScreenShot(View view) { View screenView = view.RootView; screenView.DrawingCacheEnabled = true; Bitmap bitmap = Bitmap.CreateBitmap(screenView.DrawingCache); screenView.DrawingCacheEnabled = false; return bitmap; } public String store(Bitmap bm, String fileName) { String sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Screenshots"; Java.IO.File dir = new Java.IO.File(sdCardPath); if (!dir.Exists()) dir.Mkdirs(); var filePath = ""; try { filePath = System.IO.Path.Combine(sdCardPath, fileName); var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create); bm.Compress(Bitmap.CompressFormat.Png, 85, stream); stream.Close(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.StackTrace); } return filePath; } private void shareImage(String file) { Intent intent = new Intent(); intent.SetAction(Intent.ActionSend); intent.SetType("image/*"); intent.PutExtra(Intent.ExtraSubject, "Sales"); intent.PutExtra(Intent.ExtraText, "Check my weekly sales"); intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file:///" + file)); try { StartActivity(Intent.CreateChooser(intent, "Share Screenshot")); } catch (ActivityNotFoundException e) { Toast.MakeText(this, "No App Available", ToastLength.Short).Show(); } } } }
// // SourceWatcher.cs // // Authors: // Christian Martellini <[email protected]> // Alexander Kojevnikov <[email protected]> // // Copyright (C) 2009 Christian Martellini // Copyright (C) 2009 Alexander Kojevnikov // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Threading; using System.Collections.Generic; using Hyena; using Hyena.Data.Sqlite; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Library; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Streaming; namespace Banshee.LibraryWatcher { public class SourceWatcher : IDisposable { private readonly LibraryImportManager import_manager; private readonly LibrarySource library; private readonly FileSystemWatcher watcher; private readonly ManualResetEvent handle; private readonly Thread watch_thread; private readonly Queue<QueueItem> queue = new Queue<QueueItem> (); private readonly TimeSpan delay = TimeSpan.FromMilliseconds (1000); private bool active; private bool disposed; private class QueueItem { public DateTime When; public WatcherChangeTypes ChangeType; public string OldFullPath; public string FullPath; public string MetadataHash; } public SourceWatcher (LibrarySource library) { this.library = library; handle = new ManualResetEvent(false); string path = library.BaseDirectoryWithSeparator; if (String.IsNullOrEmpty (path)) { throw new Exception ("Will not create LibraryWatcher for the blank directory"); } string home = Environment.GetFolderPath (Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar; if (path == home) { throw new Exception ("Will not create LibraryWatcher for the entire home directory"); } string root = Path.GetPathRoot (Environment.CurrentDirectory); if (path == root || path == root + Path.DirectorySeparatorChar) { throw new Exception ("Will not create LibraryWatcher for the entire root directory"); } if (!Banshee.IO.Directory.Exists (path)) { throw new Exception ("Will not create LibraryWatcher for non-existent directory"); } import_manager = ServiceManager.Get<LibraryImportManager> (); watcher = new FileSystemWatcher (path); watcher.IncludeSubdirectories = true; watcher.Changed += OnChanged; watcher.Created += OnChanged; watcher.Deleted += OnChanged; watcher.Renamed += OnChanged; active = true; watch_thread = new Thread (new ThreadStart (Watch)); watch_thread.Name = String.Format ("LibraryWatcher for {0}", library.Name); watch_thread.IsBackground = true; watch_thread.Start (); } #region Public Methods public void Dispose () { if (!disposed) { active = false; watcher.Changed -= OnChanged; watcher.Created -= OnChanged; watcher.Deleted -= OnChanged; watcher.Renamed -= OnChanged; lock (queue) { queue.Clear (); } watcher.Dispose (); disposed = true; } } #endregion #region Private Methods private void OnChanged (object source, FileSystemEventArgs args) { var item = new QueueItem { When = DateTime.Now, ChangeType = args.ChangeType, FullPath = args.FullPath, OldFullPath = args is RenamedEventArgs ? ((RenamedEventArgs)args).OldFullPath : args.FullPath }; lock (queue) { queue.Enqueue (item); } handle.Set (); if (args.ChangeType != WatcherChangeTypes.Changed) { Hyena.Log.DebugFormat ("Watcher: {0} {1}{2}", item.ChangeType, args is RenamedEventArgs ? item.OldFullPath + " => " : "", item.FullPath); } } private void Watch () { watcher.EnableRaisingEvents = true; while (active) { WatcherChangeTypes change_types = 0; while (queue.Count > 0) { QueueItem item; lock (queue) { item = queue.Dequeue (); } int sleep = (int) (item.When + delay - DateTime.Now).TotalMilliseconds; if (sleep > 0) { Hyena.Log.DebugFormat ("Watcher: sleeping {0}ms", sleep); Thread.Sleep (sleep); } if (item.ChangeType == WatcherChangeTypes.Changed) { UpdateTrack (item.FullPath); } else if (item.ChangeType == WatcherChangeTypes.Created) { AddTrack (item.FullPath); } else if (item.ChangeType == WatcherChangeTypes.Deleted) { RemoveTrack (item.FullPath); } else if (item.ChangeType == WatcherChangeTypes.Renamed) { RenameTrack (item.OldFullPath, item.FullPath); } change_types |= item.ChangeType; } if ((change_types & WatcherChangeTypes.Deleted) > 0) { library.NotifyTracksDeleted (); } if ((change_types & (WatcherChangeTypes.Renamed | WatcherChangeTypes.Created | WatcherChangeTypes.Changed)) > 0) { library.NotifyTracksChanged (); } handle.WaitOne (); handle.Reset (); } } private void UpdateTrack (string track) { using (var reader = ServiceManager.DbConnection.Query ( DatabaseTrackInfo.Provider.CreateFetchCommand ( "CoreTracks.PrimarySourceID = ? AND CoreTracks.Uri = ? LIMIT 1"), library.DbId, new SafeUri (track).AbsoluteUri)) { if (reader.Read ()) { var track_info = DatabaseTrackInfo.Provider.Load (reader); if (Banshee.IO.File.GetModifiedTime (track_info.Uri) > track_info.FileModifiedStamp) { using (var file = StreamTagger.ProcessUri (track_info.Uri)) { StreamTagger.TrackInfoMerge (track_info, file, false); } track_info.LastSyncedStamp = DateTime.Now; track_info.Save (false); } } } } private void AddTrack (string track) { import_manager.ImportTrack (track); // Trigger file rename. string uri = new SafeUri(track).AbsoluteUri; HyenaSqliteCommand command = new HyenaSqliteCommand (@" UPDATE CoreTracks SET DateUpdatedStamp = LastSyncedStamp + 1 WHERE Uri = ?", uri); ServiceManager.DbConnection.Execute (command); } private void RemoveTrack (string track) { string uri = new SafeUri(track).AbsoluteUri; const string hash_sql = @"SELECT TrackID, MetadataHash FROM CoreTracks WHERE Uri = ? LIMIT 1"; int track_id = 0; string hash = null; using (var reader = new HyenaDataReader (ServiceManager.DbConnection.Query (hash_sql, uri))) { if (reader.Read ()) { track_id = reader.Get<int> (0); hash = reader.Get<string> (1); } } if (hash != null) { lock (queue) { var item = queue.FirstOrDefault ( i => i.ChangeType == WatcherChangeTypes.Created && GetMetadataHash (i) == hash); if (item != null) { item.ChangeType = WatcherChangeTypes.Renamed; item.OldFullPath = track; return; } } } const string delete_sql = @" INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri) SELECT ?, TrackID, Uri FROM CoreTracks WHERE TrackID IN ({0}) ; DELETE FROM CoreTracks WHERE TrackID IN ({0})"; // If track_id is 0, it's a directory. HyenaSqliteCommand delete_command; if (track_id > 0) { delete_command = new HyenaSqliteCommand (String.Format (delete_sql, "?"), DateTime.Now, track_id, track_id); } else { string pattern = StringUtil.EscapeLike (uri) + "/_%"; delete_command = new HyenaSqliteCommand (String.Format (delete_sql, @"SELECT TrackID FROM CoreTracks WHERE Uri LIKE ? ESCAPE '\'"), DateTime.Now, pattern, pattern); } ServiceManager.DbConnection.Execute (delete_command); } private void RenameTrack(string oldFullPath, string fullPath) { if (oldFullPath == fullPath) { // FIXME: bug in Mono, see bnc#322330 return; } string old_uri = new SafeUri (oldFullPath).AbsoluteUri; string new_uri = new SafeUri (fullPath).AbsoluteUri; string pattern = StringUtil.EscapeLike (old_uri) + "%"; HyenaSqliteCommand rename_command = new HyenaSqliteCommand (@" UPDATE CoreTracks SET Uri = REPLACE(Uri, ?, ?), DateUpdatedStamp = ? WHERE Uri LIKE ? ESCAPE '\'", old_uri, new_uri, DateTime.Now, pattern); ServiceManager.DbConnection.Execute (rename_command); } private string GetMetadataHash (QueueItem item) { if (item.ChangeType == WatcherChangeTypes.Created && item.MetadataHash == null) { var uri = new SafeUri (item.FullPath); if (DatabaseImportManager.IsWhiteListedFile (item.FullPath) && Banshee.IO.File.Exists (uri)) { var track = new TrackInfo (); using (var file = StreamTagger.ProcessUri (uri)) { StreamTagger.TrackInfoMerge (track, file); } item.MetadataHash = track.MetadataHash; } } return item.MetadataHash; } #endregion } }
using System; using System.IO; using System.Text; namespace ICSharpCode.SharpZipLib.Tar { /// <summary> /// Used to advise clients of 'events' while processing archives /// </summary> public delegate void ProgressMessageHandler(TarArchive archive, TarEntry entry, string message); /// <summary> /// The TarArchive class implements the concept of a /// 'Tape Archive'. A tar archive is a series of entries, each of /// which represents a file system object. Each entry in /// the archive consists of a header block followed by 0 or more data blocks. /// Directory entries consist only of the header block, and are followed by entries /// for the directory's contents. File entries consist of a /// header followed by the number of blocks needed to /// contain the file's contents. All entries are written on /// block boundaries. Blocks are 512 bytes long. /// /// TarArchives are instantiated in either read or write mode, /// based upon whether they are instantiated with an InputStream /// or an OutputStream. Once instantiated TarArchives read/write /// mode can not be changed. /// /// There is currently no support for random access to tar archives. /// However, it seems that subclassing TarArchive, and using the /// TarBuffer.CurrentRecord and TarBuffer.CurrentBlock /// properties, this would be rather trivial. /// </summary> public class TarArchive : IDisposable { /// <summary> /// Client hook allowing detailed information to be reported during processing /// </summary> public event ProgressMessageHandler ProgressMessageEvent; /// <summary> /// Raises the ProgressMessage event /// </summary> /// <param name="entry">The <see cref="TarEntry">TarEntry</see> for this event</param> /// <param name="message">message for this event. Null is no message</param> protected virtual void OnProgressMessageEvent(TarEntry entry, string message) { ProgressMessageHandler handler = ProgressMessageEvent; if (handler != null) { handler(this, entry, message); } } #region Constructors /// <summary> /// Constructor for a default <see cref="TarArchive"/>. /// </summary> protected TarArchive() { } /// <summary> /// Initalise a TarArchive for input. /// </summary> /// <param name="stream">The <see cref="TarInputStream"/> to use for input.</param> protected TarArchive(TarInputStream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } tarIn = stream; } /// <summary> /// Initialise a TarArchive for output. /// </summary> /// <param name="stream">The <see cref="TarOutputStream"/> to use for output.</param> protected TarArchive(TarOutputStream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } tarOut = stream; } #endregion Constructors #region Static factory methods /// <summary> /// The InputStream based constructors create a TarArchive for the /// purposes of extracting or listing a tar archive. Thus, use /// these constructors when you wish to extract files from or list /// the contents of an existing tar archive. /// </summary> /// <param name="inputStream">The stream to retrieve archive data from.</param> /// <returns>Returns a new <see cref="TarArchive"/> suitable for reading from.</returns> public static TarArchive CreateInputTarArchive(Stream inputStream) { if (inputStream == null) { throw new ArgumentNullException(nameof(inputStream)); } var tarStream = inputStream as TarInputStream; TarArchive result; if (tarStream != null) { result = new TarArchive(tarStream); } else { result = CreateInputTarArchive(inputStream, TarBuffer.DefaultBlockFactor); } return result; } /// <summary> /// Create TarArchive for reading setting block factor /// </summary> /// <param name="inputStream">A stream containing the tar archive contents</param> /// <param name="blockFactor">The blocking factor to apply</param> /// <returns>Returns a <see cref="TarArchive"/> suitable for reading.</returns> public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFactor) { if (inputStream == null) { throw new ArgumentNullException(nameof(inputStream)); } if (inputStream is TarInputStream) { throw new ArgumentException("TarInputStream not valid"); } return new TarArchive(new TarInputStream(inputStream, blockFactor)); } /// <summary> /// Create a TarArchive for writing to, using the default blocking factor /// </summary> /// <param name="outputStream">The <see cref="Stream"/> to write to</param> /// <returns>Returns a <see cref="TarArchive"/> suitable for writing.</returns> public static TarArchive CreateOutputTarArchive(Stream outputStream) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } var tarStream = outputStream as TarOutputStream; TarArchive result; if (tarStream != null) { result = new TarArchive(tarStream); } else { result = CreateOutputTarArchive(outputStream, TarBuffer.DefaultBlockFactor); } return result; } /// <summary> /// Create a <see cref="TarArchive">tar archive</see> for writing. /// </summary> /// <param name="outputStream">The stream to write to</param> /// <param name="blockFactor">The blocking factor to use for buffering.</param> /// <returns>Returns a <see cref="TarArchive"/> suitable for writing.</returns> public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFactor) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } if (outputStream is TarOutputStream) { throw new ArgumentException("TarOutputStream is not valid"); } return new TarArchive(new TarOutputStream(outputStream, blockFactor)); } #endregion Static factory methods /// <summary> /// Set the flag that determines whether existing files are /// kept, or overwritten during extraction. /// </summary> /// <param name="keepExistingFiles"> /// If true, do not overwrite existing files. /// </param> public void SetKeepOldFiles(bool keepExistingFiles) { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } keepOldFiles = keepExistingFiles; } /// <summary> /// Get/set the ascii file translation flag. If ascii file translation /// is true, then the file is checked to see if it a binary file or not. /// If the flag is true and the test indicates it is ascii text /// file, it will be translated. The translation converts the local /// operating system's concept of line ends into the UNIX line end, /// '\n', which is the defacto standard for a TAR archive. This makes /// text files compatible with UNIX. /// </summary> public bool AsciiTranslate { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return asciiTranslate; } set { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } asciiTranslate = value; } } /// <summary> /// Set the ascii file translation flag. /// </summary> /// <param name= "translateAsciiFiles"> /// If true, translate ascii text files. /// </param> [Obsolete("Use the AsciiTranslate property")] public void SetAsciiTranslation(bool translateAsciiFiles) { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } asciiTranslate = translateAsciiFiles; } /// <summary> /// PathPrefix is added to entry names as they are written if the value is not null. /// A slash character is appended after PathPrefix /// </summary> public string PathPrefix { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return pathPrefix; } set { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } pathPrefix = value; } } /// <summary> /// RootPath is removed from entry names if it is found at the /// beginning of the name. /// </summary> public string RootPath { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return rootPath; } set { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } // Convert to forward slashes for matching. Trim trailing / for correct final path rootPath = value.Replace('\\', '/').TrimEnd('/'); } } /// <summary> /// Set user and group information that will be used to fill in the /// tar archive's entry headers. This information is based on that available /// for the linux operating system, which is not always available on other /// operating systems. TarArchive allows the programmer to specify values /// to be used in their place. /// <see cref="ApplyUserInfoOverrides"/> is set to true by this call. /// </summary> /// <param name="userId"> /// The user id to use in the headers. /// </param> /// <param name="userName"> /// The user name to use in the headers. /// </param> /// <param name="groupId"> /// The group id to use in the headers. /// </param> /// <param name="groupName"> /// The group name to use in the headers. /// </param> public void SetUserInfo(int userId, string userName, int groupId, string groupName) { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } this.userId = userId; this.userName = userName; this.groupId = groupId; this.groupName = groupName; applyUserInfoOverrides = true; } /// <summary> /// Get or set a value indicating if overrides defined by <see cref="SetUserInfo">SetUserInfo</see> should be applied. /// </summary> /// <remarks>If overrides are not applied then the values as set in each header will be used.</remarks> public bool ApplyUserInfoOverrides { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return applyUserInfoOverrides; } set { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } applyUserInfoOverrides = value; } } /// <summary> /// Get the archive user id. /// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail /// on how to allow setting values on a per entry basis. /// </summary> /// <returns> /// The current user id. /// </returns> public int UserId { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return userId; } } /// <summary> /// Get the archive user name. /// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail /// on how to allow setting values on a per entry basis. /// </summary> /// <returns> /// The current user name. /// </returns> public string UserName { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return userName; } } /// <summary> /// Get the archive group id. /// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail /// on how to allow setting values on a per entry basis. /// </summary> /// <returns> /// The current group id. /// </returns> public int GroupId { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return groupId; } } /// <summary> /// Get the archive group name. /// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail /// on how to allow setting values on a per entry basis. /// </summary> /// <returns> /// The current group name. /// </returns> public string GroupName { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return groupName; } } /// <summary> /// Get the archive's record size. Tar archives are composed of /// a series of RECORDS each containing a number of BLOCKS. /// This allowed tar archives to match the IO characteristics of /// the physical device being used. Archives are expected /// to be properly "blocked". /// </summary> /// <returns> /// The record size this archive is using. /// </returns> public int RecordSize { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } if (tarIn != null) { return tarIn.RecordSize; } else if (tarOut != null) { return tarOut.RecordSize; } return TarBuffer.DefaultRecordSize; } } /// <summary> /// Sets the IsStreamOwner property on the underlying stream. /// Set this to false to prevent the Close of the TarArchive from closing the stream. /// </summary> public bool IsStreamOwner { set { if (tarIn != null) { tarIn.IsStreamOwner = value; } else { tarOut.IsStreamOwner = value; } } } /// <summary> /// Close the archive. /// </summary> [Obsolete("Use Close instead")] public void CloseArchive() { Close(); } /// <summary> /// Perform the "list" command for the archive contents. /// /// NOTE That this method uses the <see cref="ProgressMessageEvent"> progress event</see> to actually list /// the contents. If the progress display event is not set, nothing will be listed! /// </summary> public void ListContents() { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } while (true) { TarEntry entry = tarIn.GetNextEntry(); if (entry == null) { break; } OnProgressMessageEvent(entry, null); } } /// <summary> /// Perform the "extract" command and extract the contents of the archive. /// </summary> /// <param name="destinationDirectory"> /// The destination directory into which to extract. /// </param> public void ExtractContents(string destinationDirectory) { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } while (true) { TarEntry entry = tarIn.GetNextEntry(); if (entry == null) { break; } if (entry.TarHeader.TypeFlag == TarHeader.LF_LINK || entry.TarHeader.TypeFlag == TarHeader.LF_SYMLINK) continue; ExtractEntry(destinationDirectory, entry); } } /// <summary> /// Extract an entry from the archive. This method assumes that the /// tarIn stream has been properly set with a call to GetNextEntry(). /// </summary> /// <param name="destDir"> /// The destination directory into which to extract. /// </param> /// <param name="entry"> /// The TarEntry returned by tarIn.GetNextEntry(). /// </param> private void ExtractEntry(string destDir, TarEntry entry) { OnProgressMessageEvent(entry, null); string name = entry.Name; if (Path.IsPathRooted(name)) { // NOTE: // for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt name = name.Substring(Path.GetPathRoot(name).Length); } name = name.Replace('/', Path.DirectorySeparatorChar); string destFile = Path.Combine(destDir, name); if (entry.IsDirectory) { EnsureDirectoryExists(destFile); } else { string parentDirectory = Path.GetDirectoryName(destFile); EnsureDirectoryExists(parentDirectory); bool process = true; var fileInfo = new FileInfo(destFile); if (fileInfo.Exists) { if (keepOldFiles) { OnProgressMessageEvent(entry, "Destination file already exists"); process = false; } else if ((fileInfo.Attributes & FileAttributes.ReadOnly) != 0) { OnProgressMessageEvent(entry, "Destination file already exists, and is read-only"); process = false; } } if (process) { using (var outputStream = File.Create(destFile)) { if (this.asciiTranslate) { // May need to translate the file. ExtractAndTranslateEntry(destFile, outputStream); } else { // If translation is disabled, just copy the entry across directly. tarIn.CopyEntryContents(outputStream); } } } } } // Extract a TAR entry, and perform an ASCII translation if required. private void ExtractAndTranslateEntry(string destFile, Stream outputStream) { bool asciiTrans = !IsBinary(destFile); if (asciiTrans) { using (var outw = new StreamWriter(outputStream, new UTF8Encoding(false), 1024, true)) { byte[] rdbuf = new byte[32 * 1024]; while (true) { int numRead = tarIn.Read(rdbuf, 0, rdbuf.Length); if (numRead <= 0) { break; } for (int off = 0, b = 0; b < numRead; ++b) { if (rdbuf[b] == 10) { string s = Encoding.ASCII.GetString(rdbuf, off, (b - off)); outw.WriteLine(s); off = b + 1; } } } } } else { // No translation required. tarIn.CopyEntryContents(outputStream); } } /// <summary> /// Write an entry to the archive. This method will call the putNextEntry /// and then write the contents of the entry, and finally call closeEntry() /// for entries that are files. For directories, it will call putNextEntry(), /// and then, if the recurse flag is true, process each entry that is a /// child of the directory. /// </summary> /// <param name="sourceEntry"> /// The TarEntry representing the entry to write to the archive. /// </param> /// <param name="recurse"> /// If true, process the children of directory entries. /// </param> public void WriteEntry(TarEntry sourceEntry, bool recurse) { if (sourceEntry == null) { throw new ArgumentNullException(nameof(sourceEntry)); } if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } try { if (recurse) { TarHeader.SetValueDefaults(sourceEntry.UserId, sourceEntry.UserName, sourceEntry.GroupId, sourceEntry.GroupName); } WriteEntryCore(sourceEntry, recurse); } finally { if (recurse) { TarHeader.RestoreSetValues(); } } } /// <summary> /// Write an entry to the archive. This method will call the putNextEntry /// and then write the contents of the entry, and finally call closeEntry() /// for entries that are files. For directories, it will call putNextEntry(), /// and then, if the recurse flag is true, process each entry that is a /// child of the directory. /// </summary> /// <param name="sourceEntry"> /// The TarEntry representing the entry to write to the archive. /// </param> /// <param name="recurse"> /// If true, process the children of directory entries. /// </param> private void WriteEntryCore(TarEntry sourceEntry, bool recurse) { string tempFileName = null; string entryFilename = sourceEntry.File; var entry = (TarEntry)sourceEntry.Clone(); if (applyUserInfoOverrides) { entry.GroupId = groupId; entry.GroupName = groupName; entry.UserId = userId; entry.UserName = userName; } OnProgressMessageEvent(entry, null); if (asciiTranslate && !entry.IsDirectory) { if (!IsBinary(entryFilename)) { tempFileName = Path.GetTempFileName(); using (StreamReader inStream = File.OpenText(entryFilename)) { using (Stream outStream = File.Create(tempFileName)) { while (true) { string line = inStream.ReadLine(); if (line == null) { break; } byte[] data = Encoding.ASCII.GetBytes(line); outStream.Write(data, 0, data.Length); outStream.WriteByte((byte)'\n'); } outStream.Flush(); } } entry.Size = new FileInfo(tempFileName).Length; entryFilename = tempFileName; } } string newName = null; if (!String.IsNullOrEmpty(rootPath)) { if (entry.Name.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase)) { newName = entry.Name.Substring(rootPath.Length + 1); } } if (pathPrefix != null) { newName = (newName == null) ? pathPrefix + "/" + entry.Name : pathPrefix + "/" + newName; } if (newName != null) { entry.Name = newName; } tarOut.PutNextEntry(entry); if (entry.IsDirectory) { if (recurse) { TarEntry[] list = entry.GetDirectoryEntries(); for (int i = 0; i < list.Length; ++i) { WriteEntryCore(list[i], recurse); } } } else { using (Stream inputStream = File.OpenRead(entryFilename)) { byte[] localBuffer = new byte[32 * 1024]; while (true) { int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); if (numRead <= 0) { break; } tarOut.Write(localBuffer, 0, numRead); } } if (!string.IsNullOrEmpty(tempFileName)) { File.Delete(tempFileName); } tarOut.CloseEntry(); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; /// false to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; if (disposing) { if (tarOut != null) { tarOut.Flush(); tarOut.Dispose(); } if (tarIn != null) { tarIn.Dispose(); } } } } /// <summary> /// Closes the archive and releases any associated resources. /// </summary> public virtual void Close() { Dispose(true); } /// <summary> /// Ensures that resources are freed and other cleanup operations are performed /// when the garbage collector reclaims the <see cref="TarArchive"/>. /// </summary> ~TarArchive() { Dispose(false); } private static void EnsureDirectoryExists(string directoryName) { if (!Directory.Exists(directoryName)) { try { Directory.CreateDirectory(directoryName); } catch (Exception e) { throw new TarException("Exception creating directory '" + directoryName + "', " + e.Message, e); } } } // TODO: TarArchive - Is there a better way to test for a text file? // It no longer reads entire files into memory but is still a weak test! // This assumes that byte values 0-7, 14-31 or 255 are binary // and that all non text files contain one of these values private static bool IsBinary(string filename) { using (FileStream fs = File.OpenRead(filename)) { int sampleSize = Math.Min(4096, (int)fs.Length); byte[] content = new byte[sampleSize]; int bytesRead = fs.Read(content, 0, sampleSize); for (int i = 0; i < bytesRead; ++i) { byte b = content[i]; if ((b < 8) || ((b > 13) && (b < 32)) || (b == 255)) { return true; } } } return false; } #region Instance Fields private bool keepOldFiles; private bool asciiTranslate; private int userId; private string userName = string.Empty; private int groupId; private string groupName = string.Empty; private string rootPath; private string pathPrefix; private bool applyUserInfoOverrides; private TarInputStream tarIn; private TarOutputStream tarOut; private bool isDisposed; #endregion Instance Fields } }
// Copyright (c) 2016-2022 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Diagnostics; using System.IO; using System.Reflection; using NUnit.Framework; namespace Icu.Tests { [Platform(Exclude = "Linux", Reason = "These tests require ICU4C installed from NuGet packages which isn't available on Linux")] [TestFixture] public class NativeMethodsTests { private string _tmpDir; private string _pathEnvironmentVariable; public const string FullIcuLibraryVersion = "62.1"; public const string FullIcuLibraryVersionMajor = "62"; public const string MinIcuLibraryVersion = "59.1"; public const string MinIcuLibraryVersionMajor = "59"; internal static int MaxInstalledIcuLibraryVersion { get { var fullVersion = int.Parse(FullIcuLibraryVersionMajor); var minVersion = int.Parse(MinIcuLibraryVersionMajor); return Math.Max(fullVersion, minVersion); } } internal static void CopyFile(string srcPath, string dstDir) { var fileName = Path.GetFileName(srcPath); File.Copy(srcPath, Path.Combine(dstDir, fileName)); } private static void CopyFilesFromDirectory(string srcPath, string dstDir) { var srcDirectory = new DirectoryInfo(srcPath); foreach (var file in srcDirectory.GetFiles()) { CopyFile(file.FullName, dstDir); } } private static bool IsRunning64Bit => IntPtr.Size == 8; internal static string GetArchSubdir(string prefix = "") { var archSubdir = IsRunning64Bit ? "x64" : "x86"; return $"{prefix}{archSubdir}"; } internal static string OutputDirectory => Path.GetDirectoryName( new Uri( #if NET40 typeof(NativeMethodsTests).Assembly.CodeBase #elif NET5_0_OR_GREATER typeof(NativeMethodsTests).GetTypeInfo().Assembly.Location #else typeof(NativeMethodsTests).GetTypeInfo().Assembly.CodeBase #endif ) .LocalPath); internal static string IcuDirectory { get { var directory = Path.Combine(OutputDirectory, "lib", GetArchSubdir("win-")); if (Directory.Exists(directory)) return directory; directory = Path.Combine(OutputDirectory, "runtimes", GetArchSubdir("win7-"), "native"); if (Directory.Exists(directory)) return directory; throw new DirectoryNotFoundException("Can't find ICU directory"); } } private string RunTestHelper(string workDir, string exeDir = null) { if (string.IsNullOrEmpty(exeDir)) exeDir = _tmpDir; using var process = new Process(); process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = workDir; var filename = Path.Combine(exeDir, "TestHelper.exe"); if (File.Exists(filename)) { process.StartInfo.Arguments = $"{Wrapper.MinSupportedIcuVersion} {MaxInstalledIcuLibraryVersion}"; } else { // netcore process.StartInfo.Arguments = $"{Path.Combine(exeDir, "TestHelper.dll")} {Wrapper.MinSupportedIcuVersion} {MaxInstalledIcuLibraryVersion}"; filename = "dotnet"; } process.StartInfo.FileName = filename; process.Start(); var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { Console.WriteLine(process.StandardError.ReadToEnd()); } return output.TrimEnd('\r', '\n'); } private static void CopyMinimalIcuFiles(string targetDir) { CopyFile(Path.Combine(IcuDirectory, $"icudt{MinIcuLibraryVersionMajor}.dll"), targetDir); CopyFile(Path.Combine(IcuDirectory, $"icuin{MinIcuLibraryVersionMajor}.dll"), targetDir); CopyFile(Path.Combine(IcuDirectory, $"icuuc{MinIcuLibraryVersionMajor}.dll"), targetDir); } internal static void CopyTestFiles(string sourceDir, string targetDir) { // sourceDir is something like output/Debug/net461, TestHelper is in output/Debug/TestHelper/net461 var framework = Path.GetFileName(sourceDir); sourceDir = Path.Combine(sourceDir, "..", "TestHelper", framework); CopyFilesFromDirectory(sourceDir, targetDir); } [SetUp] public void Setup() { _tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(_tmpDir); CopyTestFiles(OutputDirectory, _tmpDir); _pathEnvironmentVariable = Environment.GetEnvironmentVariable("PATH"); var path = $"{IcuDirectory}{Path.PathSeparator}{_pathEnvironmentVariable}"; Environment.SetEnvironmentVariable("PATH", path); } [TearDown] public void TearDown() { Wrapper.Cleanup(); DeleteDirectory(_tmpDir); Environment.SetEnvironmentVariable("PATH", _pathEnvironmentVariable); } internal static void DeleteDirectory(string tmpDir) { if (string.IsNullOrEmpty(tmpDir)) return; try { Directory.Delete(tmpDir, true); } catch (IOException e) { Console.WriteLine( $"IOException trying to delete temporary directory {tmpDir}: {e.Message}"); foreach (var f in new DirectoryInfo(tmpDir).EnumerateFileSystemInfos()) { try { if (f is DirectoryInfo directoryInfo) directoryInfo.Delete(true); else f.Delete(); } catch (Exception) { // just ignore - not worth failing the test if we can't delete // a temporary file Console.WriteLine($"Can't delete {f.Name}"); } } // Try again to delete the directory try { Directory.Delete(tmpDir, true); } catch (Exception) { // just ignore - not worth failing the test if we can't delete // a temporary directory Console.WriteLine($"Still can't delete {tmpDir}"); } } } [Test] public void LoadIcuLibrary_GetFromPath() { Assert.That(RunTestHelper(_tmpDir), Is.EqualTo(FullIcuLibraryVersion)); } [Test] public void LoadIcuLibrary_GetFromPathDifferentDir() { Assert.That(RunTestHelper(Path.GetTempPath()), Is.EqualTo(FullIcuLibraryVersion)); } [Test] public void LoadIcuLibrary_LoadLocalVersion() { CopyMinimalIcuFiles(_tmpDir); Assert.That(RunTestHelper(_tmpDir), Is.EqualTo(MinIcuLibraryVersion)); } [Test] public void LoadIcuLibrary_LoadLocalVersionDifferentWorkDir() { CopyMinimalIcuFiles(_tmpDir); Assert.That(RunTestHelper(Path.GetTempPath()), Is.EqualTo(MinIcuLibraryVersion)); } [TestCase("")] [TestCase("win-")] public void LoadIcuLibrary_LoadLocalVersionFromArchSubDir(string prefix) { var targetDir = Path.Combine(_tmpDir, GetArchSubdir(prefix)); Directory.CreateDirectory(targetDir); CopyMinimalIcuFiles(targetDir); Assert.That(RunTestHelper(_tmpDir), Is.EqualTo(MinIcuLibraryVersion)); } [Test] public void LoadIcuLibrary_LoadLocalVersion_DirectoryWithSpaces() { var subdir = Path.Combine(_tmpDir, "Dir With Spaces"); Directory.CreateDirectory(subdir); CopyTestFiles(OutputDirectory, subdir); CopyMinimalIcuFiles(subdir); Assert.That(RunTestHelper(subdir, subdir), Is.EqualTo(MinIcuLibraryVersion)); } } }
using System; #if !(UNIVERSALW8 || FULL_BUILD || PURE_CLIENT_LIB) using System.Windows.Controls; #endif #if !FULL_BUILD && !UNIVERSALW8 && !WINDOWS_PHONE && !PURE_CLIENT_LIB && !WINDOWS_PHONE8 using System.Security; using System.Windows.Browser; #endif #if !(NET_35 || NET_40) using System.Threading.Tasks; #endif using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Net; using Weborb.Message; using Weborb.Protocols.Amf; using Weborb.Reader; using Weborb.Types; using Weborb.Util.Logging; using Weborb.V3Types; namespace Weborb.Client { public abstract class Engine { protected const string TIMEOUT_FAULT_MESSAGE = "Request timeout"; protected const string SECURITY_FAULT_MESSAGE = "Unable to connect to the server. Make sure clientaccesspolicy.xml are deployed in the root of the web server the client will communicate with."; private CookieContainer _cookies; public CookieContainer Cookies { get { return _cookies; } set { _cookies = value; } } private int _timeout = 0; public int Timeout { get { return _timeout; } set { _timeout = value; } } protected Dictionary<string, Subscription> Subscriptions = new Dictionary<string, Subscription>(); public Subscription GetSubscription(string clientId) { if ( Subscriptions.ContainsKey( clientId ) ) return Subscriptions[clientId]; return null; } public void SetSubscription(Subscription subscription ) { if ( Subscriptions.ContainsKey( subscription.ClientId ) ) Subscriptions[subscription.ClientId] = subscription; else Subscriptions.Add( subscription.ClientId, subscription ); } public void RemoveSubscription( string clientId ) { if ( Subscriptions.ContainsKey( clientId ) ) Subscriptions.Remove( clientId ); } private Dictionary<string, object> _responder = new Dictionary<string, object>(); public Responder<T> GetResponder<T>(string clientId) { if(_responder.ContainsKey(clientId)) return (Responder<T>)_responder[clientId]; return null; } private object GetResponder(string clientId) { if ( _responder.ContainsKey( clientId ) ) return _responder[clientId]; return null; } public void SetResponder<T>(string clientId, Responder<T> responder) { if ( _responder.ContainsKey( clientId ) ) _responder[clientId] = responder; else _responder.Add(clientId, responder); } public void RemoveResponder(string clientId) { if ( _responder.ContainsKey( clientId ) ) _responder.Remove(clientId); } public static Engine Create(string gatewayUrl, IdInfo idInfo) { if( gatewayUrl.StartsWith( "http://" ) || gatewayUrl.StartsWith( "https://" ) ) #if !( NET_35 || NET_40 ) return new HttpEngineWithClient(gatewayUrl, idInfo); #else return new HttpEngineWithRequest( gatewayUrl, idInfo ); #endif #if !UNIVERSALW8 && !PURE_CLIENT_LIB && !WINDOWS_PHONE8 if (gatewayUrl.StartsWith("rtmpt://")) return new RtmptEngine(gatewayUrl, idInfo); #endif #if( !UNIVERSALW8 && !WINDOWS_PHONE && !PURE_CLIENT_LIB && !WINDOWS_PHONE8 ) if (gatewayUrl.StartsWith("rtmp://")) return new RtmpEngine(gatewayUrl, idInfo); #endif throw new ArgumentOutOfRangeException("gatewayUrl", "Unsupported URI scheme in the gateway URL."); } public String GatewayUrl; public IdInfo IdInfo; internal const string INTERNAL_CLIENT_EXCEPTION_FAULT_CODE = "Internal client exception"; internal Engine(string gateway, IdInfo idInfo) { GatewayUrl = gateway; IdInfo = idInfo.MemberwiseClone(); } #if !( UNIVERSALW8 || FULL_BUILD || PURE_CLIENT_LIB ) public static Engine Create(string gatewayUrl, IdInfo idInfo, UserControl uiControl) { Engine engine = Create(gatewayUrl, idInfo); engine.UiControl = uiControl; return engine; } internal UserControl UiControl; #endif internal abstract void Invoke<T>(string className, string methodName, object[] args, IDictionary requestHeaders, IDictionary messageHeaders, IDictionary httpHeaders, Responder<T> responder, AsyncStreamSetInfo<T> asyncStreamSetInfo); public abstract void SendRequest<T>( V3Message v3Msg, IDictionary requestHeaders, IDictionary httpHeaders, Responder<T> responder, AsyncStreamSetInfo<T> asyncStreamSetInfo ); #if !( NET_35 || NET_40 ) internal abstract Task<T> Invoke<T>(string className, string methodName, object[] args, IDictionary requestHeaders, IDictionary messageHeaders, IDictionary httpHeaders, ResponseThreadConfigurator threadConfigurator ); public abstract Task<T> SendRequest<T>( V3Message v3Msg, IDictionary requestHeaders, IDictionary httpHeaders, ResponseThreadConfigurator threadConfigurator ); #endif internal void SendRequest<T>( V3Message v3Msg, Responder<T> responder ) { SendRequest( v3Msg, null, null, responder, null ); } internal bool IsRTMP() { #if UNIVERSALW8 || PURE_CLIENT_LIB || WINDOWS_PHONE8 return false; #else return this is BaseRtmpEngine; #endif } internal virtual void OnSubscribed(string subTopic, string selector, string clientId) { GetSubscription(clientId).InvokeSubscribed(); } internal virtual void OnUnsubscribed(string clientId) { RemoveSubscription(clientId); RemoveResponder(clientId); } protected void ReceivedMessage<T>(AckMessage message) { object responder = GetResponder(message.clientId.ToString()); if (responder == null) return; object[] arr = (object[])((ArrayType)message.body.body).getArray(); foreach (var o in arr) { IAdaptingType adaptingType = (IAdaptingType)o; GetResponder<T>( message.clientId.ToString() ).ResponseHandler( (T)adaptingType.adapt( typeof( T ) ) ); } } protected void ReceivedMessage( AsyncMessage message ) { object responder = GetResponder(message.clientId.ToString()); if (responder != null && responder is ISubscribeResponder ) ( (ISubscribeResponder)responder ).ResponseHandler( message ); } internal V3Message CreateMessageForInvocation( String className, String methodName, Object[] args, IDictionary headers ) { ReqMessage bodyMessage = new ReqMessage(); bodyMessage.body = new BodyHolder(); bodyMessage.body.body = args == null ? new object[0] : args; bodyMessage.destination = IdInfo.Destination; bodyMessage.headers = headers; if ( className != null ) bodyMessage.source = className; bodyMessage.operation = methodName; return bodyMessage; } protected void ProcessV3Message<T>( V3Types.V3Message v3, Responder<T> responder ) { try { if ( IdInfo != null && IdInfo.DsId == null && v3.headers != null ) { try { IdInfo.DsId = (String)v3.headers["DSId"]; } catch ( KeyNotFoundException ) { } } // if ( IdInfo != null && IdInfo.ClientId == null ) // IdInfo.ClientId = (String)v3.clientId; List<T> messagesFirstPhase = new List<T>(); foreach ( Object returnValueElement in (Object[])v3.body.body ) ProcessElement( returnValueElement, messagesFirstPhase ); foreach ( T adaptedObject in messagesFirstPhase ) { #if !( UNIVERSALW8 || FULL_BUILD || PURE_CLIENT_LIB ) if (UiControl != null && responder != null) UiControl.Dispatcher.BeginInvoke(delegate() { responder.ResponseHandler(adaptedObject); }); else #endif if ( responder != null ) responder.ResponseHandler( adaptedObject ); } } catch ( Exception e ) { ProccessException(e, responder); } } protected void ProccessException<T>(Exception e, Responder<T> responder) { if ( responder != null ) { Fault fault = new Fault( e.Message, e.StackTrace, INTERNAL_CLIENT_EXCEPTION_FAULT_CODE ); #if( !UNIVERSALW8 && !FULL_BUILD && !WINDOWS_PHONE && !PURE_CLIENT_LIB && !WINDOWS_PHONE8 ) if ( e is SecurityException ) fault = new Fault(SECURITY_FAULT_MESSAGE, e.Message); #endif if ( e is WebException && ( (WebException)e ).Status == WebExceptionStatus.RequestCanceled ) fault = new Fault( TIMEOUT_FAULT_MESSAGE, TIMEOUT_FAULT_MESSAGE, "timeout" ); responder.ErrorHandler( fault ); } } private void ProcessElement<T>( Object returnValue, List<T> collector ) { // try { if( returnValue.GetType().IsArray ) { Object[] returnValueArray = (Object[]) returnValue; Object[] adaptedValues = new object[returnValueArray.Length]; if( returnValueArray.Length == 0 && !typeof( T ).IsArray && !IsIListGeneric( typeof( T ) ) ) throw new InvalidCastException(returnValue.GetType().Name + " cannot be casted to " + typeof(T).Name); //collector.Add( (T) returnValue ); else { for( int i = 0; i < returnValueArray.Length; i++ ) { Object adaptedObject = ((IAdaptingType) returnValueArray[i]).defaultAdapt(); adaptedValues[i] = adaptedObject; if( adaptedObject is AsyncMessage ) { ((AsyncMessage) adaptedObject)._body.body = ((Object[]) ((AsyncMessage) adaptedObject)._body.body)[0]; collector.Add( (T) adaptedObject ); } else if( !typeof( T ).IsArray && !IsIListGeneric( typeof( T ) ) ) { collector.Add( (T) adaptedObject ); } } if( typeof( T ).IsArray ) { Array arrayInstance = Array.CreateInstance( typeof( T ).GetElementType(), adaptedValues.Length ); for( int i = 0; i < adaptedValues.Length; i++ ) { arrayInstance.SetValue( adaptedValues[i], i ); } object convertedObject = Convert.ChangeType( arrayInstance, typeof( T ), new NumberFormatInfo() ); collector.Add( (T) convertedObject ); } else if( IsIListGeneric( typeof( T ) ) ) { object list = Weborb.Util.ObjectFactories.CreateServiceObject( typeof( T ) ); //object list = Activator.CreateInstance( typeof( T ) ); for( int i = 0; i < adaptedValues.Length; i++ ) { MethodInfo addMethod = list.GetType().GetMethod( "Add" ); addMethod.Invoke( list, new object[] {adaptedValues[i]} ); } collector.Add( (T) list ); } } } else { T adaptedObject = (T) ((IAdaptingType) returnValue).adapt( typeof( T ) ); collector.Add( adaptedObject ); } } /* catch( Exception e ) { if( Log.isLogging( LoggingConstants.ERROR ) ) Log.log( LoggingConstants.ERROR, "Error while proccesing messsage" ); if( Log.isLogging( LoggingConstants.EXCEPTION ) ) Log.log( LoggingConstants.EXCEPTION, e ); throw e; }*/ } private bool IsIListGeneric(Type type) { if ( type == null ) { throw new ArgumentNullException( "type" ); } foreach ( Type interfaceType in type.GetInterfaces() ) { if ( interfaceType.IsGenericType ) { if ( interfaceType.GetGenericTypeDefinition() == typeof( ICollection<> ) ) { // if needed, you can also return the type used as generic argument return true; } } } return false; } } }
/* * 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.Reflection; using System.Text.RegularExpressions; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Assets; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Gather uuids for a given entity. /// </summary> /// /// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts /// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets /// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be /// retrieved to work out which assets it references). public class UuidGatherer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Asset cache used for gathering assets /// </summary> protected IAssetService m_assetCache; /// <summary> /// Used as a temporary store of an asset which represents an object. This can be a null if no appropriate /// asset was found by the asset service. /// </summary> protected AssetBase m_requestedObjectAsset; /// <summary> /// Signal whether we are currently waiting for the asset service to deliver an asset. /// </summary> protected bool m_waitingForObjectAsset; public UuidGatherer(IAssetService assetCache) { m_assetCache = assetCache; } /// <summary> /// Gather all the asset uuids associated with the asset referenced by a given uuid /// </summary> /// /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param> /// <param name="assetType">The type of the asset for the uuid given</param> /// <param name="assetUuids">The assets gathered</param> public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, int> assetUuids) { assetUuids[assetUuid] = 1; if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType) { GetWearableAssetUuids(assetUuid, assetUuids); } else if (AssetType.LSLText == assetType) { GetScriptAssetUuids(assetUuid, assetUuids); } else if (AssetType.Object == assetType) { GetSceneObjectAssetUuids(assetUuid, assetUuids); } } /// <summary> /// Gather all the asset uuids associated with a given object. /// </summary> /// /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// /// <param name="sceneObject">The scene object for which to gather assets</param> /// <param name="assetUuids">The assets gathered</param> public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, int> assetUuids) { // m_log.DebugFormat( // "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID); foreach (SceneObjectPart part in sceneObject.GetParts()) { //m_log.DebugFormat( // "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID); try { Primitive.TextureEntry textureEntry = part.Shape.Textures; // Get the prim's default texture. This will be used for faces which don't have their own texture assetUuids[textureEntry.DefaultTexture.TextureID] = 1; // XXX: Not a great way to iterate through face textures, but there's no // other method available to tell how many faces there actually are //int i = 0; foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures) { if (texture != null) { //m_log.DebugFormat("[ARCHIVER]: Got face {0}", i++); assetUuids[texture.TextureID] = 1; } } // If the prim is a sculpt then preserve this information too if (part.Shape.SculptTexture != UUID.Zero) assetUuids[part.Shape.SculptTexture] = 1; TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone(); // Now analyze this prim's inventory items to preserve all the uuids that they reference foreach (TaskInventoryItem tii in taskDictionary.Values) { //m_log.DebugFormat("[ARCHIVER]: Analysing item asset type {0}", tii.Type); if (!assetUuids.ContainsKey(tii.AssetID)) GatherAssetUuids(tii.AssetID, (AssetType)tii.Type, assetUuids); } } catch (Exception e) { m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e); m_log.DebugFormat( "[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)", part.Shape.TextureEntry.Length); } } } /// <summary> /// The callback made when we request the asset for an object from the asset service. /// </summary> protected void AssetReceived(string id, Object sender, AssetBase asset) { lock (this) { m_requestedObjectAsset = asset; m_waitingForObjectAsset = false; Monitor.Pulse(this); } } /// <summary> /// Get an asset synchronously, potentially using an asynchronous callback. If the /// asynchronous callback is used, we will wait for it to complete. /// </summary> /// <param name="uuid"></param> /// <returns></returns> protected virtual AssetBase GetAsset(UUID uuid) { m_waitingForObjectAsset = true; m_assetCache.Get(uuid.ToString(), this, AssetReceived); // The asset cache callback can either // // 1. Complete on the same thread (if the asset is already in the cache) or // 2. Come in via a different thread (if we need to go fetch it). // // The code below handles both these alternatives. lock (this) { if (m_waitingForObjectAsset) { Monitor.Wait(this); m_waitingForObjectAsset = false; } } return m_requestedObjectAsset; } /// <summary> /// Record the asset uuids embedded within the given script. /// </summary> /// <param name="scriptUuid"></param> /// <param name="assetUuids">Dictionary in which to record the references</param> protected void GetScriptAssetUuids(UUID scriptUuid, IDictionary<UUID, int> assetUuids) { AssetBase scriptAsset = GetAsset(scriptUuid); if (null != scriptAsset) { string script = Utils.BytesToString(scriptAsset.Data); //m_log.DebugFormat("[ARCHIVER]: Script {0}", script); MatchCollection uuidMatches = Util.UUIDPattern.Matches(script); //m_log.DebugFormat("[ARCHIVER]: Found {0} matches in script", uuidMatches.Count); foreach (Match uuidMatch in uuidMatches) { UUID uuid = new UUID(uuidMatch.Value); //m_log.DebugFormat("[ARCHIVER]: Recording {0} in script", uuid); assetUuids[uuid] = 1; } } } /// <summary> /// Record the uuids referenced by the given wearable asset /// </summary> /// <param name="wearableAssetUuid"></param> /// <param name="assetUuids">Dictionary in which to record the references</param> protected void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, int> assetUuids) { AssetBase assetBase = GetAsset(wearableAssetUuid); if (null != assetBase) { //m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data)); AssetWearable wearableAsset = new AssetBodypart(wearableAssetUuid, assetBase.Data); wearableAsset.Decode(); //m_log.DebugFormat( // "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count); foreach (UUID uuid in wearableAsset.Textures.Values) { //m_log.DebugFormat("[ARCHIVER]: Got bodypart uuid {0}", uuid); assetUuids[uuid] = 1; } } } /// <summary> /// Get all the asset uuids associated with a given object. This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// </summary> /// <param name="sceneObject"></param> /// <param name="assetUuids"></param> protected void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, int> assetUuids) { AssetBase objectAsset = GetAsset(sceneObjectUuid); if (null != objectAsset) { string xml = Utils.BytesToString(objectAsset.Data); SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml); GatherAssetUuids(sog, assetUuids); } } } }
using System; using System.Collections; using System.Text; using System.Diagnostics; using OTFontFile; // OTF2Dot14 using NS_ValCommon; using NS_IDraw; using NS_GMath; using Curve=NS_GMath.I_CurveD; using BCurve=NS_GMath.I_BCurveD; namespace NS_Glyph { public class GErr : ValInfoBasic, I_Drawable { /* * ENUMS */ public enum TypeGErrSeverity { Undef=-1, Low, Middle, High, Fatal // TODO: try to put VAL_UNDEF into Undef } /* * MEMBERS */ protected int indexGlyphOwner=GConsts.IND_UNINITIALIZED; protected GConsts.TypeGlyph typeGlyph; protected string gscope; // glyph scope protected TypeGErrSeverity severity; protected string signCreator=null; // creator of the error /* * PROPERTIES */ public TypeGErrSeverity Severity { get { return this.severity; } set { this.severity=value; } } public GConsts.TypeGlyph TypeGlyph { get { return this.typeGlyph; } set { this.typeGlyph=value; } } public string GetScope { get { return this.gscope; } } public int IndexGlyphOwner { get { return this.indexGlyphOwner; } } internal string SignCreator { get { return this.signCreator; } set { this.signCreator=value; } } public string StrTypeName { get { return "("+this.TypeBasic.ToString()[0]+"): "+ this.ValueName+" "; } } public string StrTypeNameSign { get { return this.StrTypeName+this.SignCreator+" "; } } override public string ValueUser { get { return ("Glyph index "+this.indexGlyphOwner); } set { this.m_StringValueUser=value; } } /* * METHODS */ protected void SetScope(params GScope.TypeGScope[] scopes) { this.gscope=GScope.StrGScope(scopes); } override public bool IsSame(object obj) { return false; } public bool ClearDestroy() // return value indicatetes whether the error was cleared { this.ClearFunc(); this.indexGlyphOwner=GConsts.IND_DESTROYED; base.Name = "GERR_UNINITIALIZED"; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; return true; } protected virtual void ClearFunc() { } public virtual string WriteUserFriendly() { StringBuilder sb=new StringBuilder(""); sb.Append(this.IndexGlyphOwner+": "); if (this.ValueName!=null) { sb.Append(this.ValueName); } return sb.ToString(); } override public string ToString() { string strIndex=this.IndexGlyphOwner.ToString(); strIndex=strIndex.PadLeft(7); return strIndex; } public virtual string WriteSpecific() { return ""; } public string Write() { StringBuilder sb=new StringBuilder("\r\n"); sb.Append("Validation Info Type : "); sb.Append(Enum.GetName(typeof(ValInfoBasic.ValInfoType),this.TypeBasic)); sb.Append("\r\n"); sb.Append("Index Glyph : "); sb.Append(this.IndexGlyphOwner); sb.Append("\r\n"); sb.Append("Type Glyph : "); sb.Append(this.typeGlyph); sb.Append("\r\n"); sb.Append("Error Type : "); sb.Append(this.GetType()); sb.Append("\r\n"); sb.Append("Error Scopes : "); sb.Append(this.GetScope); sb.Append("\r\n"); sb.Append("Error Severity :"); sb.Append(Enum.GetName(typeof(GErr.TypeGErrSeverity),this.Severity)); sb.Append("\r\n"); if (this.Name!=null) { sb.Append("Name : "); sb.Append(this.Name); sb.Append("\r\n"); } if (this.ValueName!=null) { sb.Append("Value Name : "); sb.Append(this.ValueName); sb.Append("\r\n"); } if (this.ValueUser!=null) { sb.Append("Details : "); sb.Append(this.ValueUser); sb.Append("\r\n"); } if ((this.m_StringValueUser!=null)&&(this.m_StringValueUser!="")) { sb.Append("Value User : "); sb.Append(this.m_StringValueUser); sb.Append("\r\n"); } /* if (this.ValueUser!=null) { sb.Append("Value User : "); sb.Append(this.ValueUser); sb.Append("\r\n"); } */ if (this.TagPrincipal!=null) { sb.Append("Tag Principal : "); sb.Append((string)(this.TagPrincipal)); sb.Append("\r\n"); } /* if (this.TagRelated!=null) { sb.Append("TagRelated : "); sb.Append((string)(this.TagRelated)); sb.Append("\r\n"); } */ sb.Append("Signature of Creator : "); sb.Append(this.signCreator); sb.Append("\r\n"); sb.Append(this.WriteSpecific()); sb.Append("\r\n"); return sb.ToString(); } public virtual bool Read(string str) { return true; } /* * METHODS: I_DRAWABLE */ public virtual void Draw(I_Draw i_draw, DrawParam dp) { throw new ExceptionGlyph("GErr","Draw","Pure virtual function"); } //===================== search utilities =========== // PARAMETERS: // indexGlyph: IND_ANY - any index, including IND_INVALID & IND_ALL // otherwise - exact match // scope: SEARCH_ANY_ - any scope, including UNDEF_ // simple scope or UNDEF_ - exact match // complex scope - indicates whether gerrsum // contains specified error in // at least ONE of SUBSCOPES internal class DICWrap_HasErrorType { int indexGlyph; GScope.TypeGScope scope; System.Type typeGErr; public DICWrap_HasErrorType(int indexGlyph, GScope.TypeGScope scope, System.Type typeGErr) { this.indexGlyph=indexGlyph; this.scope=scope; this.typeGErr=typeGErr; } public bool DICFunc(GErr gerr) { return gerr.HasErrorType(this.indexGlyph,this.scope,this.typeGErr); } DICond DIC { get { return (Delegate.CreateDelegate(typeof(DICond),this,"DICFunc")) as DICond; } } } public virtual bool HasErrorType(int indexGlyph, GScope.TypeGScope scope, System.Type typeGErr) { if ((indexGlyph!=GConsts.IND_ANY)&&(indexGlyph!=this.IndexGlyphOwner)) return false; if (!GScope.GScInterfer(scope, this.GetScope)) return false; // traverse GErr hierarchy (if any) Type type=this.GetType(); do { if (type==typeGErr) return true; type=type.BaseType; } while (type!=typeof(GErr)); return false; } public bool HasSeverity(int indexGlyph, GScope.TypeGScope scope, GErr.TypeGErrSeverity severity) { if ((indexGlyph!=GConsts.IND_ANY)&&(indexGlyph!=this.IndexGlyphOwner)) return false; if (!GScope.GScInterfer(scope, this.GetScope)) return false; return (severity==this.Severity); } /* static public bool DICFunc_HasTypeExact(ValInfoBasic info, Type typeGErr) { GErr gerr=info as GErr; if (gerr==null) return false; return (gerr is typeGErr); } */ static public bool DICFunc_HasSeverity(ValInfoBasic info, GErr.TypeGErrSeverity severity) { GErr gerr=info as GErr; if (gerr==null) return false; // has NO ANY severity return (gerr.severity==severity); } } public class DIWrapperSource { int indGlyphOwner; GConsts.TypeGlyph typeGlyph; GScope.TypeGScope scope; public DIWrapperSource(int indGlyphOwner, GConsts.TypeGlyph typeGlyph, GScope.TypeGScope scope) { this.indGlyphOwner=indGlyphOwner; this.typeGlyph=typeGlyph; this.scope=scope; } public GErr DIWFunc(ValInfoBasic info) { return new GErrSource(info,this.indGlyphOwner,this.typeGlyph,this.scope); } public static implicit operator DIWrapper(DIWrapperSource diwSource) { return (Delegate.CreateDelegate(typeof(DIWrapper),diwSource,"DIWFunc") as DIWrapper); } } /*================================================================== * * * DERIVED CLASSES * * ==================================================================*/ /*=================================================================== * * GErrApplication * *==================================================================*/ abstract public class GErrApplication : GErr { /* * MEANING: the error is reported in case of an * UNHANDELED EXCEPTION * (unspecified failure of the application) * */ protected string strException; protected GErrApplication() { } public GErrApplication(int indGlyph, GConsts.TypeGlyph typeGlyph, Exception exception) { // ValInfoBasic base.TypeBasic = ValInfoType.AppError; base.Name = "GERR_APPLICATION"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner =indGlyph; base.severity = GErr.TypeGErrSeverity.High; base.SetScope(GScope.TypeGScope._UNDEF_); base.typeGlyph=typeGlyph; // this this.strException=this.ExceptionToString(exception); GErrSign.Sign(this,DefsGV.TypeGV.Invalid,this.indexGlyphOwner); } virtual protected string ExceptionToString(Exception exception) { try { if (exception==null) { return ""; } else if (exception.InnerException!=null) { string str="Exception: "+exception.InnerException.Message; if (exception.InnerException.StackTrace!=null) str+=exception.InnerException.StackTrace; return str; } else { string str="Exception: "+exception.Message; if (exception.StackTrace!=null) str+=exception.StackTrace; return str; } } catch (Exception) { return "Unable to write the exception"; } } protected override void ClearFunc() { this.strException=null; } public override string WriteSpecific() { return this.strException; } public override void Draw(I_Draw i_draw, DrawParam dp) { } } public class GErrValidation : GErrApplication { // members private DefsGV.TypeGV typeGV; private StatusGV.TypeStatusExec statusExec; // properties internal DefsGV.TypeGV TypeGV { get { return this.typeGV; } } internal StatusGV.TypeStatusExec StatusExec { get { return this.statusExec; } } // constructors private GErrValidation() { } public GErrValidation(int indGlyph, GConsts.TypeGlyph typeGlyph, DefsGV.TypeGV typeGV, StatusGV.TypeStatusExec statusExec, Exception exception) : base(indGlyph,typeGlyph,exception) { this.typeGV=typeGV; this.statusExec=statusExec; switch (statusExec) { case StatusGV.TypeStatusExec.Aborted: base.m_Type=ValInfoBasic.ValInfoType.AppError; base.Name="GERR_VAL_ABORTED"; base.Severity=GErr.TypeGErrSeverity.High; break; case StatusGV.TypeStatusExec.UnableToExec: base.m_Type=ValInfoBasic.ValInfoType.AppError; base.Name="GERR_VAL_UNABLE_TO_PERFORM_TEST"; base.Severity=GErr.TypeGErrSeverity.Low; break; default: // should not occur break; } GErrSign.Sign(this,this.typeGV,this.indexGlyphOwner); } // methods public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Validation: "+this.typeGV+" \r\n"); sb.Append("Status Exec: "+this.statusExec+" \r\n"); sb.Append(base.WriteSpecific()); return sb.ToString(); } override public string ValueUser { get { StringBuilder sb=new StringBuilder(base.ValueUser); sb.Append(" Test: "+this.typeGV+" "); sb.Append(base.WriteSpecific()); return sb.ToString(); } } } /*================================================================== * * GErrSource * *=================================================================*/ public class GErrSource : GErr { /* * CONSTRUCTOR */ public GErrSource(ValInfoBasic info, int indGlyphOwner, GConsts.TypeGlyph typeGlyph, GScope.TypeGScope scope) { // ValInfoBasic base.TypeBasic = info.TypeBasic; base.Name = info.Name; base.ValueUser = info.ValueUser; base.NameFileErrs = info.NameFileErrs; base.NameAsmFileErrs = info.NameAsmFileErrs; base.TagPrincipal = info.TagPrincipal; // GErr base.indexGlyphOwner=indGlyphOwner; base.typeGlyph=typeGlyph; if (info.TypeBasic==ValInfoBasic.ValInfoType.Error) { base.severity=GErr.TypeGErrSeverity.Fatal; } else if (info.TypeBasic==ValInfoBasic.ValInfoType.Warning) { base.severity=GErr.TypeGErrSeverity.Low; } else { base.severity=GErr.TypeGErrSeverity.Undef; } base.SetScope(scope); } /* * METHODS: I_DRAWABLE */ override public void Draw(I_Draw i_draw, DrawParam dp) { } /* * METHODS: IsSame */ override public bool IsSame(object obj) { ValInfoBasic info=new ValInfoBasic(this); return info.IsSame(obj); } } /*================================================================ * GERR: Bbox *==============================================================*/ public class GErrBBox : GErr { // is reported when the bounding box given in GLYF table // differs from the bounding box computed from the // CONTROL POINTS of the outline // members private BoxD bboxCP; private BoxD bboxInit; private GErrBBox() { } public GErrBBox(int indGlyph, GConsts.TypeGlyph typeGlyph, BoxD bboxInit, BoxD bboxCP) { // ValInfoBasic base.TypeBasic = ValInfoType.Error; base.Name = "GERR_BBOX"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner =indGlyph; base.severity = GErr.TypeGErrSeverity.Middle; base.SetScope(GScope.TypeGScope._GGB_,GScope.TypeGScope._GGO_); base.typeGlyph=typeGlyph; // this this.bboxInit=new BoxD(bboxInit); this.bboxCP=new BoxD(bboxCP); } protected override void ClearFunc() { this.bboxInit=null; this.bboxCP=null; } override public string ValueUser { get { int devMax=(int)Math.Round(this.bboxInit.DeviationMax(this.bboxCP)); StringBuilder sb=new StringBuilder(base.ValueUser); string strTypeGlyph=this.typeGlyph.ToString().PadRight(10,' '); sb.Append(", "+strTypeGlyph); sb.Append(" Maximal deviation="+devMax+"(FU)"); return sb.ToString(); } } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("BBox Init :"); sb.Append(" xmin="+this.bboxInit.VecMin.X); sb.Append(" ymin="+this.bboxInit.VecMin.Y); sb.Append(" xmax="+this.bboxInit.VecMax.X); sb.Append(" ymax="+this.bboxInit.VecMax.Y); sb.Append(" \r\n"); sb.Append("BBox for the Control Points :"); sb.Append(" xmin="+this.bboxCP.VecMin.X); sb.Append(" ymin="+this.bboxCP.VecMin.Y); sb.Append(" xmax="+this.bboxCP.VecMax.X); sb.Append(" ymax="+this.bboxCP.VecMax.Y); sb.Append(" \r\n"); return sb.ToString(); } /* * METHODS: I_DRAWABLE */ override public void Draw(I_Draw i_draw, DrawParam dp) { if (((object)this.bboxInit==null)||((object)this.bboxCP==null)) return; DrawParam dpBoxInit=new DrawParam("Red",1); this.bboxInit.Draw(i_draw,dpBoxInit); DrawParam dpBoxCP=new DrawParam("Cyan",1); this.bboxCP.Draw(i_draw,dpBoxCP); } } /*================================================================ * GERR: Extreme *==============================================================*/ public class GErrExtremeNotOnCurve : GErr { // members private BoxD bboxCP; private BoxD bboxOutl; private GErrExtremeNotOnCurve() { } public GErrExtremeNotOnCurve(int indGlyph, GConsts.TypeGlyph typeGlyph, BoxD bboxCP, BoxD bboxOutl) { // ValInfoBasic base.TypeBasic = ValInfoType.Warning; base.Name = "GERR_EXTEREME_NOT_ON_CURVE"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner =indGlyph; base.severity = GErr.TypeGErrSeverity.Middle; base.SetScope(GScope.TypeGScope._GGB_,GScope.TypeGScope._GGO_); base.typeGlyph=typeGlyph; // this this.bboxCP=new BoxD(bboxCP); this.bboxOutl=new BoxD(bboxOutl); } protected override void ClearFunc() { this.bboxCP=null; this.bboxOutl=null; } /* override public string ValueUser { get { } } */ public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); double xMinCP=this.bboxCP.VecMin.X; double yMinCP=this.bboxCP.VecMin.Y; double xMaxCP=this.bboxCP.VecMax.X; double yMaxCP=this.bboxCP.VecMax.Y; double xMinOutl=this.bboxOutl.VecMin.X; double yMinOutl=this.bboxOutl.VecMin.Y; double xMaxOutl=this.bboxOutl.VecMax.X; double yMaxOutl=this.bboxOutl.VecMax.Y; if (xMinCP<xMinOutl) { sb.Append(" Left: by control points="+xMinCP+" by outline="+xMinOutl); sb.Append(" \r\n"); } if (yMinCP<yMinOutl) { sb.Append(" Bottom: by control points="+yMinCP+" by outline="+yMinOutl); sb.Append(" \r\n"); } if (xMaxCP>xMaxOutl) { sb.Append(" Right: by control points="+xMaxCP+" by outline="+xMaxOutl); sb.Append(" \r\n"); } if (yMaxCP>yMaxOutl) { sb.Append(" Top: by control points="+yMaxCP+" by outline="+yMaxOutl); sb.Append(" \r\n"); } return sb.ToString(); } /* * METHODS: I_DRAWABLE */ override public void Draw(I_Draw i_draw, DrawParam dp) { if (((object)this.bboxCP==null)||((object)this.bboxOutl==null)) return; double xMinCP=this.bboxCP.VecMin.X; double yMinCP=this.bboxCP.VecMin.Y; double xMaxCP=this.bboxCP.VecMax.X; double yMaxCP=this.bboxCP.VecMax.Y; double xMinOutl=this.bboxOutl.VecMin.X; double yMinOutl=this.bboxOutl.VecMin.Y; double xMaxOutl=this.bboxOutl.VecMax.X; double yMaxOutl=this.bboxOutl.VecMax.Y; SegD seg; DrawParamCurve dpCurve; if (xMinCP<xMinOutl) { seg=new SegD(new VecD(xMinOutl,yMinCP), new VecD(xMinOutl,yMaxCP)); dpCurve=new DrawParamCurve("Orange",1.5F,false,null); seg.Draw(i_draw,dpCurve); } if (yMinCP<yMinOutl) { seg=new SegD(new VecD(xMinCP,yMinOutl), new VecD(xMaxCP,yMinOutl)); dpCurve=new DrawParamCurve("Orange",1.5F,false,null); seg.Draw(i_draw,dpCurve); } if (xMaxCP>xMaxOutl) { seg=new SegD(new VecD(xMaxOutl,yMinCP), new VecD(xMaxOutl,yMaxCP)); dpCurve=new DrawParamCurve("Orange",1.5F,false,null); seg.Draw(i_draw,dpCurve); } if (yMaxCP>yMaxOutl) { seg=new SegD(new VecD(xMinCP,yMaxOutl), new VecD(xMaxCP,yMaxOutl)); dpCurve=new DrawParamCurve("Orange",1.5F,false,null); seg.Draw(i_draw,dpCurve); } } } /*================================================================ * GERR: ContMisor *==============================================================*/ public class GErrContMisor : GErr { // members private int[] indsKnotStart; // properties public int NumContMisor { get { return this.indsKnotStart.Length; } } // constructors private GErrContMisor() { } public GErrContMisor(int indGlyph, int[] indsKnotStart) { // ValInfoBasic base.TypeBasic = ValInfoType.Error; base.Name = "GERR_CONT_MISOR"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyph; base.typeGlyph=GConsts.TypeGlyph.Simple; base.severity = GErr.TypeGErrSeverity.High; base.SetScope(GScope.TypeGScope._GGO_); // this int numCont=indsKnotStart.Length; this.indsKnotStart=new int[numCont]; for (int iCont=0; iCont<numCont; iCont++) { this.indsKnotStart[iCont]=indsKnotStart[iCont]; } } /* * METHODS */ public int IndKnotStart(int poz) { if ((poz<0)||(poz>=this.NumContMisor)) return GConsts.IND_UNDEFINED; return ((int)this.indsKnotStart[poz]); } protected override void ClearFunc() { this.indsKnotStart=null; } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Indices Knot Start : "); for (int poz=0; poz<this.NumContMisor; poz++) { sb.Append(this.indsKnotStart[poz]+" "); } sb.Append(" \r\n"); return sb.ToString(); } /* * METHODS: I_DRAWABLE */ override public void Draw(I_Draw i_draw, DrawParam dp) { DrawParamGErr dpGErr=dp as DrawParamGErr; if (dpGErr==null) return; foreach (int indKnotStart in this.indsKnotStart) { Contour cont=dpGErr.G.Outl.ContByIndKnot(indKnotStart); DrawParamCurve dpCurve=new DrawParamCurve("Magenta",1.5F,false,null); DrawParamContour dpCont=new DrawParamContour(dpCurve,null); cont.Draw(i_draw, dpCont); } } } /*================================================================ * GERR: ContWrap *==============================================================*/ public class GErrContWrap : GErr { // members private int[] indsKnotStart; // properties // constructors private GErrContWrap() { } public GErrContWrap(int indGlyphOwner, int[] indsKnotStart) { // ValInfoBasic base.TypeBasic = ValInfoType.Error; base.Name = "GERR_CONT_WRAP"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyphOwner; base.typeGlyph = GConsts.TypeGlyph.Simple; base.severity = GErr.TypeGErrSeverity.High; base.SetScope(GScope.TypeGScope._GGO_); // this int numCont=indsKnotStart.Length; this.indsKnotStart=new int[numCont]; for (int iCont=0; iCont<numCont; iCont++) { this.indsKnotStart[iCont]=indsKnotStart[iCont]; } } protected override void ClearFunc() { this.indsKnotStart=null; } override public void Draw(I_Draw i_Draw, DrawParam dp) { DrawParamGErr dpGErr=dp as DrawParamGErr; if (dpGErr==null) return; int numCont=this.indsKnotStart.Length; for (int iCont=0; iCont<numCont; iCont++) { Contour cont=dpGErr.G.Outl.ContByIndKnot(indsKnotStart[iCont]); DrawParamCurve dpCurve=new DrawParamCurve("Pink",2.0F,false,null); DrawParamContour dpCont=new DrawParamContour(dpCurve,null); cont.Draw(i_Draw, dpCont); } } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); int numCont=this.indsKnotStart.Length; sb.Append("Number of wrapped contours: "+numCont+" \r\n"); sb.Append("Starting knots of contours: "); for (int iCont=0; iCont<numCont; iCont++) { sb.Append(this.indsKnotStart[iCont]+" "); } sb.Append(" \r\n"); return sb.ToString(); } } /*================================================================ * GERR: ContWrap *==============================================================*/ public class GErrContDegen : GErr { // members private int[] indsKnotStart; // properties // constructors private GErrContDegen() { } public GErrContDegen(int indGlyphOwner, int[] indsKnotStart) { // ValInfoBasic base.TypeBasic = ValInfoType.Warning; base.Name = "GERR_CONT_DEGEN"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyphOwner; base.typeGlyph = GConsts.TypeGlyph.Simple; base.severity = GErr.TypeGErrSeverity.Low; base.SetScope(GScope.TypeGScope._GGO_); // this int numCont=indsKnotStart.Length; this.indsKnotStart=new int[numCont]; for (int iCont=0; iCont<numCont; iCont++) { this.indsKnotStart[iCont]=indsKnotStart[iCont]; } } protected override void ClearFunc() { this.indsKnotStart=null; } override public void Draw(I_Draw i_Draw, DrawParam dp) { DrawParamGErr dpGErr=dp as DrawParamGErr; if (dpGErr==null) return; int numCont=this.indsKnotStart.Length; for (int iCont=0; iCont<numCont; iCont++) { Contour cont=dpGErr.G.Outl.ContByIndKnot(indsKnotStart[iCont]); Knot knot=cont.KnotByPoz(0); i_Draw.DrawPnt(knot.Val.X,knot.Val.Y,4.5F,"Green",1F,false); } } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); int numCont=this.indsKnotStart.Length; sb.Append("Number of degenerated contours: "+numCont+" \r\n"); sb.Append("Starting knots of contours: "); for (int iCont=0; iCont<numCont; iCont++) { sb.Append(this.indsKnotStart[iCont]+" "); } sb.Append(" \r\n"); return sb.ToString(); } } /*================================================================ * GERR: ContDupl *==============================================================*/ public class GErrContDupl : GErr { // members private ListPairInt pairsIndKnotStart; // properties // constructors private GErrContDupl() { } public GErrContDupl(int indGlyphOwner, ListPairInt pairsIndKnotStart) { if (pairsIndKnotStart==null) { throw new ExceptionGlyph("GErrContDupl","GErrContDupl","Null argument"); } // ValInfoBasic base.TypeBasic = ValInfoType.Error; base.Name = "GERR_CONT_DUPL"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyphOwner; base.typeGlyph = GConsts.TypeGlyph.Simple; base.severity = GErr.TypeGErrSeverity.High; base.SetScope(GScope.TypeGScope._GGO_); // this this.pairsIndKnotStart=pairsIndKnotStart; } protected override void ClearFunc() { this.pairsIndKnotStart.Clear(); this.pairsIndKnotStart=null; } override public void Draw(I_Draw i_Draw, DrawParam dp) { DrawParamGErr dpGErr=dp as DrawParamGErr; if (dpGErr==null) return; foreach (PairInt pair in this.pairsIndKnotStart) { Contour cont=dpGErr.G.Outl.ContByIndKnot(pair[0]); DrawParamCurve dpCurve=new DrawParamCurve("Orange",2.0F,false,null); DrawParamContour dpCont=new DrawParamContour(dpCurve,null); cont.Draw(i_Draw, dpCont); } } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Number of duplicated contours: "+this.pairsIndKnotStart.Count+" \r\n"); sb.Append("Starting knots of contours: "); foreach (PairInt pair in this.pairsIndKnotStart) { sb.Append("("+pair[0]+","+pair[1]+") "); } sb.Append(" \r\n"); return sb.ToString(); } } /*================================================================ * GERR: ContInters *==============================================================*/ public class GErrContInters : GErr { /* * IMPORTANT: DO NOT write property that gains access to * knot (in parameter description) in elements of * linters */ // members private ListInfoInters linters; // properties // constructors private GErrContInters() { } public GErrContInters(int indGlyphOwner, ListInfoInters linters) { // ValInfoBasic base.TypeBasic = ValInfoType.Error; base.Name = "GERR_CONT_INTERS"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyphOwner; base.typeGlyph = GConsts.TypeGlyph.Simple; base.severity = GErr.TypeGErrSeverity.High; base.SetScope(GScope.TypeGScope._GGO_); // this this.linters = linters; } // methods override public string ToString() { string strIndex=this.IndexGlyphOwner.ToString(); string strRes; if (this.linters==null) { throw new ExceptionGlyph("GErrContInters","ToString",null); } if (this.linters.ContainsD1) { strRes="D1 "+strIndex.PadLeft(6); } else if (this.linters.ContainsBezSI) { strRes="Bez "+strIndex.PadLeft(5); } else { strRes=base.ToString(); } return strRes; } protected override void ClearFunc() { this.linters.ClearDestroy(); this.linters=null; } override public void Draw(I_Draw i_Draw, DrawParam dp) { DrawParamGErr dpGErr=dp as DrawParamGErr; if (dpGErr==null) return; foreach (InfoInters inters in this.linters) { switch(inters.GetType().ToString()) { case "NS_GMath.IntersD0": IntersD0 intersD0=inters as IntersD0; double x=intersD0.PntInters.X; double y=intersD0.PntInters.Y; i_Draw.DrawPnt(x,y,1.5F,"Red",1,true); break; case "NS_GMath.IntersD1": IntersD1 intersD1=inters as IntersD1; Curve curveInters=intersD1.CurveInters; DrawParamCurve dpCurve; if (!intersD1.IsBezSI) { dpCurve=new DrawParamCurve("Red",1.5F,false,null); } else { dpCurve=new DrawParamCurve("DarkMagenta",5.0F,false,null); } bool toDrawCurves=false;//(curveInters.BBox.Diag<3.0); try { curveInters.Draw(i_Draw, dpCurve); } catch (System.Exception) { toDrawCurves=true; } if (toDrawCurves) { CParam cparamInA=intersD1.IpiIn.Par(0) as CParam; BCurve curve=dpGErr.G.Outl.CurveByIndKnot(cparamInA.IndKnot); dpCurve=new DrawParamCurve("Red",1.0F,false,null); curve.Draw(i_Draw, dpCurve); CParam cparamInB=intersD1.IpiIn.Par(1) as CParam; if (cparamInB!=null) { curve=dpGErr.G.Outl.CurveByIndKnot(cparamInA.IndKnot); curve.Draw(i_Draw, dpCurve); } } break; default: break; } } } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); int numInters=this.linters.Count; sb.Append("Number of intersections: "+numInters+" \r\n"); sb.Append("Intersections: \r\n"); foreach (InfoInters inters in this.linters) { if (inters.Dim==InfoInters.TypeDim.Dim0) { IntersD0 intersD0=inters as IntersD0; int indKnot0=(intersD0.Ipi.Par(0) as CParam).IndKnot; int indKnot1=(intersD0.Ipi.Par(1) as CParam).IndKnot; sb.Append("D0,knots: ("+indKnot0+","+indKnot1+") \r\n"); } if (inters.Dim==InfoInters.TypeDim.Dim1) { IntersD1 intersD1=inters as IntersD1; if (intersD1.IsBezSI) { int indKnot=(intersD1.IpiIn.Par(0) as CParam).IndKnot; sb.Append("BezSI,knot: "+indKnot+ "\r\n"); } else { int indKnot0=(intersD1.IpiIn.Par(0) as CParam).IndKnot; int indKnot1=(intersD1.IpiIn.Par(1) as CParam).IndKnot; sb.Append("D1,knots: ("+indKnot0+","+indKnot1+") \r\n"); } } } return sb.ToString(); } } public class GErrKnotDupl : GErr { // members private ListPairInt infosKnotDupl; // properties // constructors private GErrKnotDupl() { } public GErrKnotDupl(int indGlyphOwner, ListPairInt infosKnotDupl) { // ValInfoBasic base.TypeBasic = ValInfoType.Warning; base.Name = "GERR_KNOT_DUPL"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyphOwner; base.typeGlyph = GConsts.TypeGlyph.Simple; base.severity = GErr.TypeGErrSeverity.Middle; base.SetScope(GScope.TypeGScope._GGO_); // this this.infosKnotDupl = infosKnotDupl; } protected override void ClearFunc() { this.infosKnotDupl.Clear(); this.infosKnotDupl=null; } override public void Draw(I_Draw i_Draw, DrawParam dp) { DrawParamGErr dpGErr=dp as DrawParamGErr; if (dpGErr==null) return; foreach (PairInt infoKnotDupl in this.infosKnotDupl) { VecD vec=dpGErr.G.Outl.KnotByInd(infoKnotDupl[0]).Val; i_Draw.DrawPnt(vec.X,vec.Y,3.0F,"Green",0.5F,false); } } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Number of duplicated knots: "+this.infosKnotDupl.Count+"\r\n"); foreach (PairInt infoKnotDupl in this.infosKnotDupl) { sb.Append(" Knot: "+infoKnotDupl[0]+" multiplicity: "+infoKnotDupl[1]+" \r\n"); } return sb.ToString(); } } /*================================================================ * GERR: COMPOSITE BINDING *==============================================================*/ public class GErrComponent : GErr // gerr composite binding { // members protected int indexGlyphComponent; // properties public int IndexGlyphComponent { get { return this.indexGlyphComponent; } } override public string ValueUser { get { return ("Glyph index "+this.indexGlyphOwner+ ", Component index "+this.indexGlyphComponent); } set { this.m_StringValueUser=value; } } // constructors protected GErrComponent() { } protected GErrComponent(int indGlyphOwner, int indGlyphComponent) { // ValInfoBasic base.TypeBasic = ValInfoType.Error; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyphOwner; base.severity = GErr.TypeGErrSeverity.Fatal; base.SetScope(GScope.TypeGScope._GGC_,GScope.TypeGScope._GGO_); base.typeGlyph=GConsts.TypeGlyph.Composite; // this this.indexGlyphComponent=indGlyphComponent; } // methods protected override void ClearFunc() { this.indexGlyphComponent=GConsts.IND_DESTROYED; } override public void Draw(I_Draw i_Draw, DrawParam dp) { } override public string WriteSpecific() { return ("Index Component: "+this.indexGlyphComponent+" \r\n"); } } public class GErrComponentIndexGlyph : GErrComponent { // constructors private GErrComponentIndexGlyph() { } public GErrComponentIndexGlyph(int indGlyphOwner, int indGlyphComponent) : base(indGlyphOwner, indGlyphComponent) { // ValInfoBasic base.Name = "GERR_COMPONENT_INDEX_GLYPH"; base.TypeBasic = ValInfoType.Warning; // GErr base.severity = GErr.TypeGErrSeverity.Low; } } public class GErrComponentLoadFailure : GErrComponent { // constructors private GErrComponentLoadFailure() { } public GErrComponentLoadFailure(int indGlyphOwner, int indGlyphComponent) : base(indGlyphOwner, indGlyphComponent) { // ValInfoBasic base.Name = "GERR_COMPONENT_LOAD_FAILURE"; } } public class GErrComponentIncorrectShift : GErrComponent { // constructors private GErrComponentIncorrectShift() { } public GErrComponentIncorrectShift(int indGlyphOwner, int indGlyphComponent) : base(indGlyphOwner, indGlyphComponent) { // ValInfoBasic base.Name = "GERR_COMPONENT_INCORRECT_SHIFT"; } } public class GErrComponentIncorrectTransform : GErrComponent { // members OTF2Dot14[,] tr; // constructors private GErrComponentIncorrectTransform() { } public GErrComponentIncorrectTransform(int indGlyphOwner, int indGlyphComponent, OTF2Dot14[,] tr) : base(indGlyphOwner, indGlyphComponent) { // ValInfoBasic base.Name = "GERR_COMPONENT_INCORRECT_TRANSFORM"; // this if ((tr.GetLength(0)!=2)||(tr.GetLength(1)!=2)) { throw new ExceptionGlyph("GErrComponentIncorrectTransform","GErrComponentIncorrectTransform",null); } this.tr=new OTF2Dot14[2,2]; for (int i=0; i<2; i++) for (int j=0; j<2; j++) this.tr[i,j]=tr[i,j]; } override public string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Transform: \r\n"); for (int i=0; i<2; i++) for (int j=0; j<2; j++) { sb.Append("("+i+","+j+") "+(double)this.tr[i,j]+" \r\n"); } return sb.ToString(); } } public class GErrComponentCircularDependency : GErrComponent { // members int[] pathCompBind; // constructors private GErrComponentCircularDependency() { } public GErrComponentCircularDependency(int indGlyphOwner, int indGlyphComponent, params int[] pathCompBind) : base(indGlyphOwner, indGlyphComponent) { // ValInfoBasic base.Name = "GERR_COMPONENT_CIRCULAR_DEPENDENCY"; // this if (pathCompBind==null) { throw new ExceptionGlyph("GErrComponentCircularDependency","GErrComponentCircularDependency","Null argument"); } int numGlyph=pathCompBind.Length; this.pathCompBind=new int[numGlyph]; for (int iGlyph=0; iGlyph<numGlyph; iGlyph++) { this.pathCompBind[iGlyph]=pathCompBind[iGlyph]; } } override public string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Glyphs sequence in composite binding: \r\n"); for (int iGlyph=0; iGlyph<this.pathCompBind.Length; iGlyph++) { sb.Append(iGlyph+", "); } sb.Append(" \r\n"); return sb.ToString(); } } public class GErrComponentEmpty : GErrComponent { // constructors private GErrComponentEmpty() { } public GErrComponentEmpty(int indGlyphOwner, int indGlyphComponent) : base(indGlyphOwner, indGlyphComponent) { // ValInfoBasic base.Name = "GERR_COMPONENT_EMPTY"; } } public class GErrComponentIndexKnot : GErrComponent { // members int indexKnot; bool isKnotGlyph; // properties int IndexKnot { get { return this.indexKnot; } } bool IsKnotGlyph { get { return this.isKnotGlyph; } } // constructors private GErrComponentIndexKnot() { } public GErrComponentIndexKnot(int indGlyphOwner, int indGlyphComponent, int indKnot, bool isKnotGlyph) : base(indGlyphOwner, indGlyphComponent) { // ValInfoBasic base.Name = "GERR_COMPONENT_INDEX_KNOT"; // this this.indexKnot=indKnot; this.isKnotGlyph=isKnotGlyph; } override public string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Glyph Index of Component"+this.indexGlyphComponent+"\r\n"); if (this.isKnotGlyph) { sb.Append("Index of knot in Glyph: "+this.indexKnot+" \r\n"); } else { sb.Append("Index of knot in Component: "+this.indexKnot+" \r\n"); } return sb.ToString(); } } /*================================================================ * GERR: ComponentInters *==============================================================*/ public class GErrComponentInters : GErr { // members private ArrayList arrLinters; // properties // constructors private GErrComponentInters() { } public GErrComponentInters(int indGlyphOwner, ArrayList arrLinters) { // ValInfoBasic base.TypeBasic = ValInfoType.Warning; base.Name = "GERR_COMPONENT_INTERS"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyphOwner; base.typeGlyph = GConsts.TypeGlyph.Composite; base.severity = GErr.TypeGErrSeverity.Low; base.SetScope(GScope.TypeGScope._GGO_); // this this.arrLinters = arrLinters; } protected override void ClearFunc() { for (int iLinters=0; iLinters<this.arrLinters.Count; iLinters++) { ListInfoInters linters=this.arrLinters[iLinters] as ListInfoInters; linters.ClearDestroy(); } this.arrLinters.Clear(); this.arrLinters=null; } override public void Draw(I_Draw i_Draw, DrawParam dp) { DrawParamGErr dpGErr=dp as DrawParamGErr; if (dpGErr==null) return; foreach (ListInfoInters linters in this.arrLinters) { foreach (InfoInters inters in linters) { switch(inters.GetType().ToString()) { case "NS_GMath.IntersD0": IntersD0 intersD0=inters as IntersD0; double x=intersD0.PntInters.X; double y=intersD0.PntInters.Y; i_Draw.DrawPnt(x,y,2.0F,"Red",1,true); break; case "NS_GMath.IntersD1": IntersD1 intersD1=inters as IntersD1; Curve curveInters=intersD1.CurveInters; DrawParamCurve dpCurve=new DrawParamCurve("Red",2.0F,false,null); bool toDrawCurves=(curveInters.BBox.Diag<3.0); try { curveInters.Draw(i_Draw, dpCurve); } catch(System.Exception) { toDrawCurves=true; } if (toDrawCurves) { CParam cparamInA=intersD1.IpiIn.Par(0) as CParam; BCurve curve=dpGErr.G.Outl.CurveByIndKnot(cparamInA.IndKnot); dpCurve=new DrawParamCurve("Red",2.0F,false,null); curve.Draw(i_Draw, dpCurve); CParam cparamInB=intersD1.IpiIn.Par(1) as CParam; if (cparamInB!=null) { curve=dpGErr.G.Outl.CurveByIndKnot(cparamInA.IndKnot); curve.Draw(i_Draw, dpCurve); } } break; default: break; } } } } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Number of pairs of intersecting components: "+this.arrLinters.Count+" \r\n"); foreach (ListInfoInters linters in this.arrLinters) { sb.Append("Indices of intersecting components: ("+ linters.IndGlyphComponent(0)+","+ linters.IndGlyphComponent(1)+") \r\n"); sb.Append("Intersections: \r\n"); foreach (InfoInters inters in linters) { if (inters.Dim==InfoInters.TypeDim.Dim0) { IntersD0 intersD0=inters as IntersD0; int indKnot0=(intersD0.Ipi.Par(0) as CParam).IndKnot; int indKnot1=(intersD0.Ipi.Par(1) as CParam).IndKnot; sb.Append("D0,knots: ("+indKnot0+","+indKnot1+") \r\n"); } if (inters.Dim==InfoInters.TypeDim.Dim1) { IntersD1 intersD1=inters as IntersD1; if (intersD1.IsBezSI) { int indKnot=(intersD1.IpiIn.Par(0) as CParam).IndKnot; sb.Append("BezSI,knot: "+indKnot+" \r\n"); } else { int indKnot0=(intersD1.IpiIn.Par(0) as CParam).IndKnot; int indKnot1=(intersD1.IpiIn.Par(1) as CParam).IndKnot; sb.Append("D1,knots: ("+indKnot0+","+indKnot1+") \r\n"); } } } } return sb.ToString(); } } /*================================================================ * GERR: ComponentDupl *==============================================================*/ public class GErrComponentDupl : GErr { // members private ListPairInt pairsIndGlyphComponent; // properties // constructors private GErrComponentDupl() { } public GErrComponentDupl(int indGlyphOwner, ListPairInt pairsIndGlyphComponent) { if (pairsIndGlyphComponent==null) { throw new ExceptionGlyph("GErrComponentDupl","GErrComponentDupl","Null argument"); } // ValInfoBasic base.TypeBasic = ValInfoType.Error; base.Name = "GERR_COMPONENT_DUPL"; base.ValueUser = null; base.NameFileErrs = GErrConsts.FILE_RES_GERR_STRINGS; base.NameAsmFileErrs = GErrConsts.ASM_RES_GERR_STRINGS; base.TagPrincipal = "glyf"; // GErr base.indexGlyphOwner = indGlyphOwner; base.typeGlyph = GConsts.TypeGlyph.Composite; base.severity = GErr.TypeGErrSeverity.High; base.SetScope(GScope.TypeGScope._GGO_); // this this.pairsIndGlyphComponent=pairsIndGlyphComponent; } protected override void ClearFunc() { this.pairsIndGlyphComponent.Clear(); this.pairsIndGlyphComponent=null; } override public void Draw(I_Draw i_Draw, DrawParam dp) { DrawParamGErr dpGErr=dp as DrawParamGErr; if (dpGErr==null) return; foreach (PairInt pair in this.pairsIndGlyphComponent) { int indGlyph=pair[0]; Component component=dpGErr.G.Comp.ComponentByIndGlyph(indGlyph); for (int pozCont=component.PozContStart; pozCont<component.PozContStart+component.NumCont; pozCont++) { Contour cont=dpGErr.G.Outl.ContourByPoz(pozCont); DrawParamCurve dpCurve=new DrawParamCurve("Red",2.0F,false,null); DrawParamContour dpCont=new DrawParamContour(dpCurve,null); cont.Draw(i_Draw, dpCont); } } } public override string WriteSpecific() { StringBuilder sb=new StringBuilder(); sb.Append("Number of pairs of duplicated components: "+this.pairsIndGlyphComponent.Count+" \r\n"); sb.Append("Indices of duplicated components: "); foreach (PairInt pair in this.pairsIndGlyphComponent) { sb.Append("("+pair[0]+","+pair[1]+") "); } sb.Append(" \r\n"); return sb.ToString(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ExpressRouteCircuitAuthorizationsOperations operations. /// </summary> internal partial class ExpressRouteCircuitAuthorizationsOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteCircuitAuthorizationsOperations { /// <summary> /// Initializes a new instance of the ExpressRouteCircuitAuthorizationsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ExpressRouteCircuitAuthorizationsOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified authorization from the specified express route /// circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified authorization from the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (authorizationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("authorizationName", authorizationName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName)); _url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates an authorization in the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='authorizationParameters'> /// Parameters supplied to the create or update express route circuit /// authorization operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ExpressRouteCircuitAuthorization> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all authorizations in an express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified authorization from the specified express route /// circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (authorizationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("authorizationName", authorizationName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName)); _url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates an authorization in the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='authorizationParameters'> /// Parameters supplied to the create or update express route circuit /// authorization operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (circuitName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "circuitName"); } if (authorizationName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationName"); } if (authorizationParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("circuitName", circuitName); tracingParameters.Add("authorizationName", authorizationName); tracingParameters.Add("authorizationParameters", authorizationParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{circuitName}", System.Uri.EscapeDataString(circuitName)); _url = _url.Replace("{authorizationName}", System.Uri.EscapeDataString(authorizationName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(authorizationParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(authorizationParameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ExpressRouteCircuitAuthorization>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteCircuitAuthorization>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all authorizations in an express route circuit. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteCircuitAuthorization>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/** * (C) Copyright IBM Corp. 2019, 2020. * * 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. * */ /** * IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-153452 */ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.VisualRecognition.V3.Model; using Newtonsoft.Json; using System; using UnityEngine.Networking; namespace IBM.Watson.VisualRecognition.V3 { [System.Obsolete("On 1 December 2021, Visual Recognition will no longer be available. " + "For more information, see Visual Recognition Deprecation " + "(https://github.com/watson-developer-cloud/unity-sdk/tree/master#visual-recognition-deprecation).")] public partial class VisualRecognitionService : BaseService { private const string defaultServiceName = "visual_recognition"; private const string defaultServiceUrl = "https://api.us-south.visual-recognition.watson.cloud.ibm.com"; #region Version private string version; /// <summary> /// Gets and sets the version of the service. /// Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is /// `2018-03-19`. /// </summary> public string Version { get { return version; } set { version = value; } } #endregion #region DisableSslVerification private bool disableSslVerification = false; /// <summary> /// Gets and sets the option to disable ssl verification /// </summary> public bool DisableSslVerification { get { return disableSslVerification; } set { disableSslVerification = value; } } #endregion /// <summary> /// VisualRecognitionService constructor. /// </summary> /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. /// The current version is `2018-03-19`.</param> public VisualRecognitionService(string version) : this(version, defaultServiceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(defaultServiceName)) {} /// <summary> /// VisualRecognitionService constructor. /// </summary> /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. /// The current version is `2018-03-19`.</param> /// <param name="authenticator">The service authenticator.</param> public VisualRecognitionService(string version, Authenticator authenticator) : this(version, defaultServiceName, authenticator) {} /// <summary> /// VisualRecognitionService constructor. /// </summary> /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. /// The current version is `2018-03-19`.</param> /// <param name="serviceName">The service name to be used when configuring the client instance</param> public VisualRecognitionService(string version, string serviceName) : this(version, serviceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceName)) {} /// <summary> /// VisualRecognitionService constructor. /// </summary> /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. /// The current version is `2018-03-19`.</param> /// <param name="serviceName">The service name to be used when configuring the client instance</param> /// <param name="authenticator">The service authenticator.</param> public VisualRecognitionService(string version, string serviceName, Authenticator authenticator) : base(authenticator, serviceName) { Authenticator = authenticator; if (string.IsNullOrEmpty(version)) { throw new ArgumentNullException("`version` is required"); } else { Version = version; } if (string.IsNullOrEmpty(GetServiceUrl())) { SetServiceUrl(defaultServiceUrl); } } /// <summary> /// Classify images. /// /// Classify images with built-in or custom classifiers. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="imagesFile">An image file (.gif, .jpg, .png, .tif) or .zip file with images. Maximum image size /// is 10 MB. Include no more than 20 images and limit the .zip file to 100 MB. Encode the image and .zip file /// names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters /// non-ASCII characters. /// /// You can also include an image with the **url** parameter. (optional)</param> /// <param name="imagesFilename">The filename for imagesFile. (optional)</param> /// <param name="imagesFileContentType">The content type of imagesFile. (optional)</param> /// <param name="url">The URL of an image (.gif, .jpg, .png, .tif) to analyze. The minimum recommended pixel /// density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224 /// pixels. The maximum image size is 10 MB. /// /// You can also include images with the **images_file** parameter. (optional)</param> /// <param name="threshold">The minimum score a class must have to be displayed in the response. Set the /// threshold to `0.0` to return all identified classes. (optional)</param> /// <param name="owners">The categories of classifiers to apply. The **classifier_ids** parameter overrides /// **owners**, so make sure that **classifier_ids** is empty. /// - Use `IBM` to classify against the `default` general classifier. You get the same result if both /// **classifier_ids** and **owners** parameters are empty. /// - Use `me` to classify against all your custom classifiers. However, for better performance use /// **classifier_ids** to specify the specific custom classifiers to apply. /// - Use both `IBM` and `me` to analyze the image against both classifier categories. (optional)</param> /// <param name="classifierIds">Which classifiers to apply. Overrides the **owners** parameter. You can specify /// both custom and built-in classifier IDs. The built-in `default` classifier is used if both /// **classifier_ids** and **owners** parameters are empty. /// /// The following built-in classifier IDs require no training: /// - `default`: Returns classes from thousands of general tags. /// - `food`: Enhances specificity and accuracy for images of food items. /// - `explicit`: Evaluates whether the image might be pornographic. (optional)</param> /// <param name="acceptLanguage">The desired language of parts of the response. See the response for details. /// (optional, default to en)</param> /// <returns><see cref="ClassifiedImages" />ClassifiedImages</returns> public bool Classify(Callback<ClassifiedImages> callback, System.IO.MemoryStream imagesFile = null, string imagesFilename = null, string imagesFileContentType = null, string url = null, float? threshold = null, List<string> owners = null, List<string> classifierIds = null, string acceptLanguage = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Classify`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); RequestObject<ClassifiedImages> req = new RequestObject<ClassifiedImages> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "Classify")) { req.Headers.Add(kvp.Key, kvp.Value); } req.Forms = new Dictionary<string, RESTConnector.Form>(); if (imagesFile != null) { req.Forms["images_file"] = new RESTConnector.Form(imagesFile, imagesFilename, imagesFileContentType); } if (!string.IsNullOrEmpty(url)) { req.Forms["url"] = new RESTConnector.Form(url); } if (threshold != null) { req.Forms["threshold"] = new RESTConnector.Form(threshold.ToString()); } if (owners != null && owners.Count > 0) { req.Forms["owners"] = new RESTConnector.Form(string.Join(", ", owners.ToArray())); } if (classifierIds != null && classifierIds.Count > 0) { req.Forms["classifier_ids"] = new RESTConnector.Form(string.Join(", ", classifierIds.ToArray())); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.OnResponse = OnClassifyResponse; Connector.URL = GetServiceUrl() + "/v3/classify"; Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnClassifyResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<ClassifiedImages> response = new DetailedResponse<ClassifiedImages>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<ClassifiedImages>(json); response.Response = json; } catch (Exception e) { Log.Error("VisualRecognitionService.OnClassifyResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<ClassifiedImages>)req).Callback != null) ((RequestObject<ClassifiedImages>)req).Callback(response, resp.Error); } /// <summary> /// Create a classifier. /// /// Train a new multi-faceted classifier on the uploaded image data. Create your custom classifier with positive /// or negative example training images. Include at least two sets of examples, either two positive example /// files or one positive and one negative file. You can upload a maximum of 256 MB per call. /// /// **Tips when creating:** /// /// - If you set the **X-Watson-Learning-Opt-Out** header parameter to `true` when you create a classifier, the /// example training images are not stored. Save your training images locally. For more information, see [Data /// collection](#data-collection). /// /// - Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier /// and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="name">The name of the new classifier. Encode special characters in UTF-8.</param> /// <param name="positiveExamples">A dictionary that contains the value for each classname. The value is a .zip /// file of images that depict the visual subject of a class in the new classifier. You can include more than /// one positive example file in a call. /// /// Specify the parameter name by appending `_positive_examples` to the class name. For example, /// `goldenretriever_positive_examples` creates the class **goldenretriever**. The string cannot contain the /// following characters: ``$ * - { } \ | / ' " ` [ ]``. /// /// Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. /// The maximum number of images is 10,000 images or 100 MB per .zip file. /// /// Encode special characters in the file name in UTF-8.</param> /// <param name="negativeExamples">A .zip file of images that do not depict the visual subject of any of the /// classes of the new classifier. Must contain a minimum of 10 images. /// /// Encode special characters in the file name in UTF-8. (optional)</param> /// <param name="negativeExamplesFilename">The filename for negativeExamples. (optional)</param> /// <returns><see cref="Classifier" />Classifier</returns> public bool CreateClassifier(Callback<Classifier> callback, string name, Dictionary<string, System.IO.MemoryStream> positiveExamples, System.IO.MemoryStream negativeExamples = null, string negativeExamplesFilename = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `CreateClassifier`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("`name` is required for `CreateClassifier`"); if (positiveExamples == null) throw new ArgumentNullException("`positiveExamples` is required for `CreateClassifier`"); if (positiveExamples.Count == 0) throw new ArgumentException("`positiveExamples` must contain at least one dictionary entry"); RequestObject<Classifier> req = new RequestObject<Classifier> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "CreateClassifier")) { req.Headers.Add(kvp.Key, kvp.Value); } req.Forms = new Dictionary<string, RESTConnector.Form>(); if (!string.IsNullOrEmpty(name)) { req.Forms["name"] = new RESTConnector.Form(name); } if (positiveExamples != null && positiveExamples.Count > 0) { foreach (KeyValuePair<string, System.IO.MemoryStream> entry in positiveExamples) { var partName = string.Format("{0}_positive_examples", entry.Key); req.Forms[partName] = new RESTConnector.Form(entry.Value, entry.Key + ".zip", "application/octet-stream"); } } if (negativeExamples != null) { req.Forms["negative_examples"] = new RESTConnector.Form(negativeExamples, negativeExamplesFilename, "application/octet-stream"); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.OnResponse = OnCreateClassifierResponse; Connector.URL = GetServiceUrl() + "/v3/classifiers"; Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnCreateClassifierResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<Classifier> response = new DetailedResponse<Classifier>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<Classifier>(json); response.Response = json; } catch (Exception e) { Log.Error("VisualRecognitionService.OnCreateClassifierResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<Classifier>)req).Callback != null) ((RequestObject<Classifier>)req).Callback(response, resp.Error); } /// <summary> /// Retrieve a list of classifiers. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="verbose">Specify `true` to return details about the classifiers. Omit this parameter to return /// a brief list of classifiers. (optional)</param> /// <returns><see cref="Classifiers" />Classifiers</returns> public bool ListClassifiers(Callback<Classifiers> callback, bool? verbose = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListClassifiers`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); RequestObject<Classifiers> req = new RequestObject<Classifiers> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbGET, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "ListClassifiers")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } if (verbose != null) { req.Parameters["verbose"] = (bool)verbose ? "true" : "false"; } req.OnResponse = OnListClassifiersResponse; Connector.URL = GetServiceUrl() + "/v3/classifiers"; Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnListClassifiersResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<Classifiers> response = new DetailedResponse<Classifiers>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<Classifiers>(json); response.Response = json; } catch (Exception e) { Log.Error("VisualRecognitionService.OnListClassifiersResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<Classifiers>)req).Callback != null) ((RequestObject<Classifiers>)req).Callback(response, resp.Error); } /// <summary> /// Retrieve classifier details. /// /// Retrieve information about a custom classifier. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="classifierId">The ID of the classifier.</param> /// <returns><see cref="Classifier" />Classifier</returns> public bool GetClassifier(Callback<Classifier> callback, string classifierId) { if (callback == null) throw new ArgumentNullException("`callback` is required for `GetClassifier`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (string.IsNullOrEmpty(classifierId)) throw new ArgumentNullException("`classifierId` is required for `GetClassifier`"); RequestObject<Classifier> req = new RequestObject<Classifier> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbGET, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "GetClassifier")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.OnResponse = OnGetClassifierResponse; Connector.URL = GetServiceUrl() + string.Format("/v3/classifiers/{0}", classifierId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnGetClassifierResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<Classifier> response = new DetailedResponse<Classifier>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<Classifier>(json); response.Response = json; } catch (Exception e) { Log.Error("VisualRecognitionService.OnGetClassifierResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<Classifier>)req).Callback != null) ((RequestObject<Classifier>)req).Callback(response, resp.Error); } /// <summary> /// Update a classifier. /// /// Update a custom classifier by adding new positive or negative classes or by adding new images to existing /// classes. You must supply at least one set of positive or negative examples. For details, see [Updating /// custom /// classifiers](https://cloud.ibm.com/docs/visual-recognition?topic=visual-recognition-customizing#updating-custom-classifiers). /// /// Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier /// and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. /// /// **Tips about retraining:** /// /// - You can't update the classifier if the **X-Watson-Learning-Opt-Out** header parameter was set to `true` /// when the classifier was created. Training images are not stored in that case. Instead, create another /// classifier. For more information, see [Data collection](#data-collection). /// /// - Don't make retraining calls on a classifier until the status is ready. When you submit retraining requests /// in parallel, the last request overwrites the previous requests. The `retrained` property shows the last time /// the classifier retraining finished. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="classifierId">The ID of the classifier.</param> /// <param name="positiveExamples">A dictionary that contains the value for each classname. The value is a .zip /// file of images that depict the visual subject of a class in the classifier. The positive examples create or /// update classes in the classifier. You can include more than one positive example file in a call. /// /// Specify the parameter name by appending `_positive_examples` to the class name. For example, /// `goldenretriever_positive_examples` creates the class `goldenretriever`. The string cannot contain the /// following characters: ``$ * - { } \ | / ' " ` [ ]``. /// /// Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. /// The maximum number of images is 10,000 images or 100 MB per .zip file. /// /// Encode special characters in the file name in UTF-8. (optional)</param> /// <param name="negativeExamples">A .zip file of images that do not depict the visual subject of any of the /// classes of the new classifier. Must contain a minimum of 10 images. /// /// Encode special characters in the file name in UTF-8. (optional)</param> /// <param name="negativeExamplesFilename">The filename for negativeExamples. (optional)</param> /// <returns><see cref="Classifier" />Classifier</returns> public bool UpdateClassifier(Callback<Classifier> callback, string classifierId, Dictionary<string, System.IO.MemoryStream> positiveExamples = null, System.IO.MemoryStream negativeExamples = null, string negativeExamplesFilename = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `UpdateClassifier`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (string.IsNullOrEmpty(classifierId)) throw new ArgumentNullException("`classifierId` is required for `UpdateClassifier`"); RequestObject<Classifier> req = new RequestObject<Classifier> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "UpdateClassifier")) { req.Headers.Add(kvp.Key, kvp.Value); } req.Forms = new Dictionary<string, RESTConnector.Form>(); if (positiveExamples != null && positiveExamples.Count > 0) { foreach (KeyValuePair<string, System.IO.MemoryStream> entry in positiveExamples) { var partName = string.Format("{0}_positive_examples", entry.Key); req.Forms[partName] = new RESTConnector.Form(entry.Value, entry.Key + ".zip", "application/octet-stream"); } } if (negativeExamples != null) { req.Forms["negative_examples"] = new RESTConnector.Form(negativeExamples, negativeExamplesFilename, "application/octet-stream"); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.OnResponse = OnUpdateClassifierResponse; Connector.URL = GetServiceUrl() + string.Format("/v3/classifiers/{0}", classifierId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnUpdateClassifierResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<Classifier> response = new DetailedResponse<Classifier>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<Classifier>(json); response.Response = json; } catch (Exception e) { Log.Error("VisualRecognitionService.OnUpdateClassifierResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<Classifier>)req).Callback != null) ((RequestObject<Classifier>)req).Callback(response, resp.Error); } /// <summary> /// Delete a classifier. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="classifierId">The ID of the classifier.</param> /// <returns><see cref="object" />object</returns> public bool DeleteClassifier(Callback<object> callback, string classifierId) { if (callback == null) throw new ArgumentNullException("`callback` is required for `DeleteClassifier`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (string.IsNullOrEmpty(classifierId)) throw new ArgumentNullException("`classifierId` is required for `DeleteClassifier`"); RequestObject<object> req = new RequestObject<object> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbDELETE, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "DeleteClassifier")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.OnResponse = OnDeleteClassifierResponse; Connector.URL = GetServiceUrl() + string.Format("/v3/classifiers/{0}", classifierId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnDeleteClassifierResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<object> response = new DetailedResponse<object>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<object>(json); response.Response = json; } catch (Exception e) { Log.Error("VisualRecognitionService.OnDeleteClassifierResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<object>)req).Callback != null) ((RequestObject<object>)req).Callback(response, resp.Error); } /// <summary> /// Retrieve a Core ML model of a classifier. /// /// Download a Core ML model file (.mlmodel) of a custom classifier that returns <tt>"core_ml_enabled": /// true</tt> in the classifier details. /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="classifierId">The ID of the classifier.</param> /// <returns><see cref="byte[]" />byte[]</returns> public bool GetCoreMlModel(Callback<byte[]> callback, string classifierId) { if (callback == null) throw new ArgumentNullException("`callback` is required for `GetCoreMlModel`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (string.IsNullOrEmpty(classifierId)) throw new ArgumentNullException("`classifierId` is required for `GetCoreMlModel`"); RequestObject<byte[]> req = new RequestObject<byte[]> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbGET, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "GetCoreMlModel")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } req.OnResponse = OnGetCoreMlModelResponse; Connector.URL = GetServiceUrl() + string.Format("/v3/classifiers/{0}/core_ml_model", classifierId); Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnGetCoreMlModelResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<byte[]> response = new DetailedResponse<byte[]>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; response.Result = resp.Data; if (((RequestObject<byte[]>)req).Callback != null) ((RequestObject<byte[]>)req).Callback(response, resp.Error); } /// <summary> /// Delete labeled data. /// /// Deletes all data associated with a specified customer ID. The method has no effect if no data is associated /// with the customer ID. /// /// You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes /// data. For more information about personal data and customer IDs, see [Information /// security](https://cloud.ibm.com/docs/visual-recognition?topic=visual-recognition-information-security). /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="customerId">The customer ID for which all data is to be deleted.</param> /// <returns><see cref="object" />object</returns> public bool DeleteUserData(Callback<object> callback, string customerId) { if (callback == null) throw new ArgumentNullException("`callback` is required for `DeleteUserData`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException("`customerId` is required for `DeleteUserData`"); RequestObject<object> req = new RequestObject<object> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbDELETE, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "DeleteUserData")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } if (!string.IsNullOrEmpty(customerId)) { req.Parameters["customer_id"] = customerId; } req.OnResponse = OnDeleteUserDataResponse; Connector.URL = GetServiceUrl() + "/v3/user_data"; Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnDeleteUserDataResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<object> response = new DetailedResponse<object>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<object>(json); response.Response = json; } catch (Exception e) { Log.Error("VisualRecognitionService.OnDeleteUserDataResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<object>)req).Callback != null) ((RequestObject<object>)req).Callback(response, resp.Error); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// GradientControl /// </summary> [DefaultEvent("PositionChanging")] [ToolboxItem(false)] public class GradientSlider : Control { #region Fields private float _max; private Color _maxColor; private float _min; private Color _minColor; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GradientSlider"/> class. /// </summary> public GradientSlider() { _min = 0F; _max = 1F; LeftHandle = new RoundedHandle(this) { Position = .2F }; RightHandle = new RoundedHandle(this) { Position = .8F }; _minColor = Color.Transparent; _maxColor = Color.Blue; } #endregion #region Events /// <summary> /// Occurs after the user has finished adjusting the positions of either of the sliders and has released control /// </summary> public event EventHandler PositionChanged; /// <summary> /// Occurs as the user is adjusting the positions on either of the sliders /// </summary> public event EventHandler PositionChanging; #endregion #region Properties /// <summary> /// Gets or sets the floating point position of the left slider. This must range /// between 0 and 1, and to the left of the right slider, (therefore with a value lower than the right slider.) /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [TypeConverter(typeof(ExpandableObjectConverter))] public RoundedHandle LeftHandle { get; set; } /// <summary> /// Gets or sets the maximum allowed value for the slider. /// </summary> [Description("Gets or sets the maximum allowed value for the slider.")] public float Maximum { get { return _max; } set { _max = value; if (_max < RightHandle.Position) RightHandle.Position = _max; if (_max < LeftHandle.Position) LeftHandle.Position = _max; } } /// <summary> /// Gets or sets the color associated with the maximum value. /// </summary> [Description("Gets or sets the color associated with the maximum value.")] public Color MaximumColor { get { return _maxColor; } set { _maxColor = value; Invalidate(); } } /// <summary> /// Gets or sets the minimum allowed value for the slider. /// </summary> [Description("Gets or sets the minimum allowed value for the slider.")] public float Minimum { get { return _min; } set { _min = value; if (LeftHandle.Position < _min) LeftHandle.Position = _min; if (RightHandle.Position < _min) RightHandle.Position = _min; } } /// <summary> /// Gets or sets the color associated with the minimum color /// </summary> [Description("Gets or sets the color associated with the minimum value")] public Color MinimumColor { get { return _minColor; } set { _minColor = value; Invalidate(); } } /// <summary> /// Gets or sets the floating point position of the right slider. This must range /// between 0 and 1, and to the right of the left slider. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [TypeConverter(typeof(ExpandableObjectConverter))] public RoundedHandle RightHandle { get; set; } #endregion #region Methods /// <summary> /// Controls the actual drawing for this gradient slider control. /// </summary> /// <param name="g">The graphics object used for drawing.</param> /// <param name="clipRectangle">The clip rectangle.</param> protected virtual void OnDraw(Graphics g, Rectangle clipRectangle) { if (Width == 0 || Height == 0) return; LinearGradientBrush lgb = new LinearGradientBrush(ClientRectangle, BackColor.Lighter(.2F), BackColor.Darker(.2F), LinearGradientMode.Vertical); g.FillRectangle(lgb, ClientRectangle); lgb.Dispose(); int l = Convert.ToInt32((Width * (LeftHandle.Position - _min)) / (_max - _min)); int r = Convert.ToInt32((Width * (RightHandle.Position - _min)) / (_max - _min)); Rectangle a = new Rectangle(0, 5, l, Height - 10); Rectangle b = new Rectangle(l, 5, r - l, Height - 10); Rectangle c = new Rectangle(r, 5, Right - r, Height - 10); if (a.Width > 0) { SolidBrush sb = new SolidBrush(_minColor); g.FillRectangle(sb, a); sb.Dispose(); } if (b.Width > 0) { LinearGradientBrush center = new LinearGradientBrush(new Point(b.X, 0), new Point(b.Right, 0), _minColor, _maxColor); g.FillRectangle(center, b); center.Dispose(); } if (c.Width > 0) { SolidBrush sb = new SolidBrush(_maxColor); g.FillRectangle(sb, c); sb.Dispose(); } if (Enabled) { LeftHandle.Draw(g); RightHandle.Draw(g); } } /// <summary> /// Initiates slider dragging. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left && Enabled) { Rectangle l = LeftHandle.GetBounds(); if (l.Contains(e.Location) && LeftHandle.Visible) { LeftHandle.IsDragging = true; } Rectangle r = RightHandle.GetBounds(); if (r.Contains(e.Location) && RightHandle.Visible) { RightHandle.IsDragging = true; } } base.OnMouseDown(e); } /// <summary> /// Handles slider dragging. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseMove(MouseEventArgs e) { if (RightHandle.IsDragging) { float x = e.X; int min = 0; if (LeftHandle.Visible) min = LeftHandle.Width; if (x > Width) x = Width; if (x < min) x = min; RightHandle.Position = _min + ((x / Width) * (_max - _min)); if (LeftHandle.Visible) { float lw = LeftHandle.Width / (float)Width * (_max - _min); if (LeftHandle.Position > RightHandle.Position - lw) { LeftHandle.Position = RightHandle.Position - lw; } } OnPositionChanging(); } if (LeftHandle.IsDragging) { float x = e.X; int max = Width; if (RightHandle.Visible) max = Width - RightHandle.Width; if (x > max) x = max; if (x < 0) x = 0; LeftHandle.Position = _min + ((x / Width) * (_max - _min)); if (RightHandle.Visible) { float rw = RightHandle.Width / (float)Width * (_max - _min); if (RightHandle.Position < LeftHandle.Position + rw) { RightHandle.Position = LeftHandle.Position + rw; } } OnPositionChanging(); } Invalidate(); base.OnMouseMove(e); } /// <summary> /// Handles the mouse up situation. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseUp(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (RightHandle.IsDragging) RightHandle.IsDragging = false; if (LeftHandle.IsDragging) LeftHandle.IsDragging = false; OnPositionChanged(); } base.OnMouseUp(e); } /// <summary> /// Draw the clipped portion. /// </summary> /// <param name="e">The event args.</param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = e.ClipRectangle; if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(-clip.X, -clip.Y); g.Clip = new Region(clip); g.Clear(BackColor); g.SmoothingMode = SmoothingMode.AntiAlias; OnDraw(g, clip); g.Dispose(); e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel); } /// <summary> /// Prevent flicker /// </summary> /// <param name="e">The event args.</param> protected override void OnPaintBackground(PaintEventArgs e) { } /// <summary> /// Fires the Position Changed event after sliders are released. /// </summary> protected virtual void OnPositionChanged() { PositionChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Fires the Position Changing event while either slider is being dragged. /// </summary> protected virtual void OnPositionChanging() { PositionChanging?.Invoke(this, EventArgs.Empty); } #endregion } }
#region Copyright (c) Roni Schuetz - All Rights Reserved // * --------------------------------------------------------------------- * // * Roni Schuetz * // * Copyright (c) 2008 All Rights reserved * // * * // * Shared Cache high-performance, distributed caching and * // * replicated caching system, generic in nature, but intended to * // * speeding up dynamic web and / or win applications by alleviating * // * database load. * // * * // * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) * // * * // * This library is free software; you can redistribute it and/or * // * modify it under the terms of the GNU Lesser General Public License * // * as published by the Free Software Foundation; either version 2.1 * // * of the License, or (at your option) any later version. * // * * // * This library is distributed in the hope that it will be useful, * // * but WITHOUT ANY WARRANTY; without even the implied warranty of * // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * // * Lesser General Public License for more details. * // * * // * You should have received a copy of the GNU Lesser General Public * // * License along with this library; if not, write to the Free * // * Software Foundation, Inc., 59 Temple Place, Suite 330, * // * Boston, MA 02111-1307 USA * // * * // * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. * // * --------------------------------------------------------------------- * #endregion // ************************************************************************* // // Name: Listener.cs // // Created: 21-01-2007 SharedCache.com, rschuetz // Modified: 21-01-2007 SharedCache.com, rschuetz : Creation // Modified: 15-07-2007 SharedCache.com, rschuetz : added Sync log // Modified: 15-07-2007 SharedCache.com, rschuetz : added on some methods the check if in App.Config Logging is enabled // Modified: 31-12-2007 SharedCache.com, rschuetz : applied on all Log methods the checked if LoggingEnable == 1 // Modified: 06-01-2008 SharedCache.com, rschuetz : removed checked for LoggingEnable on MemoryFatalException, while systems are using configuration option -1 on the key: CacheAmountOfObject they need to be informed in any case that the cache is full. // Modified: 06-01-2008 SharedCache.com, rschuetz : introduce to Force Method, this enables log writting in any case even if LoggingEnable = 0; // Modified: 24-02-2008 SharedCache.com, rschuetz : updated logging part for tracking, instead of using appsetting we use precompiler definition #if TRACE // Modified: 28-01-2010 SharedCache.com, chrisme : clean up code // ************************************************************************* using System; using NLog; namespace SharedCache.WinServiceCommon.Handler { /// <summary> /// LogHandler uses to log information with NLog. /// </summary> public class LogHandler { private const string LogNameError = "General"; private const string LogNameTraffic = "Traffic"; private const string LogNameTracking = "Tracking"; private const string LogNameSync = "Sync"; private const string LogNameMemory = "Memory"; private static Logger error = LogManager.GetLogger(LogNameError); private static Logger traffic = LogManager.GetLogger(LogNameTraffic); private static Logger tracking = LogManager.GetLogger(LogNameTracking); private static Logger sync = LogManager.GetLogger(LogNameSync); private static Logger memory = LogManager.GetLogger(LogNameMemory); #region Sync /// <summary> /// Logging Message and Exception around synchronizing data /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> /// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void SyncDebugException(string msg, Exception ex) { { sync.DebugException(msg, ex); } } /// <summary> /// Logging Message and Exception around synchronizing data /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void SyncDebug(string msg) { { sync.Debug(msg); } } /// <summary> /// Logging information around synchronizing data /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void SyncInfo(string msg) { { sync.Info(msg); } } /// <summary> /// Logging Fatal Error Message around synchronizing data /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void SyncFatal(string msg) { { sync.Fatal(msg); } } /// <summary> /// Logging Fatal Error Message and Exception around synchronizing data /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> /// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void SyncFatalException(string msg, Exception ex) { { sync.FatalException(msg, ex); } } #endregion Sync #region Error Log /// <summary> /// Force a message, undepend of the Configuration. /// </summary> /// <param name="msg">a <see cref="string"/> message</param> [System.Diagnostics.DebuggerStepThrough] public static void Force(string msg) { error.Info(msg); } /// <summary> /// Debugs the specified MSG. /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> /// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Debug(string msg, Exception ex) { { error.DebugException(System.Environment.MachineName + ": " + msg, ex); } } /// <summary> /// Debugs the specified MSG. /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Debug(string msg) { { error.Debug(System.Environment.MachineName + ": " + msg); } } /// <summary> /// Infoes the specified MSG. /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> /// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Info(string msg, Exception ex) { { error.InfoException(System.Environment.MachineName + ": " + msg, ex); } } /// <summary> /// Infoes the specified MSG. /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Info(string msg) { { error.Info(System.Environment.MachineName + ": " + msg); } } /// <summary> /// Fatals the specified MSG. /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> /// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Fatal(string msg, Exception ex) { error.FatalException(System.Environment.MachineName + ": " + msg, ex); } /// <summary> /// Fatals the specified MSG. /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Fatal(string msg) { error.Fatal(System.Environment.MachineName + ": " + msg); } /// <summary> /// Errors the specified MSG. /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> /// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Error(string msg, Exception ex) { { error.ErrorException(System.Environment.MachineName + "; " + msg, ex); } } /// <summary> /// Errors the specified MSG. /// </summary> /// <param name="msg">The MSG. A <see cref="T:System.String"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Error(string msg) { { error.Error(System.Environment.MachineName + ": " + msg); } } /// <summary> /// Errors the specified ex. /// </summary> /// <param name="ex">The ex. A <see cref="T:System.Exception"/> Object.</param> [System.Diagnostics.DebuggerStepThrough] public static void Error(Exception ex) { { Error(System.Environment.MachineName, ex); } } #endregion Error Log #region Traffic /***************************************************************************************/ /// <summary> /// Traffic exceptions. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="ex">The ex.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] [System.Diagnostics.DebuggerStepThrough] public static void TrafficException(string msg, Exception ex) { traffic.LogException(LogLevel.Error, System.Environment.MachineName + ": " + msg.Replace('\n', '0'), ex); } /// <summary> /// Adding Traffic messages to log /// </summary> /// <param name="msg">The MSG.</param> [System.Diagnostics.DebuggerStepThrough] public static void Traffic(string msg) { traffic.Log(LogLevel.Info, System.Environment.MachineName + ": " + msg); } #endregion Traffic #region Tracking /***************************************************************************************/ /// <summary> /// Tracking exception and a message. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="ex">The ex.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] [System.Diagnostics.DebuggerStepThrough] public static void TrackingException(string msg, Exception ex) { #if TRACE { tracking.LogException(LogLevel.Error, System.Environment.MachineName + ": " + msg.Replace('\n', '0'), ex); } #endif } /// <summary> /// Trackings the specified MSG. /// </summary> /// <param name="msg">The MSG.</param> [System.Diagnostics.DebuggerStepThrough] public static void Tracking(string msg) { #if TRACE { tracking.Log(LogLevel.Debug, System.Environment.MachineName + ": " + msg); } #endif } #endregion Tracking #region Memory /// <summary> /// Logs the Memory fatal message. /// </summary> /// <param name="msg">The MSG.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] [System.Diagnostics.DebuggerStepThrough] public static void MemoryFatalException(string msg) { { SystemManagement.Cpu.LogCpuData(); SystemManagement.Memory.LogMemoryData(); memory.FatalException(msg, new Exception(msg)); } } /// <summary> /// Logs the Memory fatal exception. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="ex">The ex.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] [System.Diagnostics.DebuggerStepThrough] public static void MemoryFatalException(string msg, Exception ex) { SystemManagement.Cpu.LogCpuData(); SystemManagement.Memory.LogMemoryData(); memory.FatalException(msg, ex); } /// <summary> /// Memories the debug. /// </summary> /// <param name="msg">The MSG.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] [System.Diagnostics.DebuggerStepThrough] public static void MemoryDebug(string msg) { { SystemManagement.Cpu.LogCpuData(); SystemManagement.Memory.LogMemoryData(); memory.Debug(msg); } } #endregion Memory } }
using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Security; using System.Security.Cryptography; using System.Text; using System.Xml; using Server; using Server.Misc; using Server.Mobiles; using Server.Multis; using Server.Network; namespace Server.Accounting { public class Account : IAccount, IComparable, IComparable<Account> { public static readonly TimeSpan YoungDuration = TimeSpan.FromHours( 40.0 ); public static readonly TimeSpan InactiveDuration = TimeSpan.FromDays( 180.0 ); public static readonly TimeSpan EmptyInactiveDuration = TimeSpan.FromDays(30.0); private string m_Username, m_PlainPassword, m_CryptPassword, m_NewCryptPassword; private AccessLevel m_AccessLevel; private int m_Flags; private DateTime m_Created, m_LastLogin; private TimeSpan m_TotalGameTime; private List<AccountComment> m_Comments; private List<AccountTag> m_Tags; private Mobile[] m_Mobiles; private string[] m_IPRestrictions; private IPAddress[] m_LoginIPs; private HardwareInfo m_HardwareInfo; /// <summary> /// Deletes the account, all characters of the account, and all houses of those characters /// </summary> public void Delete() { for ( int i = 0; i < this.Length; ++i ) { Mobile m = this[i]; if ( m == null ) continue; List<BaseHouse> list = BaseHouse.GetHouses( m ); for ( int j = 0; j < list.Count; ++j ) list[j].Delete(); m.Delete(); m.Account = null; m_Mobiles[i] = null; } if (m_LoginIPs.Length != 0 && AccountHandler.IPTable.ContainsKey(m_LoginIPs[0])) --AccountHandler.IPTable[m_LoginIPs[0]]; Accounts.Remove( m_Username ); } /// <summary> /// Object detailing information about the hardware of the last person to log into this account /// </summary> public HardwareInfo HardwareInfo { get { return m_HardwareInfo; } set { m_HardwareInfo = value; } } /// <summary> /// List of IP addresses for restricted access. '*' wildcard supported. If the array contains zero entries, all IP addresses are allowed. /// </summary> public string[] IPRestrictions { get { return m_IPRestrictions; } set { m_IPRestrictions = value; } } /// <summary> /// List of IP addresses which have successfully logged into this account. /// </summary> public IPAddress[] LoginIPs { get { return m_LoginIPs; } set { m_LoginIPs = value; } } /// <summary> /// List of account comments. Type of contained objects is AccountComment. /// </summary> public List<AccountComment> Comments { get { if ( m_Comments == null ) m_Comments = new List<AccountComment>(); return m_Comments; } } /// <summary> /// List of account tags. Type of contained objects is AccountTag. /// </summary> public List<AccountTag> Tags { get { if ( m_Tags == null ) m_Tags = new List<AccountTag>(); return m_Tags; } } /// <summary> /// Account username. Case insensitive validation. /// </summary> public string Username { get { return m_Username; } set { m_Username = value; } } /// <summary> /// Account password. Plain text. Case sensitive validation. May be null. /// </summary> public string PlainPassword { get { return m_PlainPassword; } set { m_PlainPassword = value; } } /// <summary> /// Account password. Hashed with MD5. May be null. /// </summary> public string CryptPassword { get { return m_CryptPassword; } set { m_CryptPassword = value; } } /// <summary> /// Account username and password hashed with SHA1. May be null. /// </summary> public string NewCryptPassword { get { return m_NewCryptPassword; } set { m_NewCryptPassword = value; } } /// <summary> /// Initial AccessLevel for new characters created on this account. /// </summary> public AccessLevel AccessLevel { get { return m_AccessLevel; } set { m_AccessLevel = value; } } /// <summary> /// Internal bitfield of account flags. Consider using direct access properties (Banned, Young), or GetFlag/SetFlag methods /// </summary> public int Flags { get { return m_Flags; } set { m_Flags = value; } } /// <summary> /// Gets or sets a flag indiciating if this account is banned. /// </summary> public bool Banned { get { bool isBanned = GetFlag( 0 ); if ( !isBanned ) return false; DateTime banTime; TimeSpan banDuration; if ( GetBanTags( out banTime, out banDuration ) ) { if ( banDuration != TimeSpan.MaxValue && DateTime.Now >= ( banTime + banDuration ) ) { SetUnspecifiedBan( null ); // clear Banned = false; return false; } } return true; } set { SetFlag( 0, value ); } } /// <summary> /// Gets or sets a flag indicating if the characters created on this account will have the young status. /// </summary> public bool Young { get { return !GetFlag( 1 ); } set { SetFlag( 1, !value ); if ( m_YoungTimer != null ) { m_YoungTimer.Stop(); m_YoungTimer = null; } } } /// <summary> /// The date and time of when this account was created. /// </summary> public DateTime Created { get { return m_Created; } } /// <summary> /// Gets or sets the date and time when this account was last accessed. /// </summary> public DateTime LastLogin { get { return m_LastLogin; } set { m_LastLogin = value; } } /// <summary> /// An account is considered inactive based upon LastLogin and InactiveDuration. If the account is empty, it is based upon EmptyInactiveDuration /// </summary> public bool Inactive { get { if (this.AccessLevel != AccessLevel.Player) return false; TimeSpan inactiveLength = DateTime.Now - m_LastLogin; return (inactiveLength > ((this.Count == 0) ? EmptyInactiveDuration : InactiveDuration)); } } /// <summary> /// Gets the total game time of this account, also considering the game time of characters /// that have been deleted. /// </summary> public TimeSpan TotalGameTime { get { for ( int i = 0; i < m_Mobiles.Length; i++ ) { PlayerMobile m = m_Mobiles[i] as PlayerMobile; if ( m != null && m.NetState != null ) return m_TotalGameTime + ( DateTime.Now - m.SessionStart ); } return m_TotalGameTime; } } /// <summary> /// Gets the value of a specific flag in the Flags bitfield. /// </summary> /// <param name="index">The zero-based flag index.</param> public bool GetFlag( int index ) { return ( m_Flags & ( 1 << index ) ) != 0; } /// <summary> /// Sets the value of a specific flag in the Flags bitfield. /// </summary> /// <param name="index">The zero-based flag index.</param> /// <param name="value">The value to set.</param> public void SetFlag( int index, bool value ) { if ( value ) m_Flags |= ( 1 << index ); else m_Flags &= ~( 1 << index ); } /// <summary> /// Adds a new tag to this account. This method does not check for duplicate names. /// </summary> /// <param name="name">New tag name.</param> /// <param name="value">New tag value.</param> public void AddTag( string name, string value ) { Tags.Add( new AccountTag( name, value ) ); } /// <summary> /// Removes all tags with the specified name from this account. /// </summary> /// <param name="name">Tag name to remove.</param> public void RemoveTag( string name ) { for ( int i = Tags.Count - 1; i >= 0; --i ) { if ( i >= Tags.Count ) continue; AccountTag tag = Tags[i]; if ( tag.Name == name ) Tags.RemoveAt( i ); } } /// <summary> /// Modifies an existing tag or adds a new tag if no tag exists. /// </summary> /// <param name="name">Tag name.</param> /// <param name="value">Tag value.</param> public void SetTag( string name, string value ) { for ( int i = 0; i < Tags.Count; ++i ) { AccountTag tag = Tags[i]; if ( tag.Name == name ) { tag.Value = value; return; } } AddTag( name, value ); } /// <summary> /// Gets the value of a tag -or- null if there are no tags with the specified name. /// </summary> /// <param name="name">Name of the desired tag value.</param> public string GetTag( string name ) { for ( int i = 0; i < Tags.Count; ++i ) { AccountTag tag = Tags[i]; if ( tag.Name == name ) return tag.Value; } return null; } public void SetUnspecifiedBan( Mobile from ) { SetBanTags( from, DateTime.MinValue, TimeSpan.Zero ); } public void SetBanTags( Mobile from, DateTime banTime, TimeSpan banDuration ) { if ( from == null ) RemoveTag( "BanDealer" ); else SetTag( "BanDealer", from.ToString() ); if ( banTime == DateTime.MinValue ) RemoveTag( "BanTime" ); else SetTag( "BanTime", XmlConvert.ToString( banTime, XmlDateTimeSerializationMode.Local ) ); if ( banDuration == TimeSpan.Zero ) RemoveTag( "BanDuration" ); else SetTag( "BanDuration", banDuration.ToString() ); } public bool GetBanTags( out DateTime banTime, out TimeSpan banDuration ) { string tagTime = GetTag( "BanTime" ); string tagDuration = GetTag( "BanDuration" ); if ( tagTime != null ) banTime = Utility.GetXMLDateTime( tagTime, DateTime.MinValue ); else banTime = DateTime.MinValue; if ( tagDuration == "Infinite" ) { banDuration = TimeSpan.MaxValue; } else if ( tagDuration != null ) { banDuration = Utility.ToTimeSpan( tagDuration ); } else { banDuration = TimeSpan.Zero; } return ( banTime != DateTime.MinValue && banDuration != TimeSpan.Zero ); } private static MD5CryptoServiceProvider m_MD5HashProvider; private static SHA1CryptoServiceProvider m_SHA1HashProvider; private static byte[] m_HashBuffer; public static string HashMD5( string phrase ) { if ( m_MD5HashProvider == null ) m_MD5HashProvider = new MD5CryptoServiceProvider(); if ( m_HashBuffer == null ) m_HashBuffer = new byte[256]; int length = Encoding.ASCII.GetBytes( phrase, 0, phrase.Length > 256 ? 256 : phrase.Length, m_HashBuffer, 0 ); byte[] hashed = m_MD5HashProvider.ComputeHash( m_HashBuffer, 0, length ); return BitConverter.ToString( hashed ); } public static string HashSHA1( string phrase ) { if ( m_SHA1HashProvider == null ) m_SHA1HashProvider = new SHA1CryptoServiceProvider(); if ( m_HashBuffer == null ) m_HashBuffer = new byte[256]; int length = Encoding.ASCII.GetBytes( phrase, 0, phrase.Length > 256 ? 256 : phrase.Length, m_HashBuffer, 0 ); byte[] hashed = m_SHA1HashProvider.ComputeHash( m_HashBuffer, 0, length ); return BitConverter.ToString( hashed ); } public void SetPassword( string plainPassword ) { switch ( AccountHandler.ProtectPasswords ) { case PasswordProtection.None: { m_PlainPassword = plainPassword; m_CryptPassword = null; m_NewCryptPassword = null; break; } case PasswordProtection.Crypt: { m_PlainPassword = null; m_CryptPassword = HashMD5( plainPassword ); m_NewCryptPassword = null; break; } default: // PasswordProtection.NewCrypt { m_PlainPassword = null; m_CryptPassword = null; m_NewCryptPassword = HashSHA1( m_Username + plainPassword ); break; } } } public bool CheckPassword( string plainPassword ) { bool ok; PasswordProtection curProt; if ( m_PlainPassword != null ) { ok = ( m_PlainPassword == plainPassword ); curProt = PasswordProtection.None; } else if ( m_CryptPassword != null ) { ok = ( m_CryptPassword == HashMD5( plainPassword ) ); curProt = PasswordProtection.Crypt; } else { ok = ( m_NewCryptPassword == HashSHA1( m_Username + plainPassword ) ); curProt = PasswordProtection.NewCrypt; } if ( ok && curProt != AccountHandler.ProtectPasswords ) SetPassword( plainPassword ); return ok; } private Timer m_YoungTimer; public static void Initialize() { EventSink.Connected += new ConnectedEventHandler( EventSink_Connected ); EventSink.Disconnected += new DisconnectedEventHandler( EventSink_Disconnected ); EventSink.Login += new LoginEventHandler( EventSink_Login ); } private static void EventSink_Connected( ConnectedEventArgs e ) { Account acc = e.Mobile.Account as Account; if ( acc == null ) return; if ( acc.Young && acc.m_YoungTimer == null ) { acc.m_YoungTimer = new YoungTimer( acc ); acc.m_YoungTimer.Start(); } } private static void EventSink_Disconnected( DisconnectedEventArgs e ) { Account acc = e.Mobile.Account as Account; if ( acc == null ) return; if ( acc.m_YoungTimer != null ) { acc.m_YoungTimer.Stop(); acc.m_YoungTimer = null; } PlayerMobile m = e.Mobile as PlayerMobile; if ( m == null ) return; acc.m_TotalGameTime += DateTime.Now - m.SessionStart; } private static void EventSink_Login( LoginEventArgs e ) { PlayerMobile m = e.Mobile as PlayerMobile; if ( m == null ) return; Account acc = m.Account as Account; if ( acc == null ) return; if ( m.Young && acc.Young ) { TimeSpan ts = YoungDuration - acc.TotalGameTime; int hours = Math.Max( (int) ts.TotalHours, 0 ); m.SendAsciiMessage( "You will enjoy the benefits and relatively safe status of a young player for {0} more hour{1}.", hours, hours != 1 ? "s" : "" ); } } public void RemoveYoungStatus( int message ) { this.Young = false; for ( int i = 0; i < m_Mobiles.Length; i++ ) { PlayerMobile m = m_Mobiles[i] as PlayerMobile; if ( m != null && m.Young ) { m.Young = false; if ( m.NetState != null ) { if ( message > 0 ) m.SendLocalizedMessage( message ); m.SendLocalizedMessage( 1019039 ); // You are no longer considered a young player of Ultima Online, and are no longer subject to the limitations and benefits of being in that caste. } } } } public void CheckYoung() { if ( TotalGameTime >= YoungDuration ) RemoveYoungStatus( 1019038 ); // You are old enough to be considered an adult, and have outgrown your status as a young player! } private class YoungTimer : Timer { private Account m_Account; public YoungTimer( Account account ) : base( TimeSpan.FromMinutes( 1.0 ), TimeSpan.FromMinutes( 1.0 ) ) { m_Account = account; Priority = TimerPriority.FiveSeconds; } protected override void OnTick() { m_Account.CheckYoung(); } } public Account( string username, string password ) { m_Username = username; SetPassword( password ); m_AccessLevel = AccessLevel.Player; m_Created = m_LastLogin = DateTime.Now; m_TotalGameTime = TimeSpan.Zero; m_Mobiles = new Mobile[7]; m_IPRestrictions = new string[0]; m_LoginIPs = new IPAddress[0]; Accounts.Add( this ); } public Account( XmlElement node ) { m_Username = Utility.GetText( node["username"], "empty" ); string plainPassword = Utility.GetText( node["password"], null ); string cryptPassword = Utility.GetText( node["cryptPassword"], null ); string newCryptPassword = Utility.GetText( node["newCryptPassword"], null ); switch ( AccountHandler.ProtectPasswords ) { case PasswordProtection.None: { if ( plainPassword != null ) SetPassword( plainPassword ); else if ( newCryptPassword != null ) m_NewCryptPassword = newCryptPassword; else if ( cryptPassword != null ) m_CryptPassword = cryptPassword; else SetPassword( "empty" ); break; } case PasswordProtection.Crypt: { if ( cryptPassword != null ) m_CryptPassword = cryptPassword; else if ( plainPassword != null ) SetPassword( plainPassword ); else if ( newCryptPassword != null ) m_NewCryptPassword = newCryptPassword; else SetPassword( "empty" ); break; } default: // PasswordProtection.NewCrypt { if ( newCryptPassword != null ) m_NewCryptPassword = newCryptPassword; else if ( plainPassword != null ) SetPassword( plainPassword ); else if ( cryptPassword != null ) m_CryptPassword = cryptPassword; else SetPassword( "empty" ); break; } } #if Framework_4_0 Enum.TryParse( Utility.GetText( node["accessLevel"], "Player" ), true, out m_AccessLevel ); #else m_AccessLevel = (AccessLevel)Enum.Parse(typeof(AccessLevel), Utility.GetText(node["accessLevel"], "Player"), true); #endif m_Flags = Utility.GetXMLInt32(Utility.GetText(node["flags"], "0"), 0); m_Created = Utility.GetXMLDateTime( Utility.GetText( node["created"], null ), DateTime.Now ); m_LastLogin = Utility.GetXMLDateTime( Utility.GetText( node["lastLogin"], null ), DateTime.Now ); m_Mobiles = LoadMobiles( node ); m_Comments = LoadComments( node ); m_Tags = LoadTags( node ); m_LoginIPs = LoadAddressList( node ); m_IPRestrictions = LoadAccessCheck( node ); for ( int i = 0; i < m_Mobiles.Length; ++i ) { if ( m_Mobiles[i] != null ) m_Mobiles[i].Account = this; } TimeSpan totalGameTime = Utility.GetXMLTimeSpan( Utility.GetText( node["totalGameTime"], null ), TimeSpan.Zero ); if ( totalGameTime == TimeSpan.Zero ) { for ( int i = 0; i < m_Mobiles.Length; i++ ) { PlayerMobile m = m_Mobiles[i] as PlayerMobile; if ( m != null ) totalGameTime += m.GameTime; } } m_TotalGameTime = totalGameTime; if ( this.Young ) CheckYoung(); Accounts.Add( this ); } /// <summary> /// Deserializes a list of string values from an xml element. Null values are not added to the list. /// </summary> /// <param name="node">The XmlElement from which to deserialize.</param> /// <returns>String list. Value will never be null.</returns> public static string[] LoadAccessCheck( XmlElement node ) { string[] stringList; XmlElement accessCheck = node["accessCheck"]; if ( accessCheck != null ) { List<string> list = new List<string>(); foreach ( XmlElement ip in accessCheck.GetElementsByTagName( "ip" ) ) { string text = Utility.GetText( ip, null ); if ( text != null ) list.Add( text ); } stringList = list.ToArray(); } else { stringList = new string[0]; } return stringList; } /// <summary> /// Deserializes a list of IPAddress values from an xml element. /// </summary> /// <param name="node">The XmlElement from which to deserialize.</param> /// <returns>Address list. Value will never be null.</returns> public static IPAddress[] LoadAddressList( XmlElement node ) { IPAddress[] list; XmlElement addressList = node["addressList"]; if ( addressList != null ) { int count = Utility.GetXMLInt32( Utility.GetAttribute( addressList, "count", "0" ), 0 ); list = new IPAddress[count]; count = 0; foreach ( XmlElement ip in addressList.GetElementsByTagName( "ip" ) ) { if ( count < list.Length ) { IPAddress address; if( IPAddress.TryParse( Utility.GetText( ip, null ), out address ) ) { list[count] = Utility.Intern( address ); count++; } } } if ( count != list.Length ) { IPAddress[] old = list; list = new IPAddress[count]; for ( int i = 0; i < count && i < old.Length; ++i ) list[i] = old[i]; } } else { list = new IPAddress[0]; } return list; } /// <summary> /// Deserializes a list of Mobile instances from an xml element. /// </summary> /// <param name="node">The XmlElement instance from which to deserialize.</param> /// <returns>Mobile list. Value will never be null.</returns> public static Mobile[] LoadMobiles( XmlElement node ) { Mobile[] list = new Mobile[7]; XmlElement chars = node["chars"]; //int length = Accounts.GetInt32( Accounts.GetAttribute( chars, "length", "6" ), 6 ); //list = new Mobile[length]; //Above is legacy, no longer used if ( chars != null ) { foreach ( XmlElement ele in chars.GetElementsByTagName( "char" ) ) { try { int index = Utility.GetXMLInt32( Utility.GetAttribute( ele, "index", "0" ), 0 ); int serial = Utility.GetXMLInt32( Utility.GetText( ele, "0" ), 0 ); if ( index >= 0 && index < list.Length ) list[index] = World.FindMobile( serial ); } catch { } } } return list; } /// <summary> /// Deserializes a list of AccountComment instances from an xml element. /// </summary> /// <param name="node">The XmlElement from which to deserialize.</param> /// <returns>Comment list. Value will never be null.</returns> public static List<AccountComment> LoadComments( XmlElement node ) { List<AccountComment> list = null; XmlElement comments = node["comments"]; if ( comments != null ) { list = new List<AccountComment>(); foreach ( XmlElement comment in comments.GetElementsByTagName( "comment" ) ) { try { list.Add( new AccountComment( comment ) ); } catch { } } } return list; } /// <summary> /// Deserializes a list of AccountTag instances from an xml element. /// </summary> /// <param name="node">The XmlElement from which to deserialize.</param> /// <returns>Tag list. Value will never be null.</returns> public static List<AccountTag> LoadTags( XmlElement node ) { List<AccountTag> list = null; XmlElement tags = node["tags"]; if ( tags != null ) { list = new List<AccountTag>(); foreach ( XmlElement tag in tags.GetElementsByTagName( "tag" ) ) { try { list.Add( new AccountTag( tag ) ); } catch { } } } return list; } /// <summary> /// Checks if a specific NetState is allowed access to this account. /// </summary> /// <param name="ns">NetState instance to check.</param> /// <returns>True if allowed, false if not.</returns> public bool HasAccess( NetState ns ) { return ( ns != null && HasAccess( ns.Address ) ); } public bool HasAccess( IPAddress ipAddress ) { AccessLevel level = Misc.AccountHandler.LockdownLevel; if ( level > AccessLevel.Player ) { bool hasAccess = false; if ( m_AccessLevel >= level ) { hasAccess = true; } else { for ( int i = 0; !hasAccess && i < this.Length; ++i ) { Mobile m = this[i]; if ( m != null && m.AccessLevel >= level ) hasAccess = true; } } if ( !hasAccess ) return false; } bool accessAllowed = ( m_IPRestrictions.Length == 0 || IPLimiter.IsExempt( ipAddress ) ); for ( int i = 0; !accessAllowed && i < m_IPRestrictions.Length; ++i ) accessAllowed = Utility.IPMatch( m_IPRestrictions[i], ipAddress ); return accessAllowed; } /// <summary> /// Records the IP address of 'ns' in its 'LoginIPs' list. /// </summary> /// <param name="ns">NetState instance to record.</param> public void LogAccess( NetState ns ) { if ( ns != null ) { LogAccess( ns.Address ); } } public void LogAccess( IPAddress ipAddress ) { if ( IPLimiter.IsExempt( ipAddress ) ) return; if ( m_LoginIPs.Length == 0 ) { if ( AccountHandler.IPTable.ContainsKey( ipAddress ) ) AccountHandler.IPTable[ipAddress]++; else AccountHandler.IPTable[ipAddress] = 1; } bool contains = false; for ( int i = 0; !contains && i < m_LoginIPs.Length; ++i ) contains = m_LoginIPs[i].Equals( ipAddress ); if ( contains ) return; IPAddress[] old = m_LoginIPs; m_LoginIPs = new IPAddress[old.Length + 1]; for ( int i = 0; i < old.Length; ++i ) m_LoginIPs[i] = old[i]; m_LoginIPs[old.Length] = ipAddress; } /// <summary> /// Checks if a specific NetState is allowed access to this account. If true, the NetState IPAddress is added to the address list. /// </summary> /// <param name="ns">NetState instance to check.</param> /// <returns>True if allowed, false if not.</returns> public bool CheckAccess( NetState ns ) { return ( ns != null && CheckAccess( ns.Address ) ); } public bool CheckAccess( IPAddress ipAddress ) { bool hasAccess = this.HasAccess( ipAddress ); if ( hasAccess ) { LogAccess( ipAddress ); } return hasAccess; } /// <summary> /// Serializes this Account instance to an XmlTextWriter. /// </summary> /// <param name="xml">The XmlTextWriter instance from which to serialize.</param> public void Save( XmlTextWriter xml ) { xml.WriteStartElement( "account" ); xml.WriteStartElement( "username" ); xml.WriteString( m_Username ); xml.WriteEndElement(); if ( m_PlainPassword != null ) { xml.WriteStartElement( "password" ); xml.WriteString( m_PlainPassword ); xml.WriteEndElement(); } if ( m_CryptPassword != null ) { xml.WriteStartElement( "cryptPassword" ); xml.WriteString( m_CryptPassword ); xml.WriteEndElement(); } if ( m_NewCryptPassword != null ) { xml.WriteStartElement( "newCryptPassword" ); xml.WriteString( m_NewCryptPassword ); xml.WriteEndElement(); } if ( m_AccessLevel != AccessLevel.Player ) { xml.WriteStartElement( "accessLevel" ); xml.WriteString( m_AccessLevel.ToString() ); xml.WriteEndElement(); } if ( m_Flags != 0 ) { xml.WriteStartElement( "flags" ); xml.WriteString( XmlConvert.ToString( m_Flags ) ); xml.WriteEndElement(); } xml.WriteStartElement( "created" ); xml.WriteString( XmlConvert.ToString( m_Created, XmlDateTimeSerializationMode.Local ) ); xml.WriteEndElement(); xml.WriteStartElement( "lastLogin" ); xml.WriteString( XmlConvert.ToString( m_LastLogin, XmlDateTimeSerializationMode.Local ) ); xml.WriteEndElement(); xml.WriteStartElement( "totalGameTime" ); xml.WriteString( XmlConvert.ToString( TotalGameTime ) ); xml.WriteEndElement(); xml.WriteStartElement( "chars" ); //xml.WriteAttributeString( "length", m_Mobiles.Length.ToString() ); //Legacy, Not used anymore for ( int i = 0; i < m_Mobiles.Length; ++i ) { Mobile m = m_Mobiles[i]; if ( m != null && !m.Deleted ) { xml.WriteStartElement( "char" ); xml.WriteAttributeString( "index", i.ToString() ); xml.WriteString( m.Serial.Value.ToString() ); xml.WriteEndElement(); } } xml.WriteEndElement(); if ( m_Comments != null && m_Comments.Count > 0 ) { xml.WriteStartElement( "comments" ); for ( int i = 0; i < m_Comments.Count; ++i ) m_Comments[i].Save( xml ); xml.WriteEndElement(); } if ( m_Tags != null && m_Tags.Count > 0 ) { xml.WriteStartElement( "tags" ); for ( int i = 0; i < m_Tags.Count; ++i ) m_Tags[i].Save( xml ); xml.WriteEndElement(); } if ( m_LoginIPs.Length > 0 ) { xml.WriteStartElement( "addressList" ); xml.WriteAttributeString( "count", m_LoginIPs.Length.ToString() ); for ( int i = 0; i < m_LoginIPs.Length; ++i ) { xml.WriteStartElement( "ip" ); xml.WriteString( m_LoginIPs[i].ToString() ); xml.WriteEndElement(); } xml.WriteEndElement(); } if ( m_IPRestrictions.Length > 0 ) { xml.WriteStartElement( "accessCheck" ); for ( int i = 0; i < m_IPRestrictions.Length; ++i ) { xml.WriteStartElement( "ip" ); xml.WriteString( m_IPRestrictions[i] ); xml.WriteEndElement(); } xml.WriteEndElement(); } xml.WriteEndElement(); } /// <summary> /// Gets the current number of characters on this account. /// </summary> public int Count { get { int count = 0; for ( int i = 0; i < this.Length; ++i ) { if ( this[i] != null ) ++count; } return count; } } /// <summary> /// Gets the maximum amount of characters allowed to be created on this account. Values other than 1, 5, 6, or 7 are not supported by the client. /// </summary> public int Limit { get { return 5; /*( Core.SA ? 7 : Core.AOS ? 6 : 5 );*/ } } /// <summary> /// Gets the maxmimum amount of characters that this account can hold. /// </summary> public int Length { get { return m_Mobiles.Length; } } /// <summary> /// Gets or sets the character at a specified index for this account. Out of bound index values are handled; null returned for get, ignored for set. /// </summary> public Mobile this[int index] { get { if ( index >= 0 && index < m_Mobiles.Length ) { Mobile m = m_Mobiles[index]; if ( m != null && m.Deleted ) { m.Account = null; m_Mobiles[index] = m = null; } return m; } return null; } set { if ( index >= 0 && index < m_Mobiles.Length ) { if ( m_Mobiles[index] != null ) m_Mobiles[index].Account = null; m_Mobiles[index] = value; if ( m_Mobiles[index] != null ) m_Mobiles[index].Account = this; } } } public override string ToString() { return m_Username; } public int CompareTo( Account other ) { if ( other == null ) return 1; return m_Username.CompareTo( other.m_Username ); } public int CompareTo(IAccount other) { if (other == null) return 1; return m_Username.CompareTo(other.Username); } public int CompareTo( object obj ) { if ( obj is Account ) return this.CompareTo( (Account) obj ); throw new ArgumentException(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Batch; using Microsoft.Azure.Management.Batch.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Batch { public partial class BatchManagementClient : ServiceClient<BatchManagementClient>, IBatchManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IAccountOperations _accounts; /// <summary> /// Operations for managing batch accounts /// </summary> public virtual IAccountOperations Accounts { get { return this._accounts; } } private IApplicationOperations _applications; /// <summary> /// Operations for managing applications. /// </summary> public virtual IApplicationOperations Applications { get { return this._applications; } } private ISubscriptionOperations _subscriptions; /// <summary> /// Operations for managing Batch service properties at the /// subscription level. /// </summary> public virtual ISubscriptionOperations Subscriptions { get { return this._subscriptions; } } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> public BatchManagementClient() : base() { this._accounts = new AccountOperations(this); this._applications = new ApplicationOperations(this); this._subscriptions = new SubscriptionOperations(this); this._apiVersion = "2015-12-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public BatchManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public BatchManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public BatchManagementClient(HttpClient httpClient) : base(httpClient) { this._accounts = new AccountOperations(this); this._applications = new ApplicationOperations(this); this._subscriptions = new SubscriptionOperations(this); this._apiVersion = "2015-12-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public BatchManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the BatchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public BatchManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// BatchManagementClient instance /// </summary> /// <param name='client'> /// Instance of BatchManagementClient to clone to /// </param> protected override void Clone(ServiceClient<BatchManagementClient> client) { base.Clone(client); if (client is BatchManagementClient) { BatchManagementClient clonedClient = ((BatchManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type PackageState. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static PackageState ParsePackageState(string value) { if ("pending".Equals(value, StringComparison.OrdinalIgnoreCase)) { return PackageState.Pending; } if ("active".Equals(value, StringComparison.OrdinalIgnoreCase)) { return PackageState.Active; } if ("unmapped".Equals(value, StringComparison.OrdinalIgnoreCase)) { return PackageState.Unmapped; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type PackageState to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string PackageStateToString(PackageState value) { if (value == PackageState.Pending) { return "pending"; } if (value == PackageState.Active) { return "active"; } if (value == PackageState.Unmapped) { return "unmapped"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// The Get Account Create Operation Status operation returns the /// status of the account creation operation. After calling an /// asynchronous operation, you can call this method to determine /// whether the operation has succeeded, failed, or is still in /// progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the BeginCreating operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Values returned by the Create operation. /// </returns> public async Task<BatchAccountCreateResponse> GetAccountCreateOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetAccountCreateOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-12-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result BatchAccountCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new BatchAccountCreateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AccountResource resourceInstance = new AccountResource(); result.Resource = resourceInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); resourceInstance.Id = idInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); resourceInstance.Type = typeInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); resourceInstance.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); resourceInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); resourceInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { AccountProperties propertiesInstance = new AccountProperties(); resourceInstance.Properties = propertiesInstance; JToken accountEndpointValue = propertiesValue["accountEndpoint"]; if (accountEndpointValue != null && accountEndpointValue.Type != JTokenType.Null) { string accountEndpointInstance = ((string)accountEndpointValue); propertiesInstance.AccountEndpoint = accountEndpointInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { AccountProvisioningState provisioningStateInstance = ((AccountProvisioningState)Enum.Parse(typeof(AccountProvisioningState), ((string)provisioningStateValue), true)); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken autoStorageValue = propertiesValue["autoStorage"]; if (autoStorageValue != null && autoStorageValue.Type != JTokenType.Null) { AutoStorageProperties autoStorageInstance = new AutoStorageProperties(); propertiesInstance.AutoStorage = autoStorageInstance; JToken storageAccountIdValue = autoStorageValue["storageAccountId"]; if (storageAccountIdValue != null && storageAccountIdValue.Type != JTokenType.Null) { string storageAccountIdInstance = ((string)storageAccountIdValue); autoStorageInstance.StorageAccountId = storageAccountIdInstance; } JToken lastKeySyncValue = autoStorageValue["lastKeySync"]; if (lastKeySyncValue != null && lastKeySyncValue.Type != JTokenType.Null) { DateTime lastKeySyncInstance = ((DateTime)lastKeySyncValue); autoStorageInstance.LastKeySync = lastKeySyncInstance; } } JToken coreQuotaValue = propertiesValue["coreQuota"]; if (coreQuotaValue != null && coreQuotaValue.Type != JTokenType.Null) { int coreQuotaInstance = ((int)coreQuotaValue); propertiesInstance.CoreQuota = coreQuotaInstance; } JToken poolQuotaValue = propertiesValue["poolQuota"]; if (poolQuotaValue != null && poolQuotaValue.Type != JTokenType.Null) { int poolQuotaInstance = ((int)poolQuotaValue); propertiesInstance.PoolQuota = poolQuotaInstance; } JToken activeJobAndJobScheduleQuotaValue = propertiesValue["activeJobAndJobScheduleQuota"]; if (activeJobAndJobScheduleQuotaValue != null && activeJobAndJobScheduleQuotaValue.Type != JTokenType.Null) { int activeJobAndJobScheduleQuotaInstance = ((int)activeJobAndJobScheduleQuotaValue); propertiesInstance.ActiveJobAndJobScheduleQuota = activeJobAndJobScheduleQuotaInstance; } } BatchManagementError errorInstance = new BatchManagementError(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (result.Resource != null && result.Resource.Properties != null && result.Resource.Properties.ProvisioningState == AccountProvisioningState.Succeeded) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Delete Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Delete Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the BeginDeleting operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> GetAccountDeleteOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetAccountDeleteOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-12-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NotFound) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NotFound) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A piece of sculpture. /// </summary> public class Sculpture_Core : TypeCore, ICreativeWork { public Sculpture_Core() { this._TypeId = 235; this._Id = "Sculpture"; this._Schema_Org_Url = "http://schema.org/Sculpture"; string label = ""; GetLabel(out label, "Sculpture", typeof(Sculpture_Core)); this._Label = label; this._Ancestors = new int[]{266,78}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{78}; this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231}; } /// <summary> /// The subject matter of the content. /// </summary> private About_Core about; public About_Core About { get { return about; } set { about = value; SetPropertyInstance(about); } } /// <summary> /// Specifies the Person that is legally accountable for the CreativeWork. /// </summary> private AccountablePerson_Core accountablePerson; public AccountablePerson_Core AccountablePerson { get { return accountablePerson; } set { accountablePerson = value; SetPropertyInstance(accountablePerson); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// A secondary title of the CreativeWork. /// </summary> private AlternativeHeadline_Core alternativeHeadline; public AlternativeHeadline_Core AlternativeHeadline { get { return alternativeHeadline; } set { alternativeHeadline = value; SetPropertyInstance(alternativeHeadline); } } /// <summary> /// The media objects that encode this creative work. This property is a synonym for encodings. /// </summary> private AssociatedMedia_Core associatedMedia; public AssociatedMedia_Core AssociatedMedia { get { return associatedMedia; } set { associatedMedia = value; SetPropertyInstance(associatedMedia); } } /// <summary> /// An embedded audio object. /// </summary> private Audio_Core audio; public Audio_Core Audio { get { return audio; } set { audio = value; SetPropertyInstance(audio); } } /// <summary> /// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely. /// </summary> private Author_Core author; public Author_Core Author { get { return author; } set { author = value; SetPropertyInstance(author); } } /// <summary> /// Awards won by this person or for this creative work. /// </summary> private Awards_Core awards; public Awards_Core Awards { get { return awards; } set { awards = value; SetPropertyInstance(awards); } } /// <summary> /// Comments, typically from users, on this CreativeWork. /// </summary> private Comment_Core comment; public Comment_Core Comment { get { return comment; } set { comment = value; SetPropertyInstance(comment); } } /// <summary> /// The location of the content. /// </summary> private ContentLocation_Core contentLocation; public ContentLocation_Core ContentLocation { get { return contentLocation; } set { contentLocation = value; SetPropertyInstance(contentLocation); } } /// <summary> /// Official rating of a piece of content\u2014for example,'MPAA PG-13'. /// </summary> private ContentRating_Core contentRating; public ContentRating_Core ContentRating { get { return contentRating; } set { contentRating = value; SetPropertyInstance(contentRating); } } /// <summary> /// A secondary contributor to the CreativeWork. /// </summary> private Contributor_Core contributor; public Contributor_Core Contributor { get { return contributor; } set { contributor = value; SetPropertyInstance(contributor); } } /// <summary> /// The party holding the legal copyright to the CreativeWork. /// </summary> private CopyrightHolder_Core copyrightHolder; public CopyrightHolder_Core CopyrightHolder { get { return copyrightHolder; } set { copyrightHolder = value; SetPropertyInstance(copyrightHolder); } } /// <summary> /// The year during which the claimed copyright for the CreativeWork was first asserted. /// </summary> private CopyrightYear_Core copyrightYear; public CopyrightYear_Core CopyrightYear { get { return copyrightYear; } set { copyrightYear = value; SetPropertyInstance(copyrightYear); } } /// <summary> /// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. /// </summary> private Creator_Core creator; public Creator_Core Creator { get { return creator; } set { creator = value; SetPropertyInstance(creator); } } /// <summary> /// The date on which the CreativeWork was created. /// </summary> private DateCreated_Core dateCreated; public DateCreated_Core DateCreated { get { return dateCreated; } set { dateCreated = value; SetPropertyInstance(dateCreated); } } /// <summary> /// The date on which the CreativeWork was most recently modified. /// </summary> private DateModified_Core dateModified; public DateModified_Core DateModified { get { return dateModified; } set { dateModified = value; SetPropertyInstance(dateModified); } } /// <summary> /// Date of first broadcast/publication. /// </summary> private DatePublished_Core datePublished; public DatePublished_Core DatePublished { get { return datePublished; } set { datePublished = value; SetPropertyInstance(datePublished); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// A link to the page containing the comments of the CreativeWork. /// </summary> private DiscussionURL_Core discussionURL; public DiscussionURL_Core DiscussionURL { get { return discussionURL; } set { discussionURL = value; SetPropertyInstance(discussionURL); } } /// <summary> /// Specifies the Person who edited the CreativeWork. /// </summary> private Editor_Core editor; public Editor_Core Editor { get { return editor; } set { editor = value; SetPropertyInstance(editor); } } /// <summary> /// The media objects that encode this creative work /// </summary> private Encodings_Core encodings; public Encodings_Core Encodings { get { return encodings; } set { encodings = value; SetPropertyInstance(encodings); } } /// <summary> /// Genre of the creative work /// </summary> private Genre_Core genre; public Genre_Core Genre { get { return genre; } set { genre = value; SetPropertyInstance(genre); } } /// <summary> /// Headline of the article /// </summary> private Headline_Core headline; public Headline_Core Headline { get { return headline; } set { headline = value; SetPropertyInstance(headline); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a> /// </summary> private InLanguage_Core inLanguage; public InLanguage_Core InLanguage { get { return inLanguage; } set { inLanguage = value; SetPropertyInstance(inLanguage); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// Indicates whether this content is family friendly. /// </summary> private IsFamilyFriendly_Core isFamilyFriendly; public IsFamilyFriendly_Core IsFamilyFriendly { get { return isFamilyFriendly; } set { isFamilyFriendly = value; SetPropertyInstance(isFamilyFriendly); } } /// <summary> /// The keywords/tags used to describe this content. /// </summary> private Keywords_Core keywords; public Keywords_Core Keywords { get { return keywords; } set { keywords = value; SetPropertyInstance(keywords); } } /// <summary> /// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. /// </summary> private Mentions_Core mentions; public Mentions_Core Mentions { get { return mentions; } set { mentions = value; SetPropertyInstance(mentions); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// Specifies the Person or Organization that distributed the CreativeWork. /// </summary> private Provider_Core provider; public Provider_Core Provider { get { return provider; } set { provider = value; SetPropertyInstance(provider); } } /// <summary> /// The publisher of the creative work. /// </summary> private Publisher_Core publisher; public Publisher_Core Publisher { get { return publisher; } set { publisher = value; SetPropertyInstance(publisher); } } /// <summary> /// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. /// </summary> private PublishingPrinciples_Core publishingPrinciples; public PublishingPrinciples_Core PublishingPrinciples { get { return publishingPrinciples; } set { publishingPrinciples = value; SetPropertyInstance(publishingPrinciples); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The Organization on whose behalf the creator was working. /// </summary> private SourceOrganization_Core sourceOrganization; public SourceOrganization_Core SourceOrganization { get { return sourceOrganization; } set { sourceOrganization = value; SetPropertyInstance(sourceOrganization); } } /// <summary> /// A thumbnail image relevant to the Thing. /// </summary> private ThumbnailURL_Core thumbnailURL; public ThumbnailURL_Core ThumbnailURL { get { return thumbnailURL; } set { thumbnailURL = value; SetPropertyInstance(thumbnailURL); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } /// <summary> /// The version of the CreativeWork embodied by a specified resource. /// </summary> private Version_Core version; public Version_Core Version { get { return version; } set { version = value; SetPropertyInstance(version); } } /// <summary> /// An embedded video object. /// </summary> private Video_Core video; public Video_Core Video { get { return video; } set { video = value; SetPropertyInstance(video); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Runtime; using System.ServiceModel; using System.Threading; class BufferedConnection : DelegatingConnection { byte[] writeBuffer; int writeBufferSize; int pendingWriteSize; Exception pendingWriteException; IOThreadTimer flushTimer; long flushTimeout; TimeSpan pendingTimeout; const int maxFlushSkew = 100; public BufferedConnection(IConnection connection, TimeSpan flushTimeout, int writeBufferSize) : base(connection) { this.flushTimeout = Ticks.FromTimeSpan(flushTimeout); this.writeBufferSize = writeBufferSize; } object ThisLock { get { return this; } } public override void Close(TimeSpan timeout, bool asyncAndLinger) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); Flush(timeoutHelper.RemainingTime()); base.Close(timeoutHelper.RemainingTime(), asyncAndLinger); } void CancelFlushTimer() { if (flushTimer != null) { flushTimer.Cancel(); pendingTimeout = TimeSpan.Zero; } } void Flush(TimeSpan timeout) { ThrowPendingWriteException(); lock (ThisLock) { FlushCore(timeout); } } void FlushCore(TimeSpan timeout) { if (pendingWriteSize > 0) { ThreadTrace.Trace("BC:Flush"); Connection.Write(writeBuffer, 0, pendingWriteSize, false, timeout); pendingWriteSize = 0; } } void OnFlushTimer(object state) { ThreadTrace.Trace("BC:Flush timer"); lock (ThisLock) { try { FlushCore(pendingTimeout); pendingTimeout = TimeSpan.Zero; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } pendingWriteException = e; CancelFlushTimer(); } } } void SetFlushTimer() { if (this.flushTimer == null) { int flushSkew = Ticks.ToMilliseconds(Math.Min(this.flushTimeout / 10, Ticks.FromMilliseconds(maxFlushSkew))); this.flushTimer = new IOThreadTimer(new Action<object>(OnFlushTimer), null, true, flushSkew); } this.flushTimer.Set(Ticks.ToTimeSpan(this.flushTimeout)); } public override void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager) { if (size <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("size", size, SR.GetString( SR.ValueMustBePositive))); } ThrowPendingWriteException(); if (immediate || flushTimeout == 0) { ThreadTrace.Trace("BC:Write now"); WriteNow(buffer, offset, size, timeout, bufferManager); } else { ThreadTrace.Trace("BC:Write later"); WriteLater(buffer, offset, size, timeout); bufferManager.ReturnBuffer(buffer); } ThreadTrace.Trace("BC:Write done"); } public override void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout) { if (size <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("size", size, SR.GetString( SR.ValueMustBePositive))); } ThrowPendingWriteException(); if (immediate || flushTimeout == 0) { ThreadTrace.Trace("BC:Write now"); WriteNow(buffer, offset, size, timeout); } else { ThreadTrace.Trace("BC:Write later"); WriteLater(buffer, offset, size, timeout); } ThreadTrace.Trace("BC:Write done"); } void WriteNow(byte[] buffer, int offset, int size, TimeSpan timeout) { WriteNow(buffer, offset, size, timeout, null); } void WriteNow(byte[] buffer, int offset, int size, TimeSpan timeout, BufferManager bufferManager) { lock (ThisLock) { if (pendingWriteSize > 0) { int remainingSize = writeBufferSize - pendingWriteSize; CancelFlushTimer(); if (size <= remainingSize) { Buffer.BlockCopy(buffer, offset, writeBuffer, pendingWriteSize, size); if (bufferManager != null) { bufferManager.ReturnBuffer(buffer); } pendingWriteSize += size; FlushCore(timeout); return; } else { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); FlushCore(timeoutHelper.RemainingTime()); timeout = timeoutHelper.RemainingTime(); } } if (bufferManager == null) { Connection.Write(buffer, offset, size, true, timeout); } else { Connection.Write(buffer, offset, size, true, timeout, bufferManager); } } } void WriteLater(byte[] buffer, int offset, int size, TimeSpan timeout) { lock (ThisLock) { bool setTimer = (pendingWriteSize == 0); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); while (size > 0) { if (size >= writeBufferSize && pendingWriteSize == 0) { Connection.Write(buffer, offset, size, false, timeoutHelper.RemainingTime()); size = 0; } else { if (writeBuffer == null) { writeBuffer = DiagnosticUtility.Utility.AllocateByteArray(writeBufferSize); } int remainingSize = writeBufferSize - pendingWriteSize; int copySize = size; if (copySize > remainingSize) { copySize = remainingSize; } Buffer.BlockCopy(buffer, offset, writeBuffer, pendingWriteSize, copySize); pendingWriteSize += copySize; if (pendingWriteSize == writeBufferSize) { FlushCore(timeoutHelper.RemainingTime()); setTimer = true; } size -= copySize; offset += copySize; } } if (pendingWriteSize > 0) { if (setTimer) { SetFlushTimer(); pendingTimeout = TimeoutHelper.Add(pendingTimeout, timeoutHelper.RemainingTime()); } } else { CancelFlushTimer(); } } } public override AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, WaitCallback callback, object state) { ThreadTrace.Trace("BC:BeginWrite"); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); Flush(timeoutHelper.RemainingTime()); return base.BeginWrite(buffer, offset, size, immediate, timeoutHelper.RemainingTime(), callback, state); } public override void EndWrite() { ThreadTrace.Trace("BC:EndWrite"); base.EndWrite(); } public override void Shutdown(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); Flush(timeoutHelper.RemainingTime()); base.Shutdown(timeoutHelper.RemainingTime()); } void ThrowPendingWriteException() { if (pendingWriteException != null) { lock (ThisLock) { if (pendingWriteException != null) { Exception exceptionTothrow = pendingWriteException; pendingWriteException = null; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionTothrow); } } } } } class BufferedConnectionInitiator : IConnectionInitiator { int writeBufferSize; TimeSpan flushTimeout; IConnectionInitiator connectionInitiator; public BufferedConnectionInitiator(IConnectionInitiator connectionInitiator, TimeSpan flushTimeout, int writeBufferSize) { this.connectionInitiator = connectionInitiator; this.flushTimeout = flushTimeout; this.writeBufferSize = writeBufferSize; } protected TimeSpan FlushTimeout { get { return this.flushTimeout; } } protected int WriteBufferSize { get { return this.writeBufferSize; } } public IConnection Connect(Uri uri, TimeSpan timeout) { return new BufferedConnection(connectionInitiator.Connect(uri, timeout), flushTimeout, writeBufferSize); } public IAsyncResult BeginConnect(Uri uri, TimeSpan timeout, AsyncCallback callback, object state) { return connectionInitiator.BeginConnect(uri, timeout, callback, state); } public IConnection EndConnect(IAsyncResult result) { return new BufferedConnection(connectionInitiator.EndConnect(result), flushTimeout, writeBufferSize); } } class BufferedConnectionListener : IConnectionListener { int writeBufferSize; TimeSpan flushTimeout; IConnectionListener connectionListener; public BufferedConnectionListener(IConnectionListener connectionListener, TimeSpan flushTimeout, int writeBufferSize) { this.connectionListener = connectionListener; this.flushTimeout = flushTimeout; this.writeBufferSize = writeBufferSize; } public void Dispose() { connectionListener.Dispose(); } public void Listen() { connectionListener.Listen(); } public IAsyncResult BeginAccept(AsyncCallback callback, object state) { return connectionListener.BeginAccept(callback, state); } public IConnection EndAccept(IAsyncResult result) { IConnection connection = connectionListener.EndAccept(result); if (connection == null) { return connection; } return new BufferedConnection(connection, flushTimeout, writeBufferSize); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.AspNetCore.Razor.TagHelpers { public enum CustomEnum { FirstValue, SecondValue } public class EnumTagHelper : TagHelper { public int NonEnumProperty { get; set; } public CustomEnum EnumProperty { get; set; } } [HtmlTargetElement("p")] [HtmlTargetElement("input")] public class MultiEnumTagHelper : EnumTagHelper { } [HtmlTargetElement("input", ParentTag = "div")] public class RequiredParentTagHelper : TagHelper { } [HtmlTargetElement("p", ParentTag = "div")] [HtmlTargetElement("input", ParentTag = "section")] public class MultiSpecifiedRequiredParentTagHelper : TagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("input", ParentTag = "div")] public class MultiWithUnspecifiedRequiredParentTagHelper : TagHelper { } [RestrictChildren("p")] public class RestrictChildrenTagHelper { } [RestrictChildren("p", "strong")] public class DoubleRestrictChildrenTagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("div")] [RestrictChildren("p", "strong")] public class MultiTargetRestrictChildrenTagHelper { } [HtmlTargetElement("input", TagStructure = TagStructure.WithoutEndTag)] public class TagStructureTagHelper : TagHelper { } [HtmlTargetElement("p", TagStructure = TagStructure.NormalOrSelfClosing)] [HtmlTargetElement("input", TagStructure = TagStructure.WithoutEndTag)] public class MultiSpecifiedTagStructureTagHelper : TagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("input", TagStructure = TagStructure.WithoutEndTag)] public class MultiWithUnspecifiedTagStructureTagHelper : TagHelper { } [EditorBrowsable(EditorBrowsableState.Always)] public class DefaultEditorBrowsableTagHelper : TagHelper { [EditorBrowsable(EditorBrowsableState.Always)] public int Property { get; set; } } public class HiddenPropertyEditorBrowsableTagHelper : TagHelper { [EditorBrowsable(EditorBrowsableState.Never)] public int Property { get; set; } } public class MultiPropertyEditorBrowsableTagHelper : TagHelper { [EditorBrowsable(EditorBrowsableState.Never)] public int Property { get; set; } public virtual int Property2 { get; set; } } public class OverriddenPropertyEditorBrowsableTagHelper : MultiPropertyEditorBrowsableTagHelper { [EditorBrowsable(EditorBrowsableState.Never)] public override int Property2 { get; set; } } [EditorBrowsable(EditorBrowsableState.Never)] public class EditorBrowsableTagHelper : TagHelper { [EditorBrowsable(EditorBrowsableState.Never)] public virtual int Property { get; set; } } public class InheritedEditorBrowsableTagHelper : EditorBrowsableTagHelper { public override int Property { get; set; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public class OverriddenEditorBrowsableTagHelper : EditorBrowsableTagHelper { [EditorBrowsable(EditorBrowsableState.Advanced)] public override int Property { get; set; } } [HtmlTargetElement("p")] [HtmlTargetElement("div")] [EditorBrowsable(EditorBrowsableState.Never)] public class MultiEditorBrowsableTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "class*")] public class AttributeWildcardTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "class*,style*")] public class MultiAttributeWildcardTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "class")] public class AttributeTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "class,style")] public class MultiAttributeTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "custom")] [HtmlTargetElement(Attributes = "class,style")] public class MultiAttributeAttributeTargetingTagHelper : TagHelper { } [HtmlTargetElement(Attributes = "style")] public class InheritedAttributeTargetingTagHelper : AttributeTargetingTagHelper { } [HtmlTargetElement("input", Attributes = "class")] public class RequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("div", Attributes = "class")] public class InheritedRequiredAttributeTagHelper : RequiredAttributeTagHelper { } [HtmlTargetElement("div", Attributes = "class")] [HtmlTargetElement("input", Attributes = "class")] public class MultiAttributeRequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("input", Attributes = "style")] [HtmlTargetElement("input", Attributes = "class")] public class MultiAttributeSameTagRequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("input", Attributes = "class,style")] public class MultiRequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("div", Attributes = "style")] public class InheritedMultiRequiredAttributeTagHelper : MultiRequiredAttributeTagHelper { } [HtmlTargetElement("div", Attributes = "class,style")] [HtmlTargetElement("input", Attributes = "class,style")] public class MultiTagMultiRequiredAttributeTagHelper : TagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("div")] public class MultiTagTagHelper { public string ValidAttribute { get; set; } } public class InheritedMultiTagTagHelper : MultiTagTagHelper { } [HtmlTargetElement("p")] [HtmlTargetElement("p")] [HtmlTargetElement("div")] [HtmlTargetElement("div")] public class DuplicateTagNameTagHelper { } [HtmlTargetElement("data-condition")] public class OverrideNameTagHelper { } public class InheritedSingleAttributeTagHelper : SingleAttributeTagHelper { } public class DuplicateAttributeNameTagHelper { public string MyNameIsLegion { get; set; } [HtmlAttributeName("my-name-is-legion")] public string Fred { get; set; } } public class NotBoundAttributeTagHelper { public object BoundProperty { get; set; } [HtmlAttributeNotBound] public string NotBoundProperty { get; set; } [HtmlAttributeName("unused")] [HtmlAttributeNotBound] public string NamedNotBoundProperty { get; set; } } public class OverriddenAttributeTagHelper { [HtmlAttributeName("SomethingElse")] public virtual string ValidAttribute1 { get; set; } [HtmlAttributeName("Something-Else")] public string ValidAttribute2 { get; set; } } public class InheritedOverriddenAttributeTagHelper : OverriddenAttributeTagHelper { public override string ValidAttribute1 { get; set; } } public class InheritedNotOverriddenAttributeTagHelper : OverriddenAttributeTagHelper { } public class ALLCAPSTAGHELPER : TagHelper { public int ALLCAPSATTRIBUTE { get; set; } } public class CAPSOnOUTSIDETagHelper : TagHelper { public int CAPSOnOUTSIDEATTRIBUTE { get; set; } } public class capsONInsideTagHelper : TagHelper { public int capsONInsideattribute { get; set; } } public class One1Two2Three3TagHelper : TagHelper { public int One1Two2Three3Attribute { get; set; } } public class ONE1TWO2THREE3TagHelper : TagHelper { public int ONE1TWO2THREE3Attribute { get; set; } } public class First_Second_ThirdHiTagHelper : TagHelper { public int First_Second_ThirdAttribute { get; set; } } public class UNSuffixedCLASS : TagHelper { public int UNSuffixedATTRIBUTE { get; set; } } public class InvalidBoundAttribute : TagHelper { public string DataSomething { get; set; } } public class InvalidBoundAttributeWithValid : SingleAttributeTagHelper { public string DataSomething { get; set; } } public class OverriddenInvalidBoundAttributeWithValid : TagHelper { [HtmlAttributeName("valid-something")] public string DataSomething { get; set; } } public class OverriddenValidBoundAttributeWithInvalid : TagHelper { [HtmlAttributeName("data-something")] public string ValidSomething { get; set; } } public class OverriddenValidBoundAttributeWithInvalidUpperCase : TagHelper { [HtmlAttributeName("DATA-SOMETHING")] public string ValidSomething { get; set; } } public class DefaultValidHtmlAttributePrefix : TagHelper { public IDictionary<string, string> DictionaryProperty { get; set; } } public class SingleValidHtmlAttributePrefix : TagHelper { [HtmlAttributeName("valid-name")] public IDictionary<string, string> DictionaryProperty { get; set; } } public class MultipleValidHtmlAttributePrefix : TagHelper { [HtmlAttributeName("valid-name1", DictionaryAttributePrefix = "valid-prefix1-")] public Dictionary<string, object> DictionaryProperty { get; set; } [HtmlAttributeName("valid-name2", DictionaryAttributePrefix = "valid-prefix2-")] public DictionarySubclass DictionarySubclassProperty { get; set; } [HtmlAttributeName("valid-name3", DictionaryAttributePrefix = "valid-prefix3-")] public DictionaryWithoutParameterlessConstructor DictionaryWithoutParameterlessConstructorProperty { get; set; } [HtmlAttributeName("valid-name4", DictionaryAttributePrefix = "valid-prefix4-")] public GenericDictionarySubclass<object> GenericDictionarySubclassProperty { get; set; } [HtmlAttributeName("valid-name5", DictionaryAttributePrefix = "valid-prefix5-")] public SortedDictionary<string, int> SortedDictionaryProperty { get; set; } [HtmlAttributeName("valid-name6")] public string StringProperty { get; set; } public IDictionary<string, int> GetOnlyDictionaryProperty { get; } [HtmlAttributeName(DictionaryAttributePrefix = "valid-prefix6")] public IDictionary<string, string> GetOnlyDictionaryPropertyWithAttributePrefix { get; } } public class SingleInvalidHtmlAttributePrefix : TagHelper { [HtmlAttributeName("valid-name", DictionaryAttributePrefix = "valid-prefix")] public string StringProperty { get; set; } } public class MultipleInvalidHtmlAttributePrefix : TagHelper { [HtmlAttributeName("valid-name1")] public long LongProperty { get; set; } [HtmlAttributeName("valid-name2", DictionaryAttributePrefix = "valid-prefix2-")] public Dictionary<int, string> DictionaryOfIntProperty { get; set; } [HtmlAttributeName("valid-name3", DictionaryAttributePrefix = "valid-prefix3-")] public IReadOnlyDictionary<string, object> ReadOnlyDictionaryProperty { get; set; } [HtmlAttributeName("valid-name4", DictionaryAttributePrefix = "valid-prefix4-")] public int IntProperty { get; set; } [HtmlAttributeName("valid-name5", DictionaryAttributePrefix = "valid-prefix5-")] public DictionaryOfIntSubclass DictionaryOfIntSubclassProperty { get; set; } [HtmlAttributeName(DictionaryAttributePrefix = "valid-prefix6")] public IDictionary<int, string> GetOnlyDictionaryAttributePrefix { get; } [HtmlAttributeName("invalid-name7")] public IDictionary<string, object> GetOnlyDictionaryPropertyWithAttributeName { get; } } public class DictionarySubclass : Dictionary<string, string> { } public class DictionaryWithoutParameterlessConstructor : Dictionary<string, string> { public DictionaryWithoutParameterlessConstructor(int count) : base() { } } public class DictionaryOfIntSubclass : Dictionary<int, string> { } public class GenericDictionarySubclass<TValue> : Dictionary<string, TValue> { } [OutputElementHint("strong")] public class OutputElementHintTagHelper : TagHelper { } [HtmlTargetElement("a")] [HtmlTargetElement("p")] [OutputElementHint("div")] public class MulitpleDescriptorTagHelperWithOutputElementHint : TagHelper { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Text; using CFStringRef = System.IntPtr; using FSEventStreamRef = System.IntPtr; using size_t = System.IntPtr; using FSEventStreamEventId = System.UInt64; using FSEventStreamEventFlags = Interop.EventStream.FSEventStreamEventFlags; using CFRunLoopRef = System.IntPtr; using Microsoft.Win32.SafeHandles; namespace System.IO { public partial class FileSystemWatcher { /// <summary>Called when FileSystemWatcher is finalized.</summary> private void FinalizeDispose() { // Make sure we cleanup StopRaisingEvents(); } private void StartRaisingEvents() { // If we're called when "Initializing" is true, set enabled to true if (IsSuspended()) { _enabled = true; return; } // Don't start another instance if one is already runnings if (_cancellation != null) { return; } try { CancellationTokenSource cancellation = new CancellationTokenSource(); RunningInstance instance = new RunningInstance(this, _directory, _includeSubdirectories, TranslateFlags(_notifyFilters), cancellation.Token); _enabled = true; _cancellation = cancellation; instance.Start(); } catch { _enabled = false; _cancellation = null; throw; } } private void StopRaisingEvents() { _enabled = false; if (IsSuspended()) return; CancellationTokenSource token = _cancellation; if (token != null) { _cancellation = null; token.Cancel(); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private CancellationTokenSource _cancellation; private static FSEventStreamEventFlags TranslateFlags(NotifyFilters flagsToTranslate) { FSEventStreamEventFlags flags = 0; // Always re-create the filter flags when start is called since they could have changed if ((flagsToTranslate & (NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size)) != 0) { flags = FSEventStreamEventFlags.kFSEventStreamEventFlagItemInodeMetaMod | FSEventStreamEventFlags.kFSEventStreamEventFlagItemFinderInfoMod | FSEventStreamEventFlags.kFSEventStreamEventFlagItemModified | FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner; } if ((flagsToTranslate & NotifyFilters.Security) != 0) { flags |= FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner | FSEventStreamEventFlags.kFSEventStreamEventFlagItemXattrMod; } if ((flagsToTranslate & NotifyFilters.DirectoryName) != 0) { flags |= FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir | FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated | FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved | FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed; } if ((flagsToTranslate & NotifyFilters.FileName) != 0) { flags |= FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile | FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated | FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved | FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed; } return flags; } private sealed class RunningInstance { // Flags used to create the event stream private const Interop.EventStream.FSEventStreamCreateFlags EventStreamFlags = (Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagFileEvents | Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagNoDefer | Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagWatchRoot); // Weak reference to the associated watcher. A weak reference is used so that the FileSystemWatcher may be collected and finalized, // causing an active operation to be torn down. private readonly WeakReference<FileSystemWatcher> _weakWatcher; // The user can input relative paths, which can muck with our path comparisons. Save off the // actual full path so we can use it for comparing private string _fullDirectory; // Boolean if we allow events from nested folders private bool _includeChildren; // The bitmask of events that we want to send to the user private FSEventStreamEventFlags _filterFlags; // The EventStream to listen for events on private SafeEventStreamHandle _eventStream; // Callback delegate for the EventStream events private Interop.EventStream.FSEventStreamCallback _callback; // Token to monitor for cancellation requests, upon which processing is stopped and all // state is cleaned up. private readonly CancellationToken _cancellationToken; // Calling RunLoopStop multiple times SegFaults so protect the call to it private bool _stopping; private ExecutionContext _context; internal RunningInstance( FileSystemWatcher watcher, string directory, bool includeChildren, FSEventStreamEventFlags filter, CancellationToken cancelToken) { Debug.Assert(string.IsNullOrEmpty(directory) == false); Debug.Assert(!cancelToken.IsCancellationRequested); _weakWatcher = new WeakReference<FileSystemWatcher>(watcher); _fullDirectory = System.IO.Path.GetFullPath(directory); _includeChildren = includeChildren; _filterFlags = filter; _cancellationToken = cancelToken; _cancellationToken.UnsafeRegister(obj => ((RunningInstance)obj).CancellationCallback(), this); _stopping = false; } private static class StaticWatcherRunLoopManager { // A reference to the RunLoop that we can use to start or stop a Watcher private static CFRunLoopRef s_watcherRunLoop = IntPtr.Zero; private static int s_scheduledStreamsCount = 0; private static readonly object s_lockObject = new object(); public static void ScheduleEventStream(SafeEventStreamHandle eventStream) { lock (s_lockObject) { if (s_watcherRunLoop != IntPtr.Zero) { // Schedule the EventStream to run on the thread's RunLoop s_scheduledStreamsCount++; Interop.EventStream.FSEventStreamScheduleWithRunLoop(eventStream, s_watcherRunLoop, Interop.RunLoop.kCFRunLoopDefaultMode); return; } Debug.Assert(s_scheduledStreamsCount == 0); s_scheduledStreamsCount = 1; var runLoopStarted = new ManualResetEventSlim(); new Thread(WatchForFileSystemEventsThreadStart) { IsBackground = true }.Start(new object[] { runLoopStarted, eventStream }); runLoopStarted.Wait(); } } public static void UnscheduleFromRunLoop(SafeEventStreamHandle eventStream) { Debug.Assert(s_watcherRunLoop != IntPtr.Zero); lock (s_lockObject) { if (s_watcherRunLoop != IntPtr.Zero) { // Always unschedule the RunLoop before cleaning up Interop.EventStream.FSEventStreamUnscheduleFromRunLoop(eventStream, s_watcherRunLoop, Interop.RunLoop.kCFRunLoopDefaultMode); s_scheduledStreamsCount--; if (s_scheduledStreamsCount == 0) { // Stop the FS event message pump Interop.RunLoop.CFRunLoopStop(s_watcherRunLoop); s_watcherRunLoop = IntPtr.Zero; } } } } private static void WatchForFileSystemEventsThreadStart(object args) { var inputArgs = (object[])args; var runLoopStarted = (ManualResetEventSlim)inputArgs[0]; var _eventStream = (SafeEventStreamHandle)inputArgs[1]; // Get this thread's RunLoop IntPtr runLoop = Interop.RunLoop.CFRunLoopGetCurrent(); s_watcherRunLoop = runLoop; Debug.Assert(s_watcherRunLoop != IntPtr.Zero); // Retain the RunLoop so that it doesn't get moved or cleaned up before we're done with it. IntPtr retainResult = Interop.CoreFoundation.CFRetain(runLoop); Debug.Assert(retainResult == runLoop, "CFRetain is supposed to return the input value"); // Schedule the EventStream to run on the thread's RunLoop Interop.EventStream.FSEventStreamScheduleWithRunLoop(_eventStream, runLoop, Interop.RunLoop.kCFRunLoopDefaultMode); runLoopStarted.Set(); try { // Start the OS X RunLoop (a blocking call) that will pump file system changes into the callback function Interop.RunLoop.CFRunLoopRun(); } finally { lock (s_lockObject) { Interop.CoreFoundation.CFRelease(runLoop); } } } } private void CancellationCallback() { if (!_stopping && _eventStream != null) { _stopping = true; try { // When we get here, we've requested to stop so cleanup the EventStream and unschedule from the RunLoop Interop.EventStream.FSEventStreamStop(_eventStream); } finally { StaticWatcherRunLoopManager.UnscheduleFromRunLoop(_eventStream); } } } internal unsafe void Start() { // Make sure _fullPath doesn't contain a link or alias // since the OS will give back the actual, non link'd or alias'd paths _fullDirectory = Interop.Sys.RealPath(_fullDirectory); if (_fullDirectory == null) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } Debug.Assert(string.IsNullOrEmpty(_fullDirectory) == false, "Watch directory is null or empty"); // Normalize the _fullDirectory path to have a trailing slash if (_fullDirectory[_fullDirectory.Length - 1] != '/') { _fullDirectory += "/"; } // Get the path to watch and verify we created the CFStringRef SafeCreateHandle path = Interop.CoreFoundation.CFStringCreateWithCString(_fullDirectory); if (path.IsInvalid) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } // Take the CFStringRef and put it into an array to pass to the EventStream SafeCreateHandle arrPaths = Interop.CoreFoundation.CFArrayCreate(new CFStringRef[1] { path.DangerousGetHandle() }, (UIntPtr)1); if (arrPaths.IsInvalid) { path.Dispose(); throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } // Create the callback for the EventStream if it wasn't previously created for this instance. if (_callback == null) { _callback = new Interop.EventStream.FSEventStreamCallback(FileSystemEventCallback); } _context = ExecutionContext.Capture(); // Make sure the OS file buffer(s) are fully flushed so we don't get events from cached I/O Interop.Sys.Sync(); // Create the event stream for the path and tell the stream to watch for file system events. _eventStream = Interop.EventStream.FSEventStreamCreate( _callback, arrPaths, Interop.EventStream.kFSEventStreamEventIdSinceNow, 0.0f, EventStreamFlags); if (_eventStream.IsInvalid) { arrPaths.Dispose(); path.Dispose(); throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } StaticWatcherRunLoopManager.ScheduleEventStream(_eventStream); bool started = Interop.EventStream.FSEventStreamStart(_eventStream); if (!started) { // Try to get the Watcher to raise the error event; if we can't do that, just silently exit since the watcher is gone anyway FileSystemWatcher watcher; if (_weakWatcher.TryGetTarget(out watcher)) { // An error occurred while trying to start the run loop so fail out watcher.OnError(new ErrorEventArgs(new IOException(SR.EventStream_FailedToStart, Marshal.GetLastWin32Error()))); } } } private unsafe void FileSystemEventCallback( FSEventStreamRef streamRef, IntPtr clientCallBackInfo, size_t numEvents, byte** eventPaths, FSEventStreamEventFlags* eventFlags, FSEventStreamEventId* eventIds) { // Try to get the actual watcher from our weak reference. We maintain a weak reference most of the time // so as to avoid a rooted cycle that would prevent our processing loop from ever ending // if the watcher is dropped by the user without being disposed. If we can't get the watcher, // there's nothing more to do (we can't raise events), so bail. FileSystemWatcher watcher; if (!_weakWatcher.TryGetTarget(out watcher)) { CancellationCallback(); return; } ExecutionContext context = _context; if (context is null) { // Flow suppressed, just run here ProcessEvents(numEvents.ToInt32(), eventPaths, eventFlags, eventIds, watcher); } else { ExecutionContext.Run( context, (object o) => ((RunningInstance)o).ProcessEvents(numEvents.ToInt32(), eventPaths, eventFlags, eventIds, watcher), this); } } private unsafe void ProcessEvents(int numEvents, byte** eventPaths, FSEventStreamEventFlags* eventFlags, FSEventStreamEventId* eventIds, FileSystemWatcher watcher) { // Since renames come in pairs, when we find the first we need to search for the next one. Once we find it, we'll add it to this // list so when the for-loop comes across it, we'll skip it since it's already been processed as part of the original of the pair. List<FSEventStreamEventId> handledRenameEvents = null; Memory<char>[] events = new Memory<char>[numEvents]; ParseEvents(); for (int i = 0; i < numEvents; i++) { ReadOnlySpan<char> path = events[i].Span; Debug.Assert(path[path.Length - 1] != '/', "Trailing slashes on events is not supported"); // Match Windows and don't notify us about changes to the Root folder if (_fullDirectory.Length >= path.Length && path.Equals(_fullDirectory.AsSpan(0, path.Length), StringComparison.OrdinalIgnoreCase)) { continue; } WatcherChangeTypes eventType = 0; // First, we should check if this event should kick off a re-scan since we can't really rely on anything after this point if that is true if (ShouldRescanOccur(eventFlags[i])) { watcher.OnError(new ErrorEventArgs(new IOException(SR.FSW_BufferOverflow, (int)eventFlags[i]))); break; } else if ((handledRenameEvents != null) && (handledRenameEvents.Contains(eventIds[i]))) { // If this event is the second in a rename pair then skip it continue; } else if (CheckIfPathIsNested(path) && ((eventType = FilterEvents(eventFlags[i])) != 0)) { // The base FileSystemWatcher does a match check against the relative path before combining with // the root dir; however, null is special cased to signify the root dir, so check if we should use that. ReadOnlySpan<char> relativePath = ReadOnlySpan<char>.Empty; if (!path.Equals(_fullDirectory, StringComparison.OrdinalIgnoreCase)) { // Remove the root directory to get the relative path relativePath = path.Slice(_fullDirectory.Length); } // Raise a notification for the event if (((eventType & WatcherChangeTypes.Changed) > 0)) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, relativePath); } if (((eventType & WatcherChangeTypes.Created) > 0)) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, relativePath); } if (((eventType & WatcherChangeTypes.Deleted) > 0)) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, relativePath); } if (((eventType & WatcherChangeTypes.Renamed) > 0)) { // Find the rename that is paired to this rename, which should be the next rename in the list int pairedId = FindRenameChangePairedChange(i, eventFlags, numEvents); if (pairedId == int.MinValue) { // Getting here means we have a rename without a pair, meaning it should be a create for the // move from unwatched folder to watcher folder scenario or a move from the watcher folder out. // Check if the item exists on disk to check which it is // Don't send a new notification if we already sent one for this event. if (DoesItemExist(path, IsFlagSet(eventFlags[i], FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile))) { if ((eventType & WatcherChangeTypes.Created) == 0) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, relativePath); } } else if ((eventType & WatcherChangeTypes.Deleted) == 0) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, relativePath); } } else { // Remove the base directory prefix and add the paired event to the list of // events to skip and notify the user of the rename ReadOnlySpan<char> newPathRelativeName = events[pairedId].Span.Slice(_fullDirectory.Length); watcher.NotifyRenameEventArgs(WatcherChangeTypes.Renamed, newPathRelativeName, relativePath); // Create a new list, if necessary, and add the event if (handledRenameEvents == null) { handledRenameEvents = new List<FSEventStreamEventId>(); } handledRenameEvents.Add(eventIds[pairedId]); } } } ArraySegment<char> underlyingArray; if (MemoryMarshal.TryGetArray(events[i], out underlyingArray)) ArrayPool<char>.Shared.Return(underlyingArray.Array); } this._context = ExecutionContext.Capture(); void ParseEvents() { for (int i = 0; i < events.Length; i++) { int byteCount = 0; Debug.Assert(eventPaths[i] != null); byte* temp = eventPaths[i]; // Finds the position of null character. while (*temp != 0) { temp++; byteCount++; } Debug.Assert(byteCount > 0, "Empty events are not supported"); events[i] = new Memory<char>(ArrayPool<char>.Shared.Rent(Encoding.UTF8.GetMaxCharCount(byteCount))); int charCount; // Converting an array of bytes to UTF-8 char array charCount = Encoding.UTF8.GetChars(new ReadOnlySpan<byte>(eventPaths[i], byteCount), events[i].Span); events[i] = events[i].Slice(0, charCount); } } } /// <summary> /// Compares the given event flags to the filter flags and returns which event (if any) corresponds /// to those flags. /// </summary> private WatcherChangeTypes FilterEvents(FSEventStreamEventFlags eventFlags) { const FSEventStreamEventFlags changedFlags = FSEventStreamEventFlags.kFSEventStreamEventFlagItemInodeMetaMod | FSEventStreamEventFlags.kFSEventStreamEventFlagItemFinderInfoMod | FSEventStreamEventFlags.kFSEventStreamEventFlagItemModified | FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner | FSEventStreamEventFlags.kFSEventStreamEventFlagItemXattrMod; WatcherChangeTypes eventType = 0; // If any of the Changed flags are set in both Filter and Event then a Changed event has occurred. if (((_filterFlags & changedFlags) & (eventFlags & changedFlags)) > 0) { eventType |= WatcherChangeTypes.Changed; } // Notify created/deleted/renamed events if they pass through the filters bool allowDirs = (_filterFlags & FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir) > 0; bool allowFiles = (_filterFlags & FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile) > 0; bool isDir = (eventFlags & FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir) > 0; bool isFile = (eventFlags & FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile) > 0; bool eventIsCorrectType = (isDir && allowDirs) || (isFile && allowFiles); bool eventIsLink = (eventFlags & (FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsHardlink | FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsLastHardlink)) > 0; if (eventIsCorrectType || ((allowDirs || allowFiles) && (eventIsLink))) { // Notify Created/Deleted/Renamed events. if (IsFlagSet(eventFlags, FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed)) { eventType |= WatcherChangeTypes.Renamed; } if (IsFlagSet(eventFlags, FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated)) { eventType |= WatcherChangeTypes.Created; } if (IsFlagSet(eventFlags, FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved)) { eventType |= WatcherChangeTypes.Deleted; } } return eventType; } private bool ShouldRescanOccur(FSEventStreamEventFlags flags) { // Check if any bit is set that signals that the caller should rescan return (IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagMustScanSubDirs) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagUserDropped) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagKernelDropped) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagRootChanged) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagMount) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagUnmount)); } private bool CheckIfPathIsNested(ReadOnlySpan<char> eventPath) { // If we shouldn't include subdirectories, check if this path's parent is the watch directory // Check if the parent is the root. If so, then we'll continue processing based on the name. // If it isn't, then this will be set to false and we'll skip the name processing since it's irrelevant. return _includeChildren || _fullDirectory.AsSpan().StartsWith(System.IO.Path.GetDirectoryName(eventPath), StringComparison.OrdinalIgnoreCase); } private unsafe int FindRenameChangePairedChange( int currentIndex, FSEventStreamEventFlags* eventFlags, int numEvents) { // Start at one past the current index and try to find the next Rename item, which should be the old path. for (int i = currentIndex + 1; i < numEvents; i++) { if (IsFlagSet(eventFlags[i], FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed)) { // We found match, stop looking return i; } } return int.MinValue; } private static bool IsFlagSet(FSEventStreamEventFlags flags, FSEventStreamEventFlags value) { return (value & flags) == value; } private static bool DoesItemExist(ReadOnlySpan<char> path, bool isFile) { if (path.IsEmpty || path.Length == 0) return false; if (!isFile) return FileSystem.DirectoryExists(path); return PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? false : FileSystem.FileExists(path); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Avs; using Microsoft.Azure.Management.Avs.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; using System.Collections.Generic; using System.Linq; namespace Avs.Tests { public class WorkloadNetworksTests : TestBase { [Fact] public void WorkloadNetworksDhcp() { using var context = MockContext.Start(this.GetType()); string rgName = "wezamlyn-test-117"; string cloudName = "wezamlyn-test-117"; using var avsClient = context.GetServiceClient<AvsClient>(); // DHCP var dhcpId = "dhcpRelay"; List<string> serverAddressess = new List<string>() {"10.1.1.1", "10.1.1.2"}; var dhcpProperties = new WorkloadNetworkDhcpRelay(displayName: dhcpId, serverAddresses: serverAddressess); var dhcp = new WorkloadNetworkDhcp(properties: dhcpProperties); avsClient.WorkloadNetworks.CreateDhcp(rgName, cloudName, dhcpId, dhcp); avsClient.WorkloadNetworks.ListDhcp(rgName, cloudName); avsClient.WorkloadNetworks.GetDhcp(rgName, dhcpId, cloudName); dhcp.Properties.DisplayName = "modifiedDhcpRelay"; avsClient.WorkloadNetworks.UpdateDhcp(rgName, cloudName, dhcpId, dhcp); avsClient.WorkloadNetworks.DeleteDhcp(rgName, cloudName, dhcpId); } [Fact] public void WorkloadNetworksDns() { using var context = MockContext.Start(this.GetType()); string rgName = "wezamlyn-test-117"; string cloudName = "wezamlyn-test-117"; using var avsClient = context.GetServiceClient<AvsClient>(); // DNS Zones var defaultDnsZoneId = "defaultDnsZone"; var defaultDomain = new List<string>() {}; var defaultDnsServerIps = new List<string>() { "1.1.1.1" }; var defaultDnsZone = new WorkloadNetworkDnsZone(displayName: defaultDnsZoneId, domain: defaultDomain, dnsServerIps: defaultDnsServerIps); var resDefaultDnsZone = avsClient.WorkloadNetworks.CreateDnsZone(rgName, cloudName, defaultDnsZoneId, defaultDnsZone); // Get ARM ID for DNS Service var defaultDnsZoneIdSplit = resDefaultDnsZone.Id.Split("/"); var defaultDnsZoneArmId = defaultDnsZoneIdSplit[defaultDnsZoneIdSplit.Length-1]; var fqdnDnsZoneId = "fqdnDnsZone"; var fqdnDomain = new List<string>() { "fqdndnszone.com" }; var fqdnDnsServerIps = new List<string>() { "1.1.1.1" }; var fqdnDnsZone = new WorkloadNetworkDnsZone(displayName: fqdnDnsZoneId, domain: fqdnDomain, dnsServerIps: fqdnDnsServerIps); var resFqdnDnsZone = avsClient.WorkloadNetworks.CreateDnsZone(rgName, cloudName, fqdnDnsZoneId, fqdnDnsZone); // Get ARM ID for DNS Service var fqdnDnsZoneIdSplit = resFqdnDnsZone.Id.Split("/"); var fqdnDnsZoneArmId = fqdnDnsZoneIdSplit[fqdnDnsZoneIdSplit.Length-1]; avsClient.WorkloadNetworks.ListDnsZones(rgName, cloudName); avsClient.WorkloadNetworks.GetDnsZone(rgName, cloudName, defaultDnsZoneId); defaultDnsZone.DisplayName = "modifiedDnsZone"; avsClient.WorkloadNetworks.UpdateDnsZone(rgName, cloudName, defaultDnsZoneId, defaultDnsZone); // DNS Services var dnsServiceId = "dns-forwarder"; var dnsServiceIp = "5.5.5.5"; var logLevel = "INFO"; var dnsService = new WorkloadNetworkDnsService(displayName: dnsServiceId, dnsServiceIp: dnsServiceIp, logLevel: logLevel); dnsService.DefaultDnsZone = defaultDnsZoneArmId; dnsService.FqdnZones = new List<string>() { fqdnDnsZoneArmId }; avsClient.WorkloadNetworks.CreateDnsService(rgName, cloudName, dnsServiceId, dnsService); avsClient.WorkloadNetworks.ListDnsServices(rgName, cloudName); avsClient.WorkloadNetworks.GetDnsService(rgName, cloudName, dnsServiceId); dnsService.DisplayName = "modifiedDnsService"; avsClient.WorkloadNetworks.UpdateDnsService(rgName, cloudName, dnsServiceId, dnsService); avsClient.WorkloadNetworks.DeleteDnsService(rgName, dnsServiceId, cloudName); // Delete DNS Zones avsClient.WorkloadNetworks.DeleteDnsZone(rgName, defaultDnsZoneId, cloudName); avsClient.WorkloadNetworks.DeleteDnsZone(rgName, fqdnDnsZoneId, cloudName); } [Fact] public void WorkloadNetworksGatewaysSegments() { using var context = MockContext.Start(this.GetType()); string rgName = "wezamlyn-test-117"; string cloudName = "wezamlyn-test-117"; using var avsClient = context.GetServiceClient<AvsClient>(); // Gateways var gatewayResults = avsClient.WorkloadNetworks.ListGateways(rgName, cloudName); // Segments var gatewayName = gatewayResults.First().DisplayName; var segmentId = "segment"; var segmentSubnet = new WorkloadNetworkSegmentSubnet(gatewayAddress: "10.2.3.1/24"); var segment = new WorkloadNetworkSegment(displayName: segmentId, connectedGateway: gatewayName, subnet: segmentSubnet); avsClient.WorkloadNetworks.CreateSegments(rgName, cloudName, segmentId, segment); avsClient.WorkloadNetworks.ListSegments(rgName, cloudName); avsClient.WorkloadNetworks.GetSegment(rgName, cloudName, segmentId); segment.DisplayName = "modifiedSegment"; avsClient.WorkloadNetworks.UpdateSegments(rgName, cloudName, segmentId, segment); avsClient.WorkloadNetworks.DeleteSegment(rgName, cloudName, segmentId); } [Fact] public void WorkloadNetworksVirtualMachinesVmGroupsPortMirroring() { using var context = MockContext.Start(this.GetType()); string rgName = "wezamlyn-test-117"; string cloudName = "wezamlyn-test-117"; using var avsClient = context.GetServiceClient<AvsClient>(); // Virtual Machines var virtualMachinesList = avsClient.WorkloadNetworks.ListVirtualMachines(rgName, cloudName); // VM Groups var sourceVmGroupId = "sourceVmGroup"; var sourceVmGroup = new WorkloadNetworkVMGroup(displayName: sourceVmGroupId); var destVmGroupId = "destVmGroup"; var destVmGroup = new WorkloadNetworkVMGroup(displayName: destVmGroupId); if (virtualMachinesList.Count() >= 2) { string[] sourceMembers = {virtualMachinesList.ElementAt(0).DisplayName}; sourceVmGroup.Members = sourceMembers; string[] destMembers = {virtualMachinesList.ElementAt(1).DisplayName}; destVmGroup.Members = destMembers; } var resSourceVmGroup = avsClient.WorkloadNetworks.CreateVMGroup(rgName, cloudName, sourceVmGroupId, sourceVmGroup); // Get ARM ID for Port Mirroring var sourceIdSplit = resSourceVmGroup.Id.Split("/"); var sourceArmId = sourceIdSplit[sourceIdSplit.Length-1]; var resDestVmGroup = avsClient.WorkloadNetworks.CreateVMGroup(rgName, cloudName, destVmGroupId, destVmGroup); // Get ARM ID for Port Mirroring var destIdSplit = resDestVmGroup.Id.Split("/"); var destArmId = destIdSplit[destIdSplit.Length-1]; avsClient.WorkloadNetworks.ListVMGroups(rgName, cloudName); avsClient.WorkloadNetworks.GetVMGroup(rgName, cloudName, sourceVmGroupId); sourceVmGroup.DisplayName = "modifiedVmGroup"; avsClient.WorkloadNetworks.UpdateVMGroup(rgName, cloudName, sourceVmGroupId, sourceVmGroup); // Port Mirroring var portMirroringId = "portMirroring"; var portMirroring = new WorkloadNetworkPortMirroring(displayName: portMirroringId, direction: "BIDIRECTIONAL"); portMirroring.Source = sourceArmId; portMirroring.Destination = destArmId; avsClient.WorkloadNetworks.CreatePortMirroring(rgName, cloudName, portMirroringId, portMirroring); avsClient.WorkloadNetworks.ListPortMirroring(rgName, cloudName); avsClient.WorkloadNetworks.GetPortMirroring(rgName, cloudName, portMirroringId); portMirroring.DisplayName = "modifiedPortMirroring"; avsClient.WorkloadNetworks.UpdatePortMirroring(rgName, cloudName,portMirroringId, portMirroring); avsClient.WorkloadNetworks.DeletePortMirroring(rgName, portMirroringId, cloudName); // Delete VM Groups avsClient.WorkloadNetworks.DeleteVMGroup(rgName, sourceVmGroupId, cloudName); avsClient.WorkloadNetworks.DeleteVMGroup(rgName, destVmGroupId, cloudName); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Positioning.dll // Description: A library for managing GPS connections. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from http://geoframework.codeplex.com/ version 2.0 // // The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup) // // Contributor(s): (Open source contributors should list themselves and their modifications here). // ------------------------------------------------------------------------------------------------------- // | Developer | Date | Comments // |--------------------------|------------|-------------------------------------------------------------- // | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0 // | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper. // ******************************************************************************************************** using System; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace DotSpatial.Positioning { /// <summary> /// Represents a position on Earth marked by latitude, longitude, and altitude. /// </summary> /// <remarks>Instances of this class are guaranteed to be thread-safe because the class is /// immutable (its properties can only be changed via constructors).</remarks> public struct Position3D : IFormattable, IEquatable<Position3D>, ICloneable<Position3D>, IXmlSerializable { /// <summary> /// /// </summary> private Position _position; /// <summary> /// /// </summary> private Distance _altitude; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Position3D"/> struct. /// </summary> /// <param name="altitude">The altitude.</param> /// <param name="location">The location.</param> public Position3D(Distance altitude, Position location) { _position = location; _altitude = altitude; } /// <summary> /// Initializes a new instance of the <see cref="Position3D"/> struct. /// </summary> /// <param name="altitude">The altitude.</param> /// <param name="longitude">The longitude.</param> /// <param name="latitude">The latitude.</param> public Position3D(Distance altitude, Longitude longitude, Latitude latitude) { _position = new Position(longitude, latitude); _altitude = altitude; } /// <summary> /// Initializes a new instance of the <see cref="Position3D"/> struct. /// </summary> /// <param name="altitude">The altitude.</param> /// <param name="latitude">The latitude.</param> /// <param name="longitude">The longitude.</param> /// <overloads>Creates a new instance.</overloads> public Position3D(Distance altitude, Latitude latitude, Longitude longitude) { _position = new Position(latitude, longitude); _altitude = altitude; } /// <summary> /// Initializes a new instance of the <see cref="Position3D"/> struct. /// </summary> /// <param name="longitude">The longitude.</param> /// <param name="latitude">The latitude.</param> /// <param name="altitude">The altitude.</param> public Position3D(Longitude longitude, Latitude latitude, Distance altitude) { _position = new Position(latitude, longitude); _altitude = altitude; } /// <summary> /// Initializes a new instance of the <see cref="Position3D"/> struct. /// </summary> /// <param name="latitude">The latitude.</param> /// <param name="longitude">The longitude.</param> /// <param name="altitude">The altitude.</param> public Position3D(Latitude latitude, Longitude longitude, Distance altitude) { _position = new Position(latitude, longitude); _altitude = altitude; } /// <summary> /// Creates a new instance by parsing latitude and longitude from a single string. /// </summary> /// <param name="altitude">The altitude.</param> /// <param name="location">The location.</param> public Position3D(string altitude, string location) : this(altitude, location, CultureInfo.CurrentCulture) { } /// <summary> /// Creates a new instance by interpreting the specified latitude and longitude. /// </summary> /// <param name="altitude">The altitude.</param> /// <param name="latitude">The latitude.</param> /// <param name="longitude">The longitude.</param> /// <remarks>Latitude and longitude values are parsed using the current local culture. For better support /// of international cultures, add a CultureInfo parameter.</remarks> public Position3D(string altitude, string latitude, string longitude) : this(altitude, latitude, longitude, CultureInfo.CurrentCulture) { } /// <summary> /// Creates a new instance by interpreting the specified latitude and longitude. /// </summary> /// <param name="altitude">The altitude.</param> /// <param name="latitude">The latitude.</param> /// <param name="longitude">The longitude.</param> /// <param name="culture">The culture.</param> /// <remarks>Latitude and longitude values are parsed using the current local culture. For better support /// of international cultures, a CultureInfo parameter should be specified to indicate how numbers should /// be parsed.</remarks> public Position3D(string altitude, string latitude, string longitude, CultureInfo culture) { _position = new Position(latitude, longitude, culture); _altitude = new Distance(altitude, culture); } /// <summary> /// Creates a new instance by converting the specified string using the specific culture. /// </summary> /// <param name="altitude">The altitude.</param> /// <param name="location">The location.</param> /// <param name="culture">The culture.</param> public Position3D(string altitude, string location, CultureInfo culture) { _position = new Position(location, culture); _altitude = new Distance(altitude, culture); } /// <summary> /// Upgrades a Position object to a Position3D object. /// </summary> /// <param name="position">The position.</param> public Position3D(Position position) { _position = position; _altitude = Distance.Empty; } /// <summary> /// Initializes a new instance of the <see cref="Position3D"/> struct. /// </summary> /// <param name="reader">The reader.</param> public Position3D(XmlReader reader) { // Initialize all fields _position = Position.Invalid; _altitude = Distance.Invalid; // Deserialize the object from XML ReadXml(reader); } #endregion Constructors #region Public Properties /// <summary> /// Returns the location's distance above sea level. /// </summary> public Distance Altitude { get { return _altitude; } } /// <summary> /// Gets the latitude. /// </summary> public Latitude Latitude { get { return _position.Latitude; } } /// <summary> /// Gets the longitude. /// </summary> public Longitude Longitude { get { return _position.Longitude; } } #endregion Public Properties #region Public Methods /// <summary> /// Toes the cartesian point. /// </summary> /// <returns></returns> public CartesianPoint ToCartesianPoint() { return ToCartesianPoint(Ellipsoid.Default); } /// <summary> /// Toes the cartesian point. /// </summary> /// <param name="ellipsoid">The ellipsoid.</param> /// <returns></returns> public CartesianPoint ToCartesianPoint(Ellipsoid ellipsoid) { return _position.ToCartesianPoint(ellipsoid, _altitude); } #endregion Public Methods #region Operators /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Position3D left, Position3D right) { return left.Equals(right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Position3D left, Position3D right) { return !left.Equals(right); } /// <summary> /// Implements the operator +. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static Position3D operator +(Position3D left, Position3D right) { return left.Add(right); } /// <summary> /// Implements the operator -. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static Position3D operator -(Position3D left, Position3D right) { return left.Subtract(right); } /// <summary> /// Implements the operator *. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static Position3D operator *(Position3D left, Position3D right) { return left.Multiply(right); } /// <summary> /// Implements the operator /. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static Position3D operator /(Position3D left, Position3D right) { return left.Divide(right); } /// <summary> /// Adds the specified position. /// </summary> /// <param name="position">The position.</param> /// <returns></returns> public Position3D Add(Position3D position) { return new Position3D(Latitude.Add(position.Latitude.DecimalDegrees), Longitude.Add(position.Longitude.DecimalDegrees), _altitude.Add(position.Altitude)); } /// <summary> /// Subtracts the specified position. /// </summary> /// <param name="position">The position.</param> /// <returns></returns> public Position3D Subtract(Position3D position) { return new Position3D(Latitude.Subtract(position.Latitude.DecimalDegrees), Longitude.Subtract(position.Longitude.DecimalDegrees), _altitude.Subtract(position.Altitude)); } /// <summary> /// Multiplies the specified position. /// </summary> /// <param name="position">The position.</param> /// <returns></returns> public Position3D Multiply(Position3D position) { return new Position3D(Latitude.Multiply(position.Latitude.DecimalDegrees), Longitude.Multiply(position.Longitude.DecimalDegrees), _altitude.Multiply(position.Altitude)); } /// <summary> /// Divides the specified position. /// </summary> /// <param name="position">The position.</param> /// <returns></returns> public Position3D Divide(Position3D position) { return new Position3D(Latitude.Divide(position.Latitude.DecimalDegrees), Longitude.Divide(position.Longitude.DecimalDegrees), _altitude.Divide(position.Altitude)); } #endregion Operators /// <summary> /// Returns whether the latitude, longitude and altitude are zero. /// </summary> public bool IsEmpty { get { return _altitude.IsEmpty && _position.IsEmpty; } } #region Overrides /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return _position.GetHashCode() ^ _altitude.GetHashCode(); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">Another object to compare to.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (obj is Position3D) return Equals((Position3D)obj); return false; } #endregion Overrides #region Conversions /// <summary> /// Performs an explicit conversion from <see cref="DotSpatial.Positioning.CartesianPoint"/> to <see cref="DotSpatial.Positioning.Position3D"/>. /// </summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator Position3D(CartesianPoint value) { return value.ToPosition3D(); } /// <summary> /// Performs an explicit conversion from <see cref="DotSpatial.Positioning.Position3D"/> to <see cref="System.String"/>. /// </summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator string(Position3D value) { return value.ToString(); } #endregion Conversions #region IXmlSerializable /// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class. /// </summary> /// <returns>An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.</returns> XmlSchema IXmlSerializable.GetSchema() { return null; } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param> public void WriteXml(XmlWriter writer) { /* The position class uses the GML 3.0 specification for XML. * * <gml:pos>X Y</gml:pos> * */ writer.WriteStartElement(Xml.GML_XML_PREFIX, "pos", Xml.GML_XML_NAMESPACE); writer.WriteString(Longitude.DecimalDegrees.ToString("G17", CultureInfo.InvariantCulture)); writer.WriteString(" "); writer.WriteString(Latitude.DecimalDegrees.ToString("G17", CultureInfo.InvariantCulture)); writer.WriteString(" "); writer.WriteString(Altitude.ToMeters().Value.ToString("G17", CultureInfo.InvariantCulture)); writer.WriteEndElement(); } /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> public void ReadXml(XmlReader reader) { /* The position class uses the GML 3.0 specification for XML. * * <gml:pos>X Y</gml:pos> * * ... but it is also helpful to be able to READ older versions * of GML, such as this one for GML 2.0: * * <gml:coord> * <gml:X>double</gml:X> * <gml:Y>double</gml:Y> // optional * <gml:Z>double</gml:Z> // optional * </gml:coord> * */ // .NET Complains if we don't assign values _position = Position.Empty; _altitude = Distance.Empty; Longitude longitude = Longitude.Empty; Latitude latitude = Latitude.Empty; // Move to the <gml:pos> or <gml:coord> element if (!reader.IsStartElement("pos", Xml.GML_XML_NAMESPACE) && !reader.IsStartElement("coord", Xml.GML_XML_NAMESPACE)) reader.ReadStartElement(); switch (reader.LocalName.ToLower(CultureInfo.InvariantCulture)) { case "pos": // Read the "X Y" string, then split by the space between them string[] values = reader.ReadElementContentAsString().Split(' '); // Deserialize the longitude longitude = new Longitude(values[0], CultureInfo.InvariantCulture); // Deserialize the latitude if (values.Length >= 2) latitude = new Latitude(values[1], CultureInfo.InvariantCulture); // Deserialize the altitude if (values.Length == 3) _altitude = Distance.FromMeters(double.Parse(values[2], CultureInfo.InvariantCulture)); // Make the position _position = new Position(latitude, longitude); break; case "coord": // Read the <gml:coord> start tag reader.ReadStartElement(); // Now read up to 3 elements: X, and optionally Y or Z for (int index = 0; index < 3; index++) { switch (reader.LocalName.ToLower(CultureInfo.InvariantCulture)) { case "x": longitude = new Longitude(reader.ReadElementContentAsDouble()); break; case "y": latitude = new Latitude(reader.ReadElementContentAsDouble()); break; case "z": // Read Z as meters (there's no unit type in the spec :P morons) _altitude = Distance.FromMeters(reader.ReadElementContentAsDouble()); break; } // If we're at an end element, stop if (reader.NodeType == XmlNodeType.EndElement) break; } // Make the position _position = new Position(latitude, longitude); // Read the </gml:coord> end tag reader.ReadEndElement(); break; } reader.Read(); } #endregion IXmlSerializable #region IEquatable<Position3D> /// <summary> /// Compares the current instance to the specified position. /// </summary> /// <param name="other">A <strong>Position</strong> object to compare with.</param> /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns> /// <remarks>The two objects are compared at up to four digits of precision.</remarks> public bool Equals(Position3D other) { return Latitude.Equals(other.Latitude) && Longitude.Equals(other.Longitude) && _altitude.Equals(other.Altitude); } /// <summary> /// Compares the current instance to the specified position using the specified numeric precision. /// </summary> /// <param name="other">A <strong>Position</strong> object to compare with.</param> /// <param name="decimals">An <strong>Integer</strong> specifying the number of fractional digits to compare.</param> /// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values are identical.</returns> /// <remarks>This method is typically used when positions do not mark the same location unless they are /// extremely close to one another. Conversely, a low or even negative value for <strong>Precision</strong> /// allows positions to be considered equal even when they do not precisely match.</remarks> public bool Equals(Position3D other, int decimals) { return Latitude.Equals(other.Latitude, decimals) && Longitude.Equals(other.Longitude, decimals) && _altitude.Equals(other.Altitude, decimals); } #endregion IEquatable<Position3D> #region IFormattable Members /// <summary> /// Outputs the current instance as a string using the specified format and culture information. /// </summary> /// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param> /// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param> /// <returns>A <see cref="System.String"/> that represents this instance.</returns> public string ToString(string format, IFormatProvider formatProvider) { CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture; if (string.IsNullOrEmpty(format)) format = "G"; // Output as latitude and longitude return _position.ToString(format, culture) + culture.TextInfo.ListSeparator + _altitude.ToString(format, culture); } /// <summary> /// Returns a coordinate which has been shifted the specified bearing and distance. /// </summary> /// <param name="bearing">The bearing.</param> /// <param name="distance">The distance.</param> /// <param name="ellipsoid">The ellipsoid.</param> /// <returns></returns> public Position3D TranslateTo(Azimuth bearing, Distance distance, Ellipsoid ellipsoid) { return new Position3D(_altitude, _position.TranslateTo(bearing, distance, ellipsoid)); } #endregion IFormattable Members #region ICloneable<Position3D> Members /// <summary> /// Clones this instance. /// </summary> /// <returns></returns> public Position3D Clone() { return new Position3D(_position); } #endregion ICloneable<Position3D> Members } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class GetEnumeratorStringDictionaryTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { StringDictionary sd; IEnumerator en; DictionaryEntry curr; // Eumerator.Current value // simple string values string[] values = { "a", "aa", "", " ", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "one", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; // [] StringDictionary GetEnumerator() //----------------------------------------------------------------- sd = new StringDictionary(); // [] Enumerator for empty dictionary // en = sd.GetEnumerator(); string type = en.GetType().ToString(); if (type.IndexOf("Enumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not Enumerator")); } // // MoveNext should return false // bool res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); // // Filled collection // [] Enumerator for filled dictionary // for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } en = sd.GetEnumerator(); type = en.GetType().ToString(); if (type.IndexOf("Enumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not Enumerator")); } // // MoveNext should return true // for (int i = 0; i < sd.Count; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } curr = (DictionaryEntry)en.Current; // //enumerator enumerates in different than added order // so we'll check Contains // if (!sd.ContainsValue(curr.Value.ToString())) { Assert.False(true, string.Format("Error, Current dictionary doesn't contain value from enumerator", i)); } if (!sd.ContainsKey(curr.Key.ToString())) { Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i)); } if (String.Compare(sd[curr.Key.ToString()], curr.Value.ToString()) != 0) { Assert.False(true, string.Format("Error, Value for current Key is different in dictionary", i)); } // while we didn't MoveNext, Current should return the same value DictionaryEntry curr1 = (DictionaryEntry)en.Current; if (!curr.Equals(curr1)) { Assert.False(true, string.Format("Error, second call of Current returned different result", i)); } } // next MoveNext should bring us outside of the collection // res = en.MoveNext(); res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); en.Reset(); // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; }); // // [] Modify dictionary when enumerating // if (sd.Count < 1) { for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } } en = sd.GetEnumerator(); res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false")); } curr = (DictionaryEntry)en.Current; int cnt = sd.Count; sd.Remove(keys[0]); if (sd.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove item with 0th key")); } // will return just removed item DictionaryEntry curr2 = (DictionaryEntry)en.Current; if (!curr.Equals(curr2)) { Assert.False(true, string.Format("Error, current returned different value after midification")); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); // // [] Modify dictionary when enumerated beyond the end // sd.Clear(); for (int i = 0; i < values.Length; i++) { sd.Add(keys[i], values[i]); } en = sd.GetEnumerator(); for (int i = 0; i < sd.Count; i++) { en.MoveNext(); } curr = (DictionaryEntry)en.Current; curr = (DictionaryEntry)en.Current; cnt = sd.Count; sd.Remove(keys[0]); if (sd.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove item with 0th key")); } // will return just removed item curr2 = (DictionaryEntry)en.Current; if (!curr.Equals(curr2)) { Assert.False(true, string.Format("Error, current returned different value after midification")); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Markup; namespace Microsoft.Management.UI.Internal { /// <summary> /// Extends the basic GrdView class to introduce the Visible concept to the /// Columns collection. /// </summary> /// <!--We create our own version of Columns, that: /// 1) Only takes InnerListColumn's /// 2) Passes through the underlying ListView Columns, only the InnerListColumns /// that have Visible=true.--> [ContentProperty("AvailableColumns")] public class InnerListGridView : GridView { /// <summary> /// Set to true when we want to change the Columns collection. /// </summary> private bool canChangeColumns = false; /// <summary> /// Instanctiates a new object of this class. /// </summary> public InnerListGridView() : this(new ObservableCollection<InnerListColumn>()) { } /// <summary> /// Initializes a new instance of the <see cref="InnerListGridView"/> class with the specified columns. /// </summary> /// <param name="availableColumns">The columns this grid should display.</param> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> internal InnerListGridView(ObservableCollection<InnerListColumn> availableColumns) { if (availableColumns == null) { throw new ArgumentNullException("availableColumns"); } // Setting the AvailableColumns property won't trigger CollectionChanged, so we have to do it manually \\ this.AvailableColumns = availableColumns; this.AvailableColumns_CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, availableColumns)); availableColumns.CollectionChanged += this.AvailableColumns_CollectionChanged; this.Columns.CollectionChanged += this.Columns_CollectionChanged; } /// <summary> /// Gets a collection of all columns which can be /// added to the ManagementList, for example through ColumnPicker. /// Columns is the collection of the columns which are currently /// displayed (in the order in which they are displayed). /// </summary> internal ObservableCollection<InnerListColumn> AvailableColumns { get; private set; } /// <summary> /// Releases this instance's references to its controls. /// This API supports the framework infrastructure and is not intended to be used directly from your code. /// </summary> public void ReleaseReferences() { this.AvailableColumns.CollectionChanged -= this.AvailableColumns_CollectionChanged; this.Columns.CollectionChanged -= this.Columns_CollectionChanged; foreach (InnerListColumn column in this.AvailableColumns) { // Unsubscribe from the column's change events \\ ((INotifyPropertyChanged)column).PropertyChanged -= this.Column_PropertyChanged; // If the column is shown, store its last width before releasing \\ if (column.Visible) { column.Width = column.ActualWidth; } } // Remove the columns so they can be added to the next GridView \\ this.Columns.Clear(); } /// <summary> /// Called when the ItemsSource changes to auto populate the GridView columns /// with reflection information on the first element of the ItemsSource. /// </summary> /// <param name="newValue"> /// The new ItemsSource. /// This is used just to fetch .the first collection element. /// </param> internal void PopulateColumns(System.Collections.IEnumerable newValue) { if (newValue == null) { return; // No elements, so we can't populate } IEnumerator newValueEnumerator = newValue.GetEnumerator(); if (!newValueEnumerator.MoveNext()) { return; // No first element, so we can't populate } object first = newValueEnumerator.Current; if (first == null) { return; } Debug.Assert(this.AvailableColumns.Count == 0, "AvailabeColumns should be empty at this point"); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(first); foreach (PropertyDescriptor property in properties) { UIPropertyGroupDescription dataDescription = new UIPropertyGroupDescription(property.Name, property.Name, property.PropertyType); InnerListColumn column = new InnerListColumn(dataDescription); this.AvailableColumns.Add(column); } } /// <summary> /// Callback for displaying the Column Picker. /// </summary> /// <param name="sender">The send object.</param> /// <param name="e">The Event RoutedEventArgs.</param> internal void OnColumnPicker(object sender, RoutedEventArgs e) { ColumnPicker columnPicker = new ColumnPicker( this.Columns, this.AvailableColumns); columnPicker.Owner = Window.GetWindow((DependencyObject)sender); bool? retval = columnPicker.ShowDialog(); if (retval != true) { return; } this.canChangeColumns = true; try { this.Columns.Clear(); ObservableCollection<InnerListColumn> newColumns = columnPicker.SelectedColumns; Debug.Assert(newColumns != null, "SelectedColumns not found"); foreach (InnerListColumn column in newColumns) { Debug.Assert(column.Visible, "is visible"); // 185977: ML InnerListGridView.PopulateColumns(): Always set Width on new columns // Workaround to GridView issue suggested by Ben Carter // Issue: Once a column has been added to a GridView // and then removed, auto-sizing does not work // after it is added back. // Solution: Remove the column, change the width, // add the column back, then change the width back. double width = column.Width; column.Width = 0d; this.Columns.Add(column); column.Width = width; } } finally { this.canChangeColumns = false; } } /// <summary> /// Called when Columns changes so we can check we are the ones changing it. /// </summary> /// <param name="sender">The collection changing.</param> /// <param name="e">The event parameters.</param> private void Columns_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { // Move happens in the GUI drag and drop operation, so we have to allow it. case NotifyCollectionChangedAction.Move: return; // default means all other operations (Add, Move, Replace and Reset) those are reserved. // only we should do it, as we keep AvailableColumns in sync with columns default: if (!this.canChangeColumns) { throw new NotSupportedException( string.Format( CultureInfo.InvariantCulture, InvariantResources.CannotModified, InvariantResources.Columns, "AvailableColumns")); } break; } } /// <summary> /// Called when the AvailableColumns changes to pass through the VisibleColumns to Columns. /// </summary> /// <param name="sender">The collection changing.</param> /// <param name="e">The event parameters.</param> private void AvailableColumns_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { this.AddOrRemoveNotifications(e); this.SynchronizeColumns(); } /// <summary> /// Called from availableColumns_CollectionChanged to add or remove the notifications /// used to track the Visible property. /// </summary> /// <param name="e">The parameter passed to availableColumns_CollectionChanged.</param> private void AddOrRemoveNotifications(NotifyCollectionChangedEventArgs e) { if (e.Action != NotifyCollectionChangedAction.Move) { if (e.OldItems != null) { foreach (InnerListColumn oldColumn in e.OldItems) { ((INotifyPropertyChanged)oldColumn).PropertyChanged -= this.Column_PropertyChanged; } } if (e.NewItems != null) { foreach (InnerListColumn newColumn in e.NewItems) { ((INotifyPropertyChanged)newColumn).PropertyChanged += this.Column_PropertyChanged; } } } } /// <summary> /// Syncronizes AvailableColumns and Columns preserving the order from Columns that /// comes from the user moving Columns around. /// </summary> private void SynchronizeColumns() { this.canChangeColumns = true; try { // Add to listViewColumns all Visible columns in availableColumns not already in listViewColumns foreach (InnerListColumn column in this.AvailableColumns) { if (column.Visible && !this.Columns.Contains(column)) { this.Columns.Add(column); } } // Remove all columns which are not visible or removed from Available columns. for (int i = this.Columns.Count - 1; i >= 0; i--) { InnerListColumn listViewColumn = (InnerListColumn)this.Columns[i]; if (!listViewColumn.Visible || !this.AvailableColumns.Contains(listViewColumn)) { this.Columns.RemoveAt(i); } } } finally { this.canChangeColumns = false; } } /// <summary> /// Called when the Visible property of a column changes. /// </summary> /// <param name="sender">The column whose property changed.</param> /// <param name="e">The event parameters.</param> private void Column_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == InnerListColumn.VisibleProperty.Name) { this.SynchronizeColumns(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** Purpose: A circular-array implementation of a generic queue. ** ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Collections.Generic { // A simple Queue of generic objects. Internally it is implemented as a // circular buffer, so Enqueue can be O(n). Dequeue is O(1). [DebuggerTypeProxy(typeof(QueueDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Queue<T> : IEnumerable<T>, System.Collections.ICollection, IReadOnlyCollection<T> { private T[] _array; private int _head; // The index from which to dequeue if the queue isn't empty. private int _tail; // The index at which to enqueue if the queue isn't full. private int _size; // Number of elements. private int _version; private const int MinimumGrow = 4; private const int GrowFactor = 200; // double each time // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. public Queue() { _array = Array.Empty<T>(); } // Creates a queue with room for capacity objects. The default grow factor // is used. public Queue(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); _array = new T[capacity]; } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. public Queue(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); _array = EnumerableHelpers.ToArray(collection, out _size); if (_size != _array.Length) _tail = _size; } public int Count { get { return _size; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot => this; // Removes all Objects from the queue. public void Clear() { if (_size != 0) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { if (_head < _tail) { Array.Clear(_array, _head, _size); } else { Array.Clear(_array, _head, _array.Length - _head); Array.Clear(_array, 0, _tail); } } _size = 0; } _head = 0; _tail = 0; _version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } int arrayLen = array.Length; if (arrayLen - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int numToCopy = _size; if (numToCopy == 0) return; int firstPart = Math.Min(_array.Length - _head, numToCopy); Array.Copy(_array, _head, array, arrayIndex, firstPart); numToCopy -= firstPart; if (numToCopy > 0) { Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy); } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } int arrayLen = array.Length; if (index < 0 || index > arrayLen) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } if (arrayLen - index < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int numToCopy = _size; if (numToCopy == 0) return; try { int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, index, firstPart); numToCopy -= firstPart; if (numToCopy > 0) { Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } // Adds item to the tail of the queue. public void Enqueue(T item) { if (_size == _array.Length) { int newcapacity = (int)((long)_array.Length * (long)GrowFactor / 100); if (newcapacity < _array.Length + MinimumGrow) { newcapacity = _array.Length + MinimumGrow; } SetCapacity(newcapacity); } _array[_tail] = item; MoveNext(ref _tail); _size++; _version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. public Enumerator GetEnumerator() { return new Enumerator(this); } /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method throws an // InvalidOperationException. public T Dequeue() { int head = _head; T[] array = _array; if (_size == 0) { ThrowForEmptyQueue(); } T removed = array[head]; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { array[head] = default!; } MoveNext(ref _head); _size--; _version++; return removed; } public bool TryDequeue([MaybeNullWhen(false)] out T result) { int head = _head; T[] array = _array; if (_size == 0) { result = default!; return false; } result = array[head]; if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { array[head] = default!; } MoveNext(ref _head); _size--; _version++; return true; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. public T Peek() { if (_size == 0) { ThrowForEmptyQueue(); } return _array[_head]; } public bool TryPeek([MaybeNullWhen(false)] out T result) { if (_size == 0) { result = default!; return false; } result = _array[_head]; return true; } // Returns true if the queue contains at least one object equal to item. // Equality is determined using EqualityComparer<T>.Default.Equals(). public bool Contains(T item) { if (_size == 0) { return false; } if (_head < _tail) { return Array.IndexOf(_array, item, _head, _size) >= 0; } // We've wrapped around. Check both partitions, the least recently enqueued first. return Array.IndexOf(_array, item, _head, _array.Length - _head) >= 0 || Array.IndexOf(_array, item, 0, _tail) >= 0; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. public T[] ToArray() { if (_size == 0) { return Array.Empty<T>(); } T[] arr = new T[_size]; if (_head < _tail) { Array.Copy(_array, _head, arr, 0, _size); } else { Array.Copy(_array, _head, arr, 0, _array.Length - _head); Array.Copy(_array, 0, arr, _array.Length - _head, _tail); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity(int capacity) { T[] newarray = new T[capacity]; if (_size > 0) { if (_head < _tail) { Array.Copy(_array, _head, newarray, 0, _size); } else { Array.Copy(_array, _head, newarray, 0, _array.Length - _head); Array.Copy(_array, 0, newarray, _array.Length - _head, _tail); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; _version++; } // Increments the index wrapping it if necessary. private void MoveNext(ref int index) { // It is tempting to use the remainder operator here but it is actually much slower // than a simple comparison and a rarely taken branch. // JIT produces better code than with ternary operator ?: int tmp = index + 1; if (tmp == _array.Length) { tmp = 0; } index = tmp; } private void ThrowForEmptyQueue() { Debug.Assert(_size == 0); throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if (_size < threshold) { SetCapacity(_size); } } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private readonly Queue<T> _q; private readonly int _version; private int _index; // -1 = not started, -2 = ended/disposed [AllowNull] private T _currentElement; internal Enumerator(Queue<T> q) { _q = q; _version = q._version; _index = -1; _currentElement = default; } public void Dispose() { _index = -2; _currentElement = default; } public bool MoveNext() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) return false; _index++; if (_index == _q._size) { // We've run past the last element _index = -2; _currentElement = default; return false; } // Cache some fields in locals to decrease code size T[] array = _q._array; int capacity = array.Length; // _index represents the 0-based index into the queue, however the queue // doesn't have to start from 0 and it may not even be stored contiguously in memory. int arrayIndex = _q._head + _index; // this is the actual index into the queue's backing array if (arrayIndex >= capacity) { // NOTE: Originally we were using the modulo operator here, however // on Intel processors it has a very high instruction latency which // was slowing down the loop quite a bit. // Replacing it with simple comparison/subtraction operations sped up // the average foreach loop by 2x. arrayIndex -= capacity; // wrap around if needed } _currentElement = array[arrayIndex]; return true; } public T Current { get { if (_index < 0) ThrowEnumerationNotStartedOrEnded(); return _currentElement; } } private void ThrowEnumerationNotStartedOrEnded() { Debug.Assert(_index == -1 || _index == -2); throw new InvalidOperationException(_index == -1 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded); } object? IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -1; _currentElement = default; } } } }
// 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. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.Data.Common; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Data.SqlTypes { /// <devdoc> /// <para> /// Represents an integer value that is either 1 or 0. /// </para> /// </devdoc> [StructLayout(LayoutKind.Sequential)] public struct SqlBoolean : INullable, IComparable { // m_value: 2 (true), 1 (false), 0 (unknown/Null) private byte _value; private const byte x_Null = 0; private const byte x_False = 1; private const byte x_True = 2; // constructor /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlBoolean'/> class. /// </para> /// </devdoc> public SqlBoolean(bool value) { _value = (byte)(value ? x_True : x_False); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SqlBoolean(int value) : this(value, false) { } private SqlBoolean(int value, bool fNull) { if (fNull) _value = x_Null; else _value = (value != 0) ? x_True : x_False; } // INullable /// <devdoc> /// <para> /// Gets whether the current <see cref='System.Data.SqlTypes.SqlBoolean.Value'/> is <see cref='System.Data.SqlTypes.SqlBoolean.Null'/>. /// </para> /// </devdoc> public bool IsNull { get { return _value == x_Null; } } // property: Value /// <devdoc> /// <para> /// Gets or sets the <see cref='System.Data.SqlTypes.SqlBoolean'/> to be <see langword='true'/> or /// <see langword='false'/>. /// </para> /// </devdoc> public bool Value { get { switch (_value) { case x_True: return true; case x_False: return false; default: throw new SqlNullValueException(); } } } // property: IsTrue /// <devdoc> /// <para> /// Gets whether the current <see cref='System.Data.SqlTypes.SqlBoolean.Value'/> is <see cref='System.Data.SqlTypes.SqlBoolean.True'/>. /// </para> /// </devdoc> public bool IsTrue { get { return _value == x_True; } } // property: IsFalse /// <devdoc> /// <para> /// Gets whether the current <see cref='System.Data.SqlTypes.SqlBoolean.Value'/> is <see cref='System.Data.SqlTypes.SqlBoolean.False'/>. /// </para> /// </devdoc> public bool IsFalse { get { return _value == x_False; } } // Implicit conversion from bool to SqlBoolean /// <devdoc> /// <para> /// Converts a boolean to a <see cref='System.Data.SqlTypes.SqlBoolean'/>. /// </para> /// </devdoc> public static implicit operator SqlBoolean(bool x) { return new SqlBoolean(x); } // Explicit conversion from SqlBoolean to bool. Throw exception if x is Null. /// <devdoc> /// <para> /// Converts a <see cref='System.Data.SqlTypes.SqlBoolean'/> /// to a boolean. /// </para> /// </devdoc> public static explicit operator bool (SqlBoolean x) { return x.Value; } // Unary operators /// <devdoc> /// <para> /// Performs a NOT operation on a <see cref='System.Data.SqlTypes.SqlBoolean'/> /// . /// </para> /// </devdoc> public static SqlBoolean operator !(SqlBoolean x) { switch (x._value) { case x_True: return SqlBoolean.False; case x_False: return SqlBoolean.True; default: Debug.Assert(x._value == x_Null); return SqlBoolean.Null; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static bool operator true(SqlBoolean x) { return x.IsTrue; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static bool operator false(SqlBoolean x) { return x.IsFalse; } // Binary operators /// <devdoc> /// <para> /// Performs a bitwise AND operation on two instances of /// <see cref='System.Data.SqlTypes.SqlBoolean'/> /// . /// </para> /// </devdoc> public static SqlBoolean operator &(SqlBoolean x, SqlBoolean y) { if (x._value == x_False || y._value == x_False) return SqlBoolean.False; else if (x._value == x_True && y._value == x_True) return SqlBoolean.True; else return SqlBoolean.Null; } /// <devdoc> /// <para> /// Performs /// a bitwise OR operation on two instances of a /// <see cref='System.Data.SqlTypes.SqlBoolean'/> /// . /// </para> /// </devdoc> public static SqlBoolean operator |(SqlBoolean x, SqlBoolean y) { if (x._value == x_True || y._value == x_True) return SqlBoolean.True; else if (x._value == x_False && y._value == x_False) return SqlBoolean.False; else return SqlBoolean.Null; } // property: ByteValue /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public byte ByteValue { get { if (!IsNull) return (_value == x_True) ? (byte)1 : (byte)0; else throw new SqlNullValueException(); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override String ToString() { return IsNull ? SQLResource.NullString : Value.ToString(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean Parse(String s) { if (null == s) // Let Boolean.Parse throw exception return new SqlBoolean(Boolean.Parse(s)); if (s == SQLResource.NullString) return SqlBoolean.Null; s = s.TrimStart(); char wchFirst = s[0]; if (Char.IsNumber(wchFirst) || ('-' == wchFirst) || ('+' == wchFirst)) { return new SqlBoolean(Int32.Parse(s, (IFormatProvider)null)); } else { return new SqlBoolean(Boolean.Parse(s)); } } // Unary operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator ~(SqlBoolean x) { return (!x); } // Binary operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator ^(SqlBoolean x, SqlBoolean y) { return (x.IsNull || y.IsNull) ? Null : new SqlBoolean(x._value != y._value); } // Implicit conversions // Explicit conversions // Explicit conversion from SqlByte to SqlBoolean /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlByte x) { return x.IsNull ? Null : new SqlBoolean(x.Value != 0); } // Explicit conversion from SqlInt16 to SqlBoolean /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlInt16 x) { return x.IsNull ? Null : new SqlBoolean(x.Value != 0); } // Explicit conversion from SqlInt32 to SqlBoolean /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlInt32 x) { return x.IsNull ? Null : new SqlBoolean(x.Value != 0); } // Explicit conversion from SqlInt64 to SqlBoolean /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlInt64 x) { return x.IsNull ? Null : new SqlBoolean(x.Value != 0); } // Explicit conversion from SqlDouble to SqlBoolean /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlDouble x) { return x.IsNull ? Null : new SqlBoolean(x.Value != 0.0); } // Explicit conversion from SqlSingle to SqlBoolean /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlSingle x) { return x.IsNull ? Null : new SqlBoolean(x.Value != 0.0); } // Explicit conversion from SqlMoney to SqlBoolean /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlMoney x) { return x.IsNull ? Null : (x != SqlMoney.Zero); } // Explicit conversion from SqlDecimal to SqlBoolean /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlDecimal x) { return x.IsNull ? SqlBoolean.Null : new SqlBoolean(x.m_data1 != 0 || x.m_data2 != 0 || x.m_data3 != 0 || x.m_data4 != 0); } // Explicit conversion from SqlString to SqlBoolean // Throws FormatException or OverflowException if necessary. /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlBoolean(SqlString x) { return x.IsNull ? Null : SqlBoolean.Parse(x.Value); } // Overloading comparison operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator ==(SqlBoolean x, SqlBoolean y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator !=(SqlBoolean x, SqlBoolean y) { return !(x == y); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator <(SqlBoolean x, SqlBoolean y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator >(SqlBoolean x, SqlBoolean y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator <=(SqlBoolean x, SqlBoolean y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator >=(SqlBoolean x, SqlBoolean y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator ~ public static SqlBoolean OnesComplement(SqlBoolean x) { return ~x; } // Alternative method for operator & public static SqlBoolean And(SqlBoolean x, SqlBoolean y) { return x & y; } // Alternative method for operator | public static SqlBoolean Or(SqlBoolean x, SqlBoolean y) { return x | y; } // Alternative method for operator ^ public static SqlBoolean Xor(SqlBoolean x, SqlBoolean y) { return x ^ y; } // Alternative method for operator == public static SqlBoolean Equals(SqlBoolean x, SqlBoolean y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlBoolean x, SqlBoolean y) { return (x != y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlBoolean x, SqlBoolean y) { return (x > y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlBoolean x, SqlBoolean y) { return (x < y); } // Alternative method for operator <= public static SqlBoolean GreaterThanOrEquals(SqlBoolean x, SqlBoolean y) { return (x >= y); } // Alternative method for operator != public static SqlBoolean LessThanOrEquals(SqlBoolean x, SqlBoolean y) { return (x <= y); } // Alternative method for conversions. public SqlByte ToSqlByte() { return (SqlByte)this; } public SqlDouble ToSqlDouble() { return (SqlDouble)this; } public SqlInt16 ToSqlInt16() { return (SqlInt16)this; } public SqlInt32 ToSqlInt32() { return (SqlInt32)this; } public SqlInt64 ToSqlInt64() { return (SqlInt64)this; } public SqlMoney ToSqlMoney() { return (SqlMoney)this; } public SqlDecimal ToSqlDecimal() { return (SqlDecimal)this; } public SqlSingle ToSqlSingle() { return (SqlSingle)this; } public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int CompareTo(Object value) { if (value is SqlBoolean) { SqlBoolean i = (SqlBoolean)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlBoolean)); } public int CompareTo(SqlBoolean value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this.ByteValue < value.ByteValue) return -1; if (this.ByteValue > value.ByteValue) return 1; return 0; } // Compares this instance with a specified object /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override bool Equals(Object value) { if (!(value is SqlBoolean)) { return false; } SqlBoolean i = (SqlBoolean)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } /// <devdoc> /// <para> /// Represents a true value that can be assigned to the /// <see cref='System.Data.SqlTypes.SqlBoolean.Value'/> property of an instance of /// the <see cref='System.Data.SqlTypes.SqlBoolean'/> class. /// </para> /// </devdoc> public static readonly SqlBoolean True = new SqlBoolean(true); /// <devdoc> /// <para> /// Represents a false value that can be assigned to the /// <see cref='System.Data.SqlTypes.SqlBoolean.Value'/> property of an instance of /// the <see cref='System.Data.SqlTypes.SqlBoolean'/> class. /// </para> /// </devdoc> public static readonly SqlBoolean False = new SqlBoolean(false); /// <devdoc> /// <para> /// Represents a null value that can be assigned to the <see cref='System.Data.SqlTypes.SqlBoolean.Value'/> property of an instance of /// the <see cref='System.Data.SqlTypes.SqlBoolean'/> class. /// </para> /// </devdoc> public static readonly SqlBoolean Null = new SqlBoolean(0, true); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly SqlBoolean Zero = new SqlBoolean(0); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly SqlBoolean One = new SqlBoolean(1); } // SqlBoolean } // namespace System.Data.SqlTypes
using Lucene.Net.Support; using System; using System.Text; /* * dk.brics.automaton * * Copyright (c) 2001-2009 Anders Moeller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * this SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Lucene.Net.Util.Automaton { /// <summary> /// Finite-state automaton with fast run operation. /// <para/> /// @lucene.experimental /// </summary> public abstract class RunAutomaton { private readonly int _maxInterval; private readonly int _size; protected readonly bool[] m_accept; protected readonly int m_initial; protected readonly int[] m_transitions; // delta(state,c) = transitions[state*points.length + // getCharClass(c)] private readonly int[] _points; // char interval start points private readonly int[] _classmap; // map from char number to class class /// <summary> /// Returns a string representation of this automaton. /// </summary> public override string ToString() { var b = new StringBuilder(); b.Append("initial state: ").Append(m_initial).Append("\n"); for (int i = 0; i < _size; i++) { b.Append("state " + i); if (m_accept[i]) { b.Append(" [accept]:\n"); } else { b.Append(" [reject]:\n"); } for (int j = 0; j < _points.Length; j++) { int k = m_transitions[i * _points.Length + j]; if (k != -1) { int min = _points[j]; int max; if (j + 1 < _points.Length) { max = (_points[j + 1] - 1); } else { max = _maxInterval; } b.Append(" "); Transition.AppendCharString(min, b); if (min != max) { b.Append("-"); Transition.AppendCharString(max, b); } b.Append(" -> ").Append(k).Append("\n"); } } } return b.ToString(); } /// <summary> /// Returns number of states in automaton. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> public int Count => _size; /// <summary> /// Returns acceptance status for given state. /// </summary> public bool IsAccept(int state) { return m_accept[state]; } /// <summary> /// Returns initial state. /// </summary> public int InitialState => m_initial; /// <summary> /// Returns array of codepoint class interval start points. The array should /// not be modified by the caller. /// </summary> public int[] GetCharIntervals() { return (int[])(Array)_points.Clone(); } /// <summary> /// Gets character class of given codepoint. /// </summary> internal int GetCharClass(int c) { return SpecialOperations.FindIndex(c, _points); } /// <summary> /// Constructs a new <see cref="RunAutomaton"/> from a deterministic /// <see cref="Automaton"/>. /// </summary> /// <param name="a"> An automaton. </param> /// <param name="maxInterval"></param> /// <param name="tableize"></param> public RunAutomaton(Automaton a, int maxInterval, bool tableize) { this._maxInterval = maxInterval; a.Determinize(); _points = a.GetStartPoints(); State[] states = a.GetNumberedStates(); m_initial = a.initial.Number; _size = states.Length; m_accept = new bool[_size]; m_transitions = new int[_size * _points.Length]; for (int n = 0; n < _size * _points.Length; n++) { m_transitions[n] = -1; } foreach (State s in states) { int n = s.number; m_accept[n] = s.accept; for (int c = 0; c < _points.Length; c++) { State q = s.Step(_points[c]); if (q != null) { m_transitions[n * _points.Length + c] = q.number; } } } /* * Set alphabet table for optimal run performance. */ if (tableize) { _classmap = new int[maxInterval + 1]; int i = 0; for (int j = 0; j <= maxInterval; j++) { if (i + 1 < _points.Length && j == _points[i + 1]) { i++; } _classmap[j] = i; } } else { _classmap = null; } } /// <summary> /// Returns the state obtained by reading the given char from the given state. /// Returns -1 if not obtaining any such state. (If the original /// <see cref="Automaton"/> had no dead states, -1 is returned here if and only /// if a dead state is entered in an equivalent automaton with a total /// transition function.) /// </summary> public int Step(int state, int c) { if (_classmap == null) { return m_transitions[state * _points.Length + GetCharClass(c)]; } else { return m_transitions[state * _points.Length + _classmap[c]]; } } public override int GetHashCode() { const int prime = 31; int result = 1; result = prime * result + m_initial; result = prime * result + _maxInterval; result = prime * result + _points.Length; result = prime * result + _size; return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.GetType() != obj.GetType()) { return false; } RunAutomaton other = (RunAutomaton)obj; if (m_initial != other.m_initial) { return false; } if (_maxInterval != other._maxInterval) { return false; } if (_size != other._size) { return false; } if (!Arrays.Equals(_points, other._points)) { return false; } if (!Arrays.Equals(m_accept, other.m_accept)) { return false; } if (!Arrays.Equals(m_transitions, other.m_transitions)) { return false; } return true; } } }
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using Hydra.Framework; namespace Hydra.SharedCache.Common.Sockets { // // ********************************************************************** /// <summary> /// Represents a pool of connections for a specific server node. /// <example> /// Server: 192.168.0.1 Port: 48888 /// </example> /// </summary> // ********************************************************************** // internal class TcpSocketConnectionPool { // // ********************************************************************** /// <summary> /// Bulk Object /// </summary> // ********************************************************************** // private static object bulkObject = new object(); #region Property: Host private string host; // // ********************************************************************** /// <summary> /// Gets/sets the Host /// </summary> /// <value>The host.</value> // ********************************************************************** // public string Host { [System.Diagnostics.DebuggerStepThrough] get { return this.host; } [System.Diagnostics.DebuggerStepThrough] set { this.host = value; } } #endregion #region Property: Port private int port; // // ********************************************************************** /// <summary> /// Gets/sets the Port /// </summary> /// <value>The port.</value> // ********************************************************************** // public int Port { [System.Diagnostics.DebuggerStepThrough] get { return this.port; } [System.Diagnostics.DebuggerStepThrough] set { this.port = value; } } #endregion // // ********************************************************************** /// <summary>The maximum size of the connection pool.</summary> // TODO: set pool size from config file. // ********************************************************************** // private static readonly int POOL_SIZE = 5; // // ********************************************************************** /// <summary>Queue of available socket connections.</summary> // ********************************************************************** // private Queue<SharedCacheTcpClient> availableSockets = new Queue<SharedCacheTcpClient>(); // // ********************************************************************** /// <summary> /// Validates this instance. /// </summary> // ********************************************************************** // internal void Validate() { for (int i = 0; i < this.availableSockets.Count; i++) { SharedCacheTcpClient client = null; lock (bulkObject) { client = this.availableSockets.Dequeue(); } TimeSpan sp = DateTime.Now.Subtract(client.LastUsed); // // Console.WriteLine(@"last used: {0}m {1}s {2}ms", sp.Minutes, sp.Seconds, sp.Milliseconds); // if (sp.Minutes >= 2) { client.Dispose(); } else if (client != null && !client.Connected) { // // this will close the socket in case we have to much open sockets. // this.PutSocket(client); } else if (client != null) { lock (bulkObject) { this.availableSockets.Enqueue(client); } } } #region try to enable pool in case its disabled //if (this.Enable == false) //{ // if (CacheUtil.Ping(this.Host)) // { // this.Enable = true; // } //} #endregion } // // ********************************************************************** /// <summary> /// Get an open socket from the connection pool. /// </summary> /// <returns> /// Socket returned from the pool or new socket /// opened. /// </returns> // ********************************************************************** // public SharedCacheTcpClient GetSocket() { if (this.availableSockets.Count > 0) { SharedCacheTcpClient socket = null; while (this.availableSockets.Count > 0) { lock (bulkObject) { socket = this.availableSockets.Dequeue(); } if (socket.Connected) { TimeSpan sp = DateTime.Now.Subtract(socket.LastUsed); if (sp.Minutes >= 2) { socket.Close(); return this.OpenSocket(); } else return socket; } else { if (socket != null) { // // MAYBE we should consider to reconnect it instead to close it? // socket.Close(); } } } } return this.OpenSocket(); } // // ********************************************************************** /// <summary> /// Return the given socket back to the socket pool. /// </summary> /// <param name="socket">Socket connection to return.</param> // ********************************************************************** // public void PutSocket(SharedCacheTcpClient socket) { if (this.availableSockets.Count < TcpSocketConnectionPool.POOL_SIZE) { if (socket != null) { if (socket.Connected) { // // Set the socket back to blocking and enqueue // socket.SetBlockingMode(true); socket.LastUsed = DateTime.Now; lock (bulkObject) { this.availableSockets.Enqueue(socket); } } else { socket.Close(); } } } else { // // Number of sockets is above the pool size, so just close it. // socket.Close(); } } // // ********************************************************************** /// <summary> /// Open a new socket connection. /// </summary> /// <returns>Newly opened socket connection.</returns> // ********************************************************************** // private SharedCacheTcpClient OpenSocket() { return new SharedCacheTcpClient(this.host, this.port); } } }
/* * 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 { using System; using System.Collections.Generic; using System.Reflection; using Apache.Ignite.Core.Binary; /// <summary> /// Binary serializer which reflectively writes all fields except of ones with /// <see cref="System.NonSerializedAttribute"/>. /// <para /> /// Note that Java platform stores dates as a difference between current time /// and predefined absolute UTC date. Therefore, this difference is always the /// same for all time zones. .Net, in contrast, stores dates as a difference /// between current time and some predefined date relative to the current time /// zone. It means that this difference will be different as you change time zones. /// To overcome this discrepancy Ignite always converts .Net date to UTC form /// before serializing and allows user to decide whether to deserialize them /// in UTC or local form using <c>ReadTimestamp(..., true/false)</c> methods in /// <see cref="IBinaryReader"/> and <see cref="IBinaryRawReader"/>. /// This serializer always read dates in UTC form. It means that if you have /// local date in any field/property, it will be implicitly converted to UTC /// form after the first serialization-deserialization cycle. /// </summary> internal class BinaryReflectiveSerializer : IBinarySerializer { /** Cached binding flags. */ private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; /** Cached type descriptors. */ private readonly IDictionary<Type, Descriptor> _types = new Dictionary<Type, Descriptor>(); /// <summary> /// Write portalbe object. /// </summary> /// <param name="obj">Object.</param> /// <param name="writer">Writer.</param> /// <exception cref="BinaryObjectException">Type is not registered in serializer: + type.Name</exception> public void WriteBinary(object obj, IBinaryWriter writer) { var binarizable = obj as IBinarizable; if (binarizable != null) binarizable.WriteBinary(writer); else GetDescriptor(obj).Write(obj, writer); } /// <summary> /// Read binary object. /// </summary> /// <param name="obj">Instantiated empty object.</param> /// <param name="reader">Reader.</param> /// <exception cref="BinaryObjectException">Type is not registered in serializer: + type.Name</exception> public void ReadBinary(object obj, IBinaryReader reader) { var binarizable = obj as IBinarizable; if (binarizable != null) binarizable.ReadBinary(reader); else GetDescriptor(obj).Read(obj, reader); } /// <summary>Register type.</summary> /// <param name="type">Type.</param> /// <param name="typeId">Type ID.</param> /// <param name="converter">Name converter.</param> /// <param name="idMapper">ID mapper.</param> public void Register(Type type, int typeId, IBinaryNameMapper converter, IBinaryIdMapper idMapper) { if (type.GetInterface(typeof(IBinarizable).Name) != null) return; List<FieldInfo> fields = new List<FieldInfo>(); Type curType = type; while (curType != null) { foreach (FieldInfo field in curType.GetFields(Flags)) { if (!field.IsNotSerialized) fields.Add(field); } curType = curType.BaseType; } IDictionary<int, string> idMap = new Dictionary<int, string>(); foreach (FieldInfo field in fields) { string fieldName = BinaryUtils.CleanFieldName(field.Name); int fieldId = BinaryUtils.FieldId(typeId, fieldName, converter, idMapper); if (idMap.ContainsKey(fieldId)) { throw new BinaryObjectException("Conflicting field IDs [type=" + type.Name + ", field1=" + idMap[fieldId] + ", field2=" + fieldName + ", fieldId=" + fieldId + ']'); } idMap[fieldId] = fieldName; } fields.Sort(Compare); Descriptor desc = new Descriptor(fields); _types[type] = desc; } /// <summary> /// Gets the descriptor for an object. /// </summary> private Descriptor GetDescriptor(object obj) { var type = obj.GetType(); Descriptor desc; if (!_types.TryGetValue(type, out desc)) throw new BinaryObjectException("Type is not registered in serializer: " + type.Name); return desc; } /// <summary> /// Compare two FieldInfo instances. /// </summary> private static int Compare(FieldInfo info1, FieldInfo info2) { string name1 = BinaryUtils.CleanFieldName(info1.Name); string name2 = BinaryUtils.CleanFieldName(info2.Name); return string.Compare(name1, name2, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Type descriptor. /// </summary> private class Descriptor { /** Write actions to be performed. */ private readonly List<BinaryReflectiveWriteAction> _wActions; /** Read actions to be performed. */ private readonly List<BinaryReflectiveReadAction> _rActions; /// <summary> /// Constructor. /// </summary> /// <param name="fields">Fields.</param> public Descriptor(List<FieldInfo> fields) { _wActions = new List<BinaryReflectiveWriteAction>(fields.Count); _rActions = new List<BinaryReflectiveReadAction>(fields.Count); foreach (FieldInfo field in fields) { BinaryReflectiveWriteAction writeAction; BinaryReflectiveReadAction readAction; BinaryReflectiveActions.TypeActions(field, out writeAction, out readAction); _wActions.Add(writeAction); _rActions.Add(readAction); } } /// <summary> /// Write object. /// </summary> /// <param name="obj">Object.</param> /// <param name="writer">Writer.</param> public void Write(object obj, IBinaryWriter writer) { int cnt = _wActions.Count; for (int i = 0; i < cnt; i++) _wActions[i](obj, writer); } /// <summary> /// Read object. /// </summary> /// <param name="obj">Object.</param> /// <param name="reader">Reader.</param> public void Read(object obj, IBinaryReader reader) { int cnt = _rActions.Count; for (int i = 0; i < cnt; i++ ) _rActions[i](obj, reader); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Threading.Tasks; using appMpower.Db; namespace appMpower { public static class RawDb { private const int MaxBatch = 500; private static Random _random = new Random(); private static string[] _queriesMultipleRows = new string[MaxBatch + 1]; public static async Task<World> LoadSingleQueryRow() { var pooledConnection = await PooledConnections.GetConnection(ConnectionStrings.OdbcConnection); pooledConnection.Open(); var (pooledCommand, _) = CreateReadCommand(pooledConnection); var world = await ReadSingleRow(pooledCommand); pooledCommand.Release(); pooledConnection.Release(); return world; } public static async Task<World[]> LoadMultipleQueriesRows(int count) { var worlds = new World[count]; var pooledConnection = await PooledConnections.GetConnection(ConnectionStrings.OdbcConnection); pooledConnection.Open(); var (pooledCommand, dbDataParameter) = CreateReadCommand(pooledConnection); for (int i = 0; i < count; i++) { worlds[i] = await ReadSingleRow(pooledCommand); dbDataParameter.Value = _random.Next(1, 10001); } pooledCommand.Release(); pooledConnection.Release(); return worlds; } public static async Task<List<Fortune>> LoadFortunesRows() { var fortunes = new List<Fortune>(); var pooledConnection = await PooledConnections.GetConnection(ConnectionStrings.OdbcConnection); pooledConnection.Open(); var pooledCommand = new PooledCommand("SELECT * FROM fortune", pooledConnection); var dataReader = await pooledCommand.ExecuteReaderAsync(CommandBehavior.SingleResult); while (dataReader.Read()) { fortunes.Add(new Fortune ( id: dataReader.GetInt32(0), message: dataReader.GetString(1) )); } dataReader.Close(); pooledCommand.Release(); pooledConnection.Release(); fortunes.Add(new Fortune(id: 0, message: "Additional fortune added at request time.")); fortunes.Sort(); return fortunes; } public static async Task<World[]> LoadMultipleUpdatesRows(int count) { var worlds = new World[count]; var pooledConnection = await PooledConnections.GetConnection(ConnectionStrings.OdbcConnection); pooledConnection.Open(); var (queryCommand, dbDataParameter) = CreateReadCommand(pooledConnection); for (int i = 0; i < count; i++) { worlds[i] = await ReadSingleRow(queryCommand); dbDataParameter.Value = _random.Next(1, 10001); } queryCommand.Release(); var updateCommand = new PooledCommand(PlatformBenchmarks.BatchUpdateString.Query(count), pooledConnection); var ids = PlatformBenchmarks.BatchUpdateString.Ids; var randoms = PlatformBenchmarks.BatchUpdateString.Randoms; // --- only for alternative update statement - will be used for MySQL //var jds = PlatformBenchmarks.BatchUpdateString.Jds; for (int i = 0; i < count; i++) { var randomNumber = _random.Next(1, 10001); updateCommand.CreateParameter(ids[i], DbType.Int32, worlds[i].Id); updateCommand.CreateParameter(randoms[i], DbType.Int32, randomNumber); worlds[i].RandomNumber = randomNumber; } // --- only for alternative update statement - will be used for MySQL //for (int i = 0; i < count; i++) //{ // updateCommand.CreateParameter(jds[i], DbType.Int32, worlds[i].Id); //} await updateCommand.ExecuteNonQueryAsync(); updateCommand.Release(); pooledConnection.Release(); return worlds; } private static (PooledCommand pooledCommand, IDbDataParameter dbDataParameter) CreateReadCommand(PooledConnection pooledConnection) { var pooledCommand = new PooledCommand("SELECT * FROM world WHERE id=?", pooledConnection); var dbDataParameter = pooledCommand.CreateParameter("@Id", DbType.Int32, _random.Next(1, 10001)); return (pooledCommand, dbDataParameter); } private static async Task<World> ReadSingleRow(PooledCommand pooledCommand) { var dataReader = await pooledCommand.ExecuteReaderAsync(CommandBehavior.SingleRow); dataReader.Read(); var world = new World { Id = dataReader.GetInt32(0), RandomNumber = dataReader.GetInt32(1) }; dataReader.Close(); return world; } public static async Task<World[]> ReadMultipleRows(int count) { int j = 0; var ids = PlatformBenchmarks.BatchUpdateString.Ids; var worlds = new World[count]; string queryString; if (_queriesMultipleRows[count] != null) { queryString = _queriesMultipleRows[count]; } else { var stringBuilder = PlatformBenchmarks.StringBuilderCache.Acquire(); for (int i = 0; i < count; i++) { stringBuilder.Append("SELECT * FROM world WHERE id=?;"); } queryString = _queriesMultipleRows[count] = PlatformBenchmarks.StringBuilderCache.GetStringAndRelease(stringBuilder); } var pooledConnection = await PooledConnections.GetConnection(ConnectionStrings.OdbcConnection); pooledConnection.Open(); var pooledCommand = new PooledCommand(queryString, pooledConnection); for (int i = 0; i < count; i++) { pooledCommand.CreateParameter(ids[i], DbType.Int32, _random.Next(1, 10001)); } var dataReader = await pooledCommand.ExecuteReaderAsync(CommandBehavior.Default); do { dataReader.Read(); worlds[j] = new World { Id = dataReader.GetInt32(0), RandomNumber = dataReader.GetInt32(1) }; j++; } while (await dataReader.NextResultAsync()); dataReader.Close(); pooledCommand.Release(); pooledConnection.Release(); return worlds; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Internal.LightweightInterop; namespace Internal.StackGenerator.Dia { internal sealed class IDiaDataSource : ComInterface { public IDiaDataSource(IntPtr punk) : base(punk) { } public int LoadDataFromPdb(String pdbPath) { unsafe { fixed (char* _pdbPath = pdbPath) { int hr = S.StdCall<int>(GetVTableMember(4), Punk, _pdbPath); GC.KeepAlive(this); return hr; } } } public int OpenSession(out IDiaSession session) { session = null; IntPtr _session; int hr = S.StdCall<int>(GetVTableMember(8), Punk, out _session); GC.KeepAlive(this); if (hr != S_OK) return hr; session = new IDiaSession(_session); return hr; } } internal sealed class IDiaSession : ComInterface { public IDiaSession(IntPtr punk) : base(punk) { } public int FindChildren(IDiaSymbol parent, SymTagEnum symTag, String name, NameSearchOptions compareFlags, out IDiaEnumSymbols enumSymbols) { enumSymbols = null; IntPtr _enumSymbols; int hr; unsafe { fixed (char* _name = name) { hr = S.StdCall<int>(GetVTableMember(8), Punk, parent.Punk, (int)symTag, _name, (int)compareFlags, out _enumSymbols); } } GC.KeepAlive(this); GC.KeepAlive(parent); if (hr != S_OK) return hr; enumSymbols = new IDiaEnumSymbols(_enumSymbols); return hr; } public int FindSymbolByRVA(int rva, SymTagEnum symTag, out IDiaSymbol symbol) { symbol = null; IntPtr _symbol; int hr = S.StdCall<int>(GetVTableMember(14), Punk, rva, (int)symTag, out _symbol); GC.KeepAlive(this); if (hr != S_OK) return hr; symbol = new IDiaSymbol(_symbol); return hr; } public int FindLinesByRVA(int rva, int length, out IDiaEnumLineNumbers enumLineNumbers) { enumLineNumbers = null; IntPtr _enumLineNumbers; int hr = S.StdCall<int>(GetVTableMember(25), Punk, rva, length, out _enumLineNumbers); GC.KeepAlive(this); if (hr != S_OK) return hr; enumLineNumbers = new IDiaEnumLineNumbers(_enumLineNumbers); return hr; } } internal sealed class IDiaEnumSymbols : ComInterface { public IDiaEnumSymbols(IntPtr punk) : base(punk) { } public int Count(out int count) { int hr = S.StdCall<int>(GetVTableMember(4), Punk, out count); GC.KeepAlive(this); return hr; } public int Item(int index, out IDiaSymbol symbol) { symbol = null; IntPtr pSymbol; int hr = S.StdCall<int>(GetVTableMember(5), Punk, index, out pSymbol); GC.KeepAlive(this); if (hr != S_OK) return hr; symbol = new IDiaSymbol(pSymbol); return hr; } } internal sealed class IDiaSymbol : ComInterface { public IDiaSymbol(IntPtr punk) : base(punk) { } public int GetSymTag(out SymTagEnum symTagEnum) { symTagEnum = default(SymTagEnum); int _symTagEnum; int hr = S.StdCall<int>(GetVTableMember(4), Punk, out _symTagEnum); GC.KeepAlive(this); symTagEnum = (SymTagEnum)_symTagEnum; return hr; } public int GetName(out String name) { name = null; IntPtr _name; int hr = S.StdCall<int>(GetVTableMember(5), Punk, out _name); GC.KeepAlive(this); if (hr != S_OK) return hr; name = _name.MarshalBstr(); return hr; } public int GetType(out IDiaSymbol symbol) { symbol = null; IntPtr _symbol; int hr = S.StdCall<int>(GetVTableMember(8), Punk, out _symbol); GC.KeepAlive(this); if (hr != S_OK) return hr; symbol = new IDiaSymbol(_symbol); return hr; } public int GetDataKind(out DataKind dataKind) { dataKind = default(DataKind); int _dataKindEnum; int hr = S.StdCall<int>(GetVTableMember(9), Punk, out _dataKindEnum); GC.KeepAlive(this); dataKind = (DataKind)_dataKindEnum; return hr; } public int GetReference(out bool isReference) { isReference = false; int _isReference; int hr = S.StdCall<int>(GetVTableMember(48), Punk, out _isReference); GC.KeepAlive(this); isReference = (_isReference != 0); return hr; } public int GetBaseType(out BasicType baseType) { baseType = default(BasicType); int _baseType; int hr = S.StdCall<int>(GetVTableMember(43), Punk, out _baseType); GC.KeepAlive(this); baseType = (BasicType)_baseType; return hr; } public int GetLength(out long length) { int hr = S.StdCall<int>(GetVTableMember(17), Punk, out length); GC.KeepAlive(this); return hr; } } internal sealed class IDiaEnumLineNumbers : ComInterface { public IDiaEnumLineNumbers(IntPtr punk) : base(punk) { } public int Count(out int count) { int hr = S.StdCall<int>(GetVTableMember(4), Punk, out count); GC.KeepAlive(this); return hr; } public int Item(int index, out IDiaLineNumber lineNumber) { lineNumber = null; IntPtr pLineNumber; int hr = S.StdCall<int>(GetVTableMember(5), Punk, index, out pLineNumber); GC.KeepAlive(this); if (hr != S_OK) return hr; lineNumber = new IDiaLineNumber(pLineNumber); return hr; } } internal sealed class IDiaLineNumber : ComInterface { public IDiaLineNumber(IntPtr punk) : base(punk) { } public int SourceFile(out IDiaSourceFile sourceFile) { sourceFile = null; IntPtr _sourceFile; int hr = S.StdCall<int>(GetVTableMember(4), Punk, out _sourceFile); GC.KeepAlive(this); if (hr != S_OK) return hr; sourceFile = new IDiaSourceFile(_sourceFile); return hr; } public int LineNumber(out int lineNumber) { int hr = S.StdCall<int>(GetVTableMember(5), Punk, out lineNumber); GC.KeepAlive(this); return hr; } public int ColumnNumber(out int columnNumber) { int hr = S.StdCall<int>(GetVTableMember(7), Punk, out columnNumber); GC.KeepAlive(this); return hr; } } internal sealed class IDiaSourceFile : ComInterface { public IDiaSourceFile(IntPtr punk) : base(punk) { } public int FileName(out String fileName) { fileName = null; IntPtr _fileName; int hr = S.StdCall<int>(GetVTableMember(4), Punk, out _fileName); GC.KeepAlive(this); if (hr != S_OK) return hr; fileName = _fileName.MarshalBstr(); return hr; } } }
/* created on 01.10.2008 17:11:16 from peg generator V1.0 using 'BERTree_peg.txt' as input*/ using Peg.Base; using System; using System.IO; using System.Text; namespace BERTree { enum EBERTree{ProtocolDataUnit= 1, TLV= 2, ConstructedLengthValue= 30, Tag= 3, TagWithConstructedFlag= 4, OneOctetTag= 5, MultiOctetTag= 6, Length= 7, OneOctetLength= 8, NoLength= 9, MultiOctetLength= 10, PrimitiveValue= 11, ConstructedDelimValue= 12, ConstructedValue= 13}; class BERTree : PegByteParser { class Top { internal int @byte; internal int tag, length, n,tagclass; internal bool init_() { tag = 0; length = 0; return true; } internal bool add_Tag_() { tag *= 128; tag += n; return true; } internal bool addLength_() { length *= 256; length+= @byte;return true; } } Top top; #region CREATE #region overrides public override string TreeNodeToString(PegNode node) { string s= GetRuleNameFromId(node.id_); BERTreeNode berNode= node as BERTreeNode; if( berNode!=null ) s+= ": " + berNode.TreeNodeToString(src_); return s; } #endregion overrides #region PegNode subclasses for BERTree abstract class BERTreeNode : PegNode { internal BERTreeNode(PegNode parent, int id): base(parent, id){} internal abstract string TreeNodeToString(byte[] src); } class TagNode : BERTreeNode { internal TagNode(PegNode parent, int id) : base(parent, id) {tagValue_ = -1;} internal override string TreeNodeToString(byte[] src) {return tagValue_.ToString();} internal int tagValue_; } class LengthNode : BERTreeNode { internal LengthNode(PegNode parent, int id) : base(parent, id) { lengthValue_ = 0;} internal override string TreeNodeToString(byte[] src) { if (lengthValue_ <= 0) return "\u221E"; return lengthValue_.ToString(); } internal int lengthValue_; } class PrimitiveValueNode : BERTreeNode { const int maxShow = 16; internal PrimitiveValueNode(PegNode parent, int id) : base(parent, id) { } bool GetAsInteger(byte[] src, out string sInt) { int len = match_.Length, pos0 = match_.posBeg_, pos1 = match_.posEnd_; sInt = ""; if (len == 0 || src[pos0] == 0 && len > 1 && (src[pos0 + 1] & 0x80) == 0) return false; long val = (src[pos0] & 0x80) != 0 ? -1 : 0; for (; pos0 != pos1; ++pos0) { val <<= 8; val |= src[pos0]; } sInt = val.ToString(); return true; } string GetAsAsciiString(byte[] src) { int pos0 = match_.posBeg_, pos1 = match_.posEnd_; if (pos1 - pos0 > 16) pos1 = pos0 + 16; StringBuilder sb= new StringBuilder(); for (; pos0 < pos1; ++pos0){ if (src[pos0] <= 0x7F && !char.IsControl(((char)src[pos0]))){ sb.Append((char)src[pos0]); } else{ sb.Append('.'); } } if (match_.posEnd_ > pos1) sb.Append("..."); return sb.ToString(); } internal override string TreeNodeToString(byte[] src) { string display=""; if (match_.Length <= 8 && GetAsInteger(src, out display)){ display += " / "; } display += GetAsAsciiString(src); return display; } } #endregion PegNode subclasses for BERTree PegNode TagNodeCreator(ECreatorPhase phase,PegNode parentOrCreated, int id) { if (phase == ECreatorPhase.eCreate || phase == ECreatorPhase.eCreateAndComplete){ return new TagNode(parentOrCreated, id); }else{ ((TagNode)parentOrCreated).tagValue_ = top.tag; return null; } } PegNode LengthNodeCreator(ECreatorPhase phase,PegNode parentOrCreated, int id) { if (phase == ECreatorPhase.eCreate || phase == ECreatorPhase.eCreateAndComplete){ return new LengthNode(parentOrCreated, id); }else{ ((LengthNode)parentOrCreated).lengthValue_ = top.length; return null; } } PegNode PrimitiveValueNodeCreator(ECreatorPhase phase, PegNode parentOrCreated, int id) { if (phase == ECreatorPhase.eCreate || phase == ECreatorPhase.eCreateAndComplete) { return new PrimitiveValueNode(parentOrCreated, id); } else { return null; } } #endregion CREATE #region Input Properties public static EncodingClass encodingClass = EncodingClass.binary; public static UnicodeDetection unicodeDetection = UnicodeDetection.notApplicable; #endregion Input Properties #region Constructors public BERTree() : base() { top= new Top(); } public BERTree(byte[] src,TextWriter FerrOut) : base(src,FerrOut) { top= new Top(); } #endregion Constructors #region Overrides public override string GetRuleNameFromId(int id) { try { EBERTree ruleEnum = (EBERTree)id; string s= ruleEnum.ToString(); int val; if( int.TryParse(s,out val) ){ return base.GetRuleNameFromId(id); }else{ return s; } } catch (Exception) { return base.GetRuleNameFromId(id); } } public override void GetProperties(out EncodingClass encoding, out UnicodeDetection detection) { encoding = encodingClass; detection = unicodeDetection; } #endregion Overrides #region Grammar Rules public bool ProtocolDataUnit() /*[1] ProtocolDataUnit: TLV;*/ { return TLV(); } public bool TLV() /*[2] ^^TLV: init_ ( TagWithConstructedFlag ConstructedLengthValue / Tag Length PrimitiveValue );*/ { return TreeNT((int)EBERTree.TLV,()=> And(()=> top.init_() && ( And(()=> TagWithConstructedFlag() && ConstructedLengthValue() ) || And(()=> Tag() && Length() && PrimitiveValue() )) ) ); } public bool ConstructedLengthValue() /*[30]ConstructedLengthValue: NoLength ConstructedDelimValue @(#0#0) / Length ConstructedValue;*/ { return And(()=> NoLength() && ConstructedDelimValue() && ( And(()=> Char(0x0000) && Char(0x0000) ) || Fatal("<<(#0#0)>> expected")) ) || And(()=> Length() && ConstructedValue() ); } public bool Tag() /*[3]Tag: &BITS<7-8,.,:tagclass> (OneOctetTag / MultiOctetTag / FATAL<"illegal TAG">);*/ { return And(()=> Peek(()=> BitsInto(7,8,out top.tagclass) ) && ( OneOctetTag() || MultiOctetTag() || Fatal("illegal TAG")) ); } public bool TagWithConstructedFlag() /*[4] TagWithConstructedFlag: &BITS<6,#1> Tag;*/ { return And(()=> PeekBit(6,0x0001) && Tag() ); } public bool OneOctetTag() /*[5] ^^CREATE<TagNodeCreator> OneOctetTag: !BITS<1-5,#b11111> BITS<1-5,.,:tag>;*/ { return TreeNT(TagNodeCreator,(int)EBERTree.OneOctetTag,()=> And(()=> NotBits(1,5,0x001f) && BitsInto(1,5,out top.tag) ) ); } public bool MultiOctetTag() /*[6] ^^CREATE<TagNodeCreator> MultiOctetTag: . (&BITS<8,#1> BITS<1-7,.,:n> add_Tag_)* BITS<1-7,.,:n> add_Tag_;*/ { return TreeNT(TagNodeCreator,(int)EBERTree.MultiOctetTag,()=> And(()=> Any() && OptRepeat(()=> And(()=> PeekBit(8,0x0001) && BitsInto(1,7,out top.n) && top.add_Tag_() ) ) && BitsInto(1,7,out top.n) && top.add_Tag_() ) ); } public bool Length() /*[7] Length : OneOctetLength / NoLength / MultiOctetLength / FATAL<"illegal LENGTH">;*/ { return OneOctetLength() || NoLength() || MultiOctetLength() || Fatal("illegal LENGTH"); } public bool OneOctetLength() /*[8]^^CREATE<LengthNodeCreator> OneOctetLength: &BITS<8,#0> BITS<1-7,.,:length>;*/ { return TreeNT(LengthNodeCreator,(int)EBERTree.OneOctetLength,()=> And(()=> PeekBit(8,0x0000) && BitsInto(1,7,out top.length) ) ); } public bool NoLength() /*[9]^^CREATE<LengthNodeCreator> NoLength: #x80;*/ { return TreeNT(LengthNodeCreator,(int)EBERTree.NoLength,()=> Char(0x0080) ); } public bool MultiOctetLength() /*[10]^^CREATE<LengthNodeCreator> MultiOctetLength: &BITS<8,#1> BITS<1-7,.,:n> (( .:byte addLength_){:n}/FATAL<"illegal Length">) ;*/ { return TreeNT(LengthNodeCreator,(int)EBERTree.MultiOctetLength,()=> And(()=> PeekBit(8,0x0001) && BitsInto(1,7,out top.n) && ( ForRepeat(top.n,top.n,()=> And(()=> Into(()=> Any(),out top.@byte) && top.addLength_() ) ) || Fatal("illegal Length")) ) ); } public bool PrimitiveValue() /*[11]^^CREATE<PrimitiveValueNodeCreator> PrimitiveValue: (.{:length} / FATAL<"BER input ends before VALUE ends">);*/ { return TreeNT(PrimitiveValueNodeCreator,(int)EBERTree.PrimitiveValue,()=> ForRepeat(top.length,top.length,()=> Any() ) || Fatal("BER input ends before VALUE ends") ); } public bool ConstructedDelimValue() /*[12]^^ConstructedDelimValue: (!(#0#0) TLV)*;*/ { return TreeNT((int)EBERTree.ConstructedDelimValue,()=> OptRepeat(()=> And(()=> Not(()=> And(()=> Char(0x0000) && Char(0x0000) ) ) && TLV() ) ) ); } class _ConstructedValue{ internal _ConstructedValue(BERTree ber) { parent = ber; len = 0; begEnd.posBeg_ = 0; begEnd.posEnd_ = 0; } BERTree parent; int len; internal PegBegEnd begEnd; internal bool save_() { len = parent.top.length; return true; } internal bool at_end_() { return len <= 0; } internal bool decr_() { len -= begEnd.posEnd_ - begEnd.posBeg_; return len >= 0; } } public bool ConstructedValue() /*[13]^^ConstructedValue { internal _ConstructedValue(BERTree ber) { parent = ber; len = 0; begEnd.posBeg_ = 0; begEnd.posEnd_ = 0; } BERTree parent; int len; PegBegEnd begEnd; bool save_() { len = parent.top.length; return true; } bool at_end_() { return len <= 0; } bool decr_() { len -= begEnd.posEnd_ - begEnd.posBeg_; return len >= 0; } }: save_ (!at_end_ TLV:begEnd (decr_/FATAL<"illegal length">))*;*/ { var _sem= new _ConstructedValue(this); return TreeNT((int)EBERTree.ConstructedValue,()=> And(()=> _sem.save_() && OptRepeat(()=> And(()=> Not(()=> _sem.at_end_() ) && Into(()=> TLV(),out _sem.begEnd) && ( _sem.decr_() || Fatal("illegal length")) ) ) ) ); } #endregion Grammar Rules } }
/* | Version 10.1.84 | Copyright 2013 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.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Text; using ESRI.ArcLogistics.DomainObjects.Attributes; using ESRI.ArcLogistics.DomainObjects.Validation; namespace ESRI.ArcLogistics.DomainObjects { /// <summary> /// Class that represents a break with specific time window. /// </summary> public class TimeWindowBreak : Break { #region Constructors /// <summary> /// Initializes a new instance of the <c>TimeWindowBreak</c> class. /// </summary> public TimeWindowBreak() { // Set defaults. var from = new TimeSpan (DEFAULT_FROM_HOURS, 0, 0); var to = new TimeSpan(DEFAULT_TO_HOURS, 0, 0); _timeWindow = new TimeWindow(from, to); Duration = DefautDuration; } #endregion // Constructors #region Public static properties /// <summary> /// Gets name of the To property. /// </summary> public static string PropertyNameTo { get { return PROP_NAME_TO; } } /// <summary> /// Gets name of the Day property. /// </summary> public static string PropertyNameDay { get { return PROP_NAME_DAY; } } /// <summary> /// Gets name of the From property. /// </summary> public static string PropertyNameFrom { get { return PROP_NAME_FROM; } } #endregion // Public static properties #region Public members /// <summary> /// Time of day when the time window opens. /// </summary> public TimeSpan From { get { return _timeWindow.From; } set { if (value != _timeWindow.From) { _timeWindow.From = value; _NotifyPropertyChanged(PROP_NAME_FROM); } } } /// <summary> /// Time of day when the time window closes. /// </summary> /// <remarks> /// If <c>To</c> value is less than <c>From</c> value then this means that the time window closes at the specified time but on the next day. /// </remarks> [TimeWindowValidator] public TimeSpan To { get { return _timeWindow.To; } set { if (value != _timeWindow.To) { _timeWindow.To = value; _NotifyPropertyChanged(PROP_NAME_TO); } } } /// <summary> /// Day of the break. /// </summary> public uint Day { get { return _timeWindow.Day; } set { if (value != _timeWindow.Day) { _timeWindow.Day = value; _NotifyPropertyChanged(PROP_NAME_DAY); } } } /// <summary> /// Gets time passed since planned date midnight till the start of break. /// </summary> public TimeSpan EffectiveFrom { get { return _timeWindow.EffectiveFrom; } } /// <summary> /// Gets time passed since planned date midnight till the end of break. /// </summary> public TimeSpan EffectiveTo { get { return _timeWindow.EffectiveTo; } } /// <summary> /// Returns a string representation of the break information. /// </summary> /// <returns>Break's representation string.</returns> public override string ToString() { string timeWindow = _timeWindow.ToString(); return string.Format(Properties.Resources.TimeWindowBrakeFormat, base.ToString(), timeWindow); } #endregion #region ICloneable members /// <summary> /// Clones the <c>TimeWindowBreak</c> object. /// </summary> /// <returns>Cloned object.</returns> public override object Clone() { var obj = new TimeWindowBreak(); obj.To = this.To; obj.From = this.From; obj.Duration = this.Duration; obj.Day = this.Day; return obj; } #endregion #region Internal overrided methods /// <summary> /// Check that both breaks have same types and same Duration, To and From values. /// </summary> /// <param name="breakObject">Brake to compare with this.</param> /// <returns>'True' if breaks types and Duration, To and From /// values are the same, 'false' otherwise.</returns> internal override bool EqualsByValue(Break breakObject) { TimeWindowBreak breakToCompare = breakObject as TimeWindowBreak; return breakToCompare != null && base.EqualsByValue(breakObject) && breakToCompare.From == this.From && breakToCompare.To == this.To; } /// <summary> /// Converts state of this instance to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance.</returns> internal override string ConvertToString() { CultureInfo cultureInfo = CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE); var result = new StringBuilder(); // 0. Current version result.Append(VERSION_CURR.ToString()); // 1. Duration result.Append(CommonHelpers.SEPARATOR); result.Append(Duration.ToString(cultureInfo)); // 2. TW.From result.Append(CommonHelpers.SEPARATOR); result.Append(From.ToString()); // 3. TW.To result.Append(CommonHelpers.SEPARATOR); result.Append(To.ToString()); // 4. Day result.Append(CommonHelpers.SEPARATOR); result.Append(Day.ToString()); return result.ToString(); } /// <summary> /// Converts the string representation of a break to break internal state equivalent. /// </summary> /// <param name="context">String representation of a break.</param> internal override void InitFromString(string context) { if (null != context) { char[] valuesSeparator = new char[1] { CommonHelpers.SEPARATOR }; string[] values = context.Split(valuesSeparator, StringSplitOptions.None); Debug.Assert((3 <= values.Length) && (values.Length <= 5)); CultureInfo cultureInfo = CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE); int index = 0; int version = 0; // If we have 4 or more parts, this break is versioned. if (values.Length >= 4) { version = int.Parse(values[0]); ++index; // 0 - index is version // first version has 3 elements } // 1. Duration this.Duration = double.Parse(values[index], cultureInfo); // 2. TW.From From = TimeSpan.Parse(values[++index]); // 3. TW.To To = TimeSpan.Parse(values[++index]); // 4. Day if (version >= VERSION_2) Day = uint.Parse(values[++index]); else Day = 0; } } /// <summary> /// Method occured, when breaks collection changed. Need for validation. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> protected override void BreaksCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { // If breaks collection changed - raise notify property // changed for "To" property for all breaks in this collection. _NotifyPropertyChanged(PropertyNameTo); } #endregion // Internal overrided methods #region Private methods /// <summary> /// Notifies about change of the From property. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Property changed event arguments.</param> private void _FromPropertyChanged(object sender, PropertyChangedEventArgs e) { _NotifyPropertyChanged(e.PropertyName); _NotifyPropertyChanged(PropertyNameFrom); } /// <summary> /// Notifies about change of the To property. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Property changed event arguments.</param> private void _ToPropertyChanged(object sender, PropertyChangedEventArgs e) { _NotifyPropertyChanged(e.PropertyName); _NotifyPropertyChanged(PropertyNameTo); } #endregion #region Private constants /// <summary> /// Name of the From property. /// </summary> private const string PROP_NAME_FROM = "From"; /// <summary> /// Name of the To property. /// </summary> private const string PROP_NAME_TO = "To"; /// <summary> /// Name of the To property. /// </summary> private const string PROP_NAME_DAY = "Day"; /// <summary> /// Default start hour. /// </summary> private const int DEFAULT_FROM_HOURS = 11; /// <summary> /// Default end hour. /// </summary> private const int DEFAULT_TO_HOURS = 13; /// <summary> /// Storage schema version 1. /// </summary> private const int VERSION_1 = 0x00000001; /// <summary> /// Storage schema version 2. /// </summary> private const int VERSION_2 = 0x00000002; /// <summary> /// Storage schema current version. /// </summary> private const int VERSION_CURR = VERSION_2; #endregion #region Private members private TimeWindow _timeWindow; #endregion } }
namespace GraphLib { partial class PlotterDisplayEx { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PlotterDisplayEx)); this.tb1 = new System.Windows.Forms.ToolBar(); this.tbbSave = new System.Windows.Forms.ToolBarButton(); this.tbbOpen = new System.Windows.Forms.ToolBarButton(); this.tbbSeparator3 = new System.Windows.Forms.ToolBarButton(); this.tbbPrint = new System.Windows.Forms.ToolBarButton(); this.toolBarButton2 = new System.Windows.Forms.ToolBarButton(); this.imgList1 = new System.Windows.Forms.ImageList(this.components); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.lb_Position = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.hScrollBar2 = new System.Windows.Forms.HScrollBar(); this.hScrollBar1 = new System.Windows.Forms.HScrollBar(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.selectGraphsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.panel1 = new System.Windows.Forms.Panel(); this.gPane = new GraphLib.PlotterGraphPaneEx(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // tb1 // this.tb1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.tb1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.tbbSave, this.tbbOpen, this.tbbSeparator3, this.tbbPrint, this.toolBarButton2}); this.tb1.ButtonSize = new System.Drawing.Size(16, 16); this.tb1.Divider = false; this.tb1.Dock = System.Windows.Forms.DockStyle.None; this.tb1.DropDownArrows = true; this.tb1.ImageList = this.imgList1; this.tb1.Location = new System.Drawing.Point(11, 5); this.tb1.Name = "tb1"; this.tb1.ShowToolTips = true; this.tb1.Size = new System.Drawing.Size(80, 26); this.tb1.TabIndex = 1; this.tb1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.tb1_ButtonClick); // // tbbSave // this.tbbSave.ImageIndex = 0; this.tbbSave.Name = "tbbSave"; this.tbbSave.Tag = "play"; // // tbbOpen // this.tbbOpen.ImageIndex = 1; this.tbbOpen.Name = "tbbOpen"; this.tbbOpen.Tag = "stop"; // // tbbSeparator3 // this.tbbSeparator3.Name = "tbbSeparator3"; this.tbbSeparator3.Style = System.Windows.Forms.ToolBarButtonStyle.Separator; // // tbbPrint // this.tbbPrint.ImageIndex = 3; this.tbbPrint.Name = "tbbPrint"; this.tbbPrint.Tag = "print"; // // toolBarButton2 // this.toolBarButton2.Name = "toolBarButton2"; this.toolBarButton2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator; // // imgList1 // this.imgList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgList1.ImageStream"))); this.imgList1.TransparentColor = System.Drawing.Color.Transparent; this.imgList1.Images.SetKeyName(0, "media-playback-start.png"); this.imgList1.Images.SetKeyName(1, "media-playback-stop.png"); this.imgList1.Images.SetKeyName(2, "media-playback-pause.png"); this.imgList1.Images.SetKeyName(3, "printer.png"); // // splitContainer1 // this.splitContainer1.BackColor = System.Drawing.SystemColors.Control; this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer1.IsSplitterFixed = true; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.splitContainer1.Panel1.Controls.Add(this.tb1); this.splitContainer1.Panel1.Controls.Add(this.panel1); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.BackColor = System.Drawing.Color.Transparent; this.splitContainer1.Panel2.Controls.Add(this.gPane); this.splitContainer1.Size = new System.Drawing.Size(598, 339); this.splitContainer1.SplitterDistance = 34; this.splitContainer1.TabIndex = 2; this.splitContainer1.TabStop = false; // // lb_Position // this.lb_Position.AutoSize = true; this.lb_Position.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.lb_Position.Location = new System.Drawing.Point(6, 8); this.lb_Position.Name = "lb_Position"; this.lb_Position.Size = new System.Drawing.Size(44, 13); this.lb_Position.TabIndex = 3; this.lb_Position.Text = "Position"; // // label1 // this.label1.AutoSize = true; this.label1.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label1.Location = new System.Drawing.Point(180, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(85, 13); this.label1.TabIndex = 2; this.label1.Text = "Playback Speed"; // // hScrollBar2 // this.hScrollBar2.Location = new System.Drawing.Point(268, 10); this.hScrollBar2.Maximum = 10000; this.hScrollBar2.Name = "hScrollBar2"; this.hScrollBar2.Size = new System.Drawing.Size(111, 10); this.hScrollBar2.TabIndex = 6; this.hScrollBar2.Value = 1; this.hScrollBar2.Scroll += new System.Windows.Forms.ScrollEventHandler(this.OnScrollBarSpeedScroll); // // hScrollBar1 // this.hScrollBar1.Location = new System.Drawing.Point(57, 10); this.hScrollBar1.Maximum = 10000; this.hScrollBar1.Name = "hScrollBar1"; this.hScrollBar1.Size = new System.Drawing.Size(118, 10); this.hScrollBar1.TabIndex = 4; this.hScrollBar1.Scroll += new System.Windows.Forms.ScrollEventHandler(this.OnScrollbarScroll); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.selectGraphsToolStripMenuItem, this.toolStripSeparator1}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(117, 32); // // selectGraphsToolStripMenuItem // this.selectGraphsToolStripMenuItem.Name = "selectGraphsToolStripMenuItem"; this.selectGraphsToolStripMenuItem.Size = new System.Drawing.Size(116, 22); this.selectGraphsToolStripMenuItem.Text = "Options"; this.selectGraphsToolStripMenuItem.Click += new System.EventHandler(this.selectGraphsToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(113, 6); // // panel1 // this.panel1.Controls.Add(this.lb_Position); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.hScrollBar1); this.panel1.Controls.Add(this.hScrollBar2); this.panel1.Location = new System.Drawing.Point(99, 3); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(496, 28); this.panel1.TabIndex = 7; // // gPane // this.gPane.Dock = System.Windows.Forms.DockStyle.Fill; this.gPane.Location = new System.Drawing.Point(0, 0); this.gPane.Name = "gPane"; this.gPane.Size = new System.Drawing.Size(598, 301); this.gPane.TabIndex = 1; // // PlotterDisplayEx // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Transparent; this.ContextMenuStrip = this.contextMenuStrip1; this.Controls.Add(this.splitContainer1); this.Name = "PlotterDisplayEx"; this.Size = new System.Drawing.Size(598, 339); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel1.PerformLayout(); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.contextMenuStrip1.ResumeLayout(false); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolBar tb1; private System.Windows.Forms.ToolBarButton tbbSeparator3; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.ToolBarButton tbbSave; private System.Windows.Forms.ToolBarButton tbbOpen; private System.Windows.Forms.HScrollBar hScrollBar1; private PlotterGraphPaneEx gPane; private System.Windows.Forms.HScrollBar hScrollBar2; private System.Windows.Forms.Label lb_Position; private System.Windows.Forms.Label label1; public System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem selectGraphsToolStripMenuItem; private System.Windows.Forms.ImageList imgList1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolBarButton tbbPrint; private System.Windows.Forms.ToolBarButton toolBarButton2; private System.Windows.Forms.Panel panel1; } }
using NLog; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Forms; using System.Windows.Interop; using Wox.Infrastructure; using Wox.Infrastructure.Logger; using Application = System.Windows.Application; using Control = System.Windows.Controls.Control; using FormsApplication = System.Windows.Forms.Application; using MessageBox = System.Windows.MessageBox; namespace Wox.Plugin.Sys { public class Main : IPlugin, ISettingProvider, IPluginI18n { private PluginInitContext context; #region DllImport internal const int EWX_LOGOFF = 0x00000000; internal const int EWX_SHUTDOWN = 0x00000001; internal const int EWX_REBOOT = 0x00000002; internal const int EWX_FORCE = 0x00000004; internal const int EWX_POWEROFF = 0x00000008; internal const int EWX_FORCEIFHUNG = 0x00000010; [DllImport("user32")] private static extern bool ExitWindowsEx(uint uFlags, uint dwReason); [DllImport("user32")] private static extern void LockWorkStation(); [DllImport("Shell32.dll", CharSet = CharSet.Unicode)] private static extern uint SHEmptyRecycleBin(IntPtr hWnd, uint dwFlags); // http://www.pinvoke.net/default.aspx/Enums/HRESULT.html private enum HRESULT : uint { S_FALSE = 0x0001, S_OK = 0x0000 } #endregion private static readonly NLog.Logger Logger = LogManager.GetCurrentClassLogger(); public Control CreateSettingPanel() { var results = Commands(); return new SysSettings(results); } public List<Result> Query(Query query) { var commands = Commands(); var results = new List<Result>(); foreach (var c in commands) { var titleMatch = StringMatcher.FuzzySearch(query.Search, c.Title); if (titleMatch.Score > 0) { c.Score = titleMatch.Score; c.TitleHighlightData = titleMatch.MatchData; results.Add(c); } } return results; } public void Init(PluginInitContext context) { this.context = context; } private List<Result> Commands() { var results = new List<Result>(); results.AddRange(new[] { new Result { Title = "Shutdown", SubTitle = context.API.GetTranslation("wox_plugin_sys_shutdown_computer"), IcoPath = "Images\\shutdown.png", Action = c => { var reuslt = MessageBox.Show(context.API.GetTranslation("wox_plugin_sys_dlgtext_shutdown_computer"), context.API.GetTranslation("wox_plugin_sys_shutdown_computer"), MessageBoxButton.YesNo, MessageBoxImage.Warning); if (reuslt == MessageBoxResult.Yes) { Process.Start("shutdown", "/s /hybrid /t 0"); } return true; } }, new Result { Title = "Restart", SubTitle = context.API.GetTranslation("wox_plugin_sys_restart_computer"), IcoPath = "Images\\restart.png", Action = c => { var result = MessageBox.Show(context.API.GetTranslation("wox_plugin_sys_dlgtext_restart_computer"), context.API.GetTranslation("wox_plugin_sys_restart_computer"), MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.Yes) { Process.Start("shutdown", "/r /t 0"); } return true; } }, new Result { Title = "Log Off", SubTitle = context.API.GetTranslation("wox_plugin_sys_log_off"), IcoPath = "Images\\logoff.png", Action = c => ExitWindowsEx(EWX_LOGOFF, 0) }, new Result { Title = "Lock", SubTitle = context.API.GetTranslation("wox_plugin_sys_lock"), IcoPath = "Images\\lock.png", Action = c => { LockWorkStation(); return true; } }, new Result { Title = "Sleep", SubTitle = context.API.GetTranslation("wox_plugin_sys_sleep"), IcoPath = "Images\\sleep.png", Action = c => FormsApplication.SetSuspendState(PowerState.Suspend, false, false) }, new Result { Title = "Hibernate", SubTitle = context.API.GetTranslation("wox_plugin_sys_hibernate"), IcoPath = "Images\\sleep.png", // Icon change needed Action = c => FormsApplication.SetSuspendState(PowerState.Hibernate, false, false) }, new Result { Title = "Empty Recycle Bin", SubTitle = context.API.GetTranslation("wox_plugin_sys_emptyrecyclebin"), IcoPath = "Images\\recyclebin.png", Action = c => { // http://www.pinvoke.net/default.aspx/shell32/SHEmptyRecycleBin.html // FYI, couldn't find documentation for this but if the recycle bin is already empty, it will return -2147418113 (0x8000FFFF (E_UNEXPECTED)) // 0 for nothing var result = SHEmptyRecycleBin(new WindowInteropHelper(Application.Current.MainWindow).Handle, 0); if (result != (uint) HRESULT.S_OK && result != (uint)0x8000FFFF) { MessageBox.Show($"Error emptying recycle bin, error code: {result}\n" + "please refer to https://msdn.microsoft.com/en-us/library/windows/desktop/aa378137", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } return true; } }, new Result { Title = "Exit", SubTitle = context.API.GetTranslation("wox_plugin_sys_exit"), IcoPath = "Images\\app.png", Action = c => { Application.Current.MainWindow.Close(); return true; } }, new Result { Title = "Save Settings", SubTitle = context.API.GetTranslation("wox_plugin_sys_save_all_settings"), IcoPath = "Images\\app.png", Action = c => { context.API.SaveAppAllSettings(); context.API.ShowMsg(context.API.GetTranslation("wox_plugin_sys_dlgtitle_success"), context.API.GetTranslation("wox_plugin_sys_dlgtext_all_settings_saved")); return true; } }, new Result { Title = "Restart Wox", SubTitle = context.API.GetTranslation("wox_plugin_sys_restart"), IcoPath = "Images\\app.png", Action = c => { context.API.RestarApp(); return false; } }, new Result { Title = "Settings", SubTitle = context.API.GetTranslation("wox_plugin_sys_setting"), IcoPath = "Images\\app.png", Action = c => { context.API.OpenSettingDialog(); return true; } }, new Result { Title = "Reload Plugin Data", SubTitle = context.API.GetTranslation("wox_plugin_sys_reload_plugin_data"), IcoPath = "Images\\app.png", Action = c => { // Hide the window first then show msg after done because sometimes the reload could take a while, so not to make user think it's frozen. Application.Current.MainWindow.Hide(); context.API.ReloadAllPluginData(); context.API.ShowMsg(context.API.GetTranslation("wox_plugin_sys_dlgtitle_success"), context.API.GetTranslation("wox_plugin_sys_dlgtext_all_applicableplugins_reloaded")); return true; } }, new Result { PluginDirectory = context.CurrentPluginMetadata.PluginDirectory, Title = "Check For Update", SubTitle = "Check for new Wox update", IcoPath = "Images\\update.png", Action = c => { Application.Current.MainWindow.Hide(); context.API.CheckForNewUpdate(); context.API.ShowMsg("Please wait...", "Checking for new update"); return true; } } }); return results; } public string GetTranslatedPluginTitle() { return context.API.GetTranslation("wox_plugin_sys_plugin_name"); } public string GetTranslatedPluginDescription() { return context.API.GetTranslation("wox_plugin_sys_plugin_description"); } } }
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 Aurora.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace IdentityBase.EntityFramework.IntegrationTests.Stores { using System; using System.Collections.Generic; using System.Linq; using IdentityBase.EntityFramework.Configuration; using IdentityBase.EntityFramework.DbContexts; using IdentityBase.EntityFramework.Mappers; using IdentityBase.EntityFramework.Stores; using IdentityBase.Models; using Microsoft.EntityFrameworkCore; using ServiceBase.Logging; using Xunit; [Collection("UserAccountStoreTests")] public class UserAccountStoreTests : IClassFixture<DatabaseProviderFixture<UserAccountDbContext>> { private static readonly EntityFrameworkOptions StoreOptions = new EntityFrameworkOptions(); public static readonly TheoryData<DbContextOptions<UserAccountDbContext>> TestDatabaseProviders = new TheoryData<DbContextOptions<UserAccountDbContext>> { DatabaseProviderBuilder.BuildInMemory<UserAccountDbContext>( nameof(UserAccountStoreTests), StoreOptions), DatabaseProviderBuilder.BuildSqlite<UserAccountDbContext>( nameof(UserAccountStoreTests), StoreOptions), DatabaseProviderBuilder.BuildSqlServer<UserAccountDbContext>( nameof(UserAccountStoreTests), StoreOptions) }; public UserAccountStoreTests( DatabaseProviderFixture<UserAccountDbContext> fixture) { fixture.Options = TestDatabaseProviders .SelectMany(x => x .Select(y => (DbContextOptions<UserAccountDbContext>)y)) .ToList(); fixture.StoreOptions = StoreOptions; } [Theory, MemberData(nameof(TestDatabaseProviders))] public void LoadByIdAsync_WhenUserAccountExists_ExpectUserAccountRetured( DbContextOptions<UserAccountDbContext> options) { var testUserAccount = new UserAccount { Id = Guid.NewGuid(), Email = "[email protected]" }; using (var context = new UserAccountDbContext(options, StoreOptions)) { context.UserAccounts.Add(testUserAccount.ToEntity()); context.SaveChanges(); } UserAccount userAccount; using (var context = new UserAccountDbContext(options, StoreOptions)) { var store = new UserAccountStore( context, NullLogger<UserAccountStore>.Create()); userAccount = store.LoadByIdAsync(testUserAccount.Id).Result; } Assert.NotNull(userAccount); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void LoadByEmailAsync_WhenUserAccountExists_ExpectUserAccountRetured( DbContextOptions<UserAccountDbContext> options) { var testUserAccount = new UserAccount { Email = "[email protected]" }; using (var context = new UserAccountDbContext(options, StoreOptions)) { context.UserAccounts.Add(testUserAccount.ToEntity()); context.SaveChanges(); } UserAccount userAccount; using (var context = new UserAccountDbContext(options, StoreOptions)) { var store = new UserAccountStore( context, NullLogger<UserAccountStore>.Create() ); userAccount = store .LoadByEmailAsync(testUserAccount.Email).Result; } Assert.NotNull(userAccount); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void LoadByVerificationKeyAsync_WhenUserAccountExists_ExpectUserAccountRetured( DbContextOptions<UserAccountDbContext> options) { var testUserAccount = new UserAccount { Id = Guid.NewGuid(), Email = "[email protected]", VerificationKey = Guid.NewGuid().ToString() }; using (var context = new UserAccountDbContext(options, StoreOptions)) { context.UserAccounts.Add(testUserAccount.ToEntity()); context.SaveChanges(); } UserAccount userAccount; using (var context = new UserAccountDbContext(options, StoreOptions)) { var store = new UserAccountStore( context, NullLogger<UserAccountStore>.Create() ); userAccount = store.LoadByVerificationKeyAsync( testUserAccount.VerificationKey).Result; } Assert.NotNull(userAccount); } [Theory, MemberData(nameof(TestDatabaseProviders))] public void LoadByExternalProviderAsync_WhenUserAccountExists_ExpectUserAccountRetured( DbContextOptions<UserAccountDbContext> options) { var testExternalAccount = new ExternalAccount { Email = "[email protected]", Provider = "yahoo", Subject = "123456789" }; var testUserAccount = new UserAccount { Id = Guid.NewGuid(), Email = "[email protected]", Accounts = new List<ExternalAccount> { testExternalAccount } }; using (var context = new UserAccountDbContext(options, StoreOptions)) { context.UserAccounts.Add(testUserAccount.ToEntity()); context.SaveChanges(); } UserAccount userAccount; using (var context = new UserAccountDbContext(options, StoreOptions)) { var store = new UserAccountStore( context, NullLogger<UserAccountStore>.Create() ); userAccount = store.LoadByExternalProviderAsync( testExternalAccount.Provider, testExternalAccount.Subject).Result; } Assert.NotNull(userAccount); } // Create user account [Theory, MemberData(nameof(TestDatabaseProviders))] public void Create_UserAccount( DbContextOptions<UserAccountDbContext> options) { var userAccount1 = new UserAccount { Id = Guid.NewGuid(), Email = "[email protected]", Accounts = new List<ExternalAccount> { new ExternalAccount { Email = "[email protected]", Provider = "facebook", Subject = "123456712", }, new ExternalAccount { Email = "[email protected]", Provider = "google", Subject = "789456111", } }, Claims = new List<UserAccountClaim> { new UserAccountClaim("name", "foo"), new UserAccountClaim("email", "[email protected]"), } }; using (var context = new UserAccountDbContext(options, StoreOptions)) { var store = new UserAccountStore( context, NullLogger<UserAccountStore>.Create() ); // Write user account UserAccount userAccount2 = store.WriteAsync(userAccount1).Result; // Assert user account Assert.NotNull(userAccount2); // TODO: check other fields // Assert claims Assert.Equal(2, userAccount2.Claims.Count()); Assert.NotNull(userAccount2.Claims.FirstOrDefault(c => c.Type.Equals("name") && c.Value.Equals("foo"))); Assert.NotNull(userAccount2.Claims.FirstOrDefault(c => c.Type.Equals("email") && c.Value.Equals("[email protected]"))); // Assert external accounts Assert.Equal(2, userAccount2.Accounts.Count()); Assert.NotNull(userAccount2.Accounts.FirstOrDefault(c => c.Email.Equals("[email protected]") && c.Provider.Equals("facebook") && c.Subject.Equals("123456712"))); Assert.NotNull(userAccount2.Accounts.FirstOrDefault(c => c.Email.Equals("[email protected]") && c.Provider.Equals("google") && c.Subject.Equals("789456111"))); } } // Delete user account [Theory, MemberData(nameof(TestDatabaseProviders))] public void Delete_UserAccount( DbContextOptions<UserAccountDbContext> options) { var userAccountId = Guid.NewGuid(); using (var context = new UserAccountDbContext(options, StoreOptions)) { var userAccount1 = new UserAccount { Id = userAccountId, Email = "[email protected]", Accounts = new List<ExternalAccount> { new ExternalAccount { Email = "[email protected]", Provider = "facebook", Subject = "123456712", }, new ExternalAccount { Email = "[email protected]", Provider = "google", Subject = "789456111", } }, Claims = new List<UserAccountClaim> { new UserAccountClaim("name", "foo"), new UserAccountClaim("email", "[email protected]"), } }; context.UserAccounts.Add(userAccount1.ToEntity()); context.SaveChanges(); } using (var context = new UserAccountDbContext(options, StoreOptions)) { var store = new UserAccountStore( context, NullLogger<UserAccountStore>.Create() ); store.DeleteByIdAsync(userAccountId).Wait(); } using (var context = new UserAccountDbContext(options, StoreOptions)) { Assert.Null(context.UserAccounts .FirstOrDefault(c => c.Id.Equals(userAccountId))); Assert.Null(context.ExternalAccounts .FirstOrDefault(c => c.UserAccountId.Equals(userAccountId))); Assert.Null(context.UserAccountClaims .FirstOrDefault(c => c.UserAccountId.Equals(userAccountId))); } } } [Collection("UserAccountStoreTests")] public class UserAccountStore2Tests : IClassFixture<DatabaseProviderFixture<UserAccountDbContext>> { private static readonly EntityFrameworkOptions StoreOptions = new EntityFrameworkOptions(); public static readonly TheoryData<DbContextOptions<UserAccountDbContext>> TestDatabaseProviders = new TheoryData<DbContextOptions<UserAccountDbContext>> { DatabaseProviderBuilder.BuildInMemory<UserAccountDbContext>( nameof(UserAccountStoreTests), StoreOptions), DatabaseProviderBuilder.BuildSqlite<UserAccountDbContext>( nameof(UserAccountStoreTests), StoreOptions), DatabaseProviderBuilder.BuildSqlServer<UserAccountDbContext>( nameof(UserAccountStoreTests), StoreOptions) }; public UserAccountStore2Tests( DatabaseProviderFixture<UserAccountDbContext> fixture) { fixture.Options = TestDatabaseProviders .SelectMany(x => x .Select(y => (DbContextOptions<UserAccountDbContext>)y)) .ToList(); fixture.StoreOptions = StoreOptions; } // Update user account [Theory, MemberData(nameof(TestDatabaseProviders))] public void Update_UserAccount( DbContextOptions<UserAccountDbContext> options) { var userAccountId = Guid.NewGuid(); var now = DateTime.Now; using (var context = new UserAccountDbContext(options, StoreOptions)) { var userAccount1 = new UserAccount { Id = userAccountId, Email = "[email protected]", Accounts = new List<ExternalAccount> { new ExternalAccount { Email = "[email protected]", Provider = "facebook", Subject = "123456712", }, new ExternalAccount { Email = "[email protected]", Provider = "google", Subject = "789456111", } }, Claims = new List<UserAccountClaim> { new UserAccountClaim("name", "foo"), new UserAccountClaim("email", "[email protected]"), } }; context.UserAccounts.Add(userAccount1.ToEntity()); context.SaveChanges(); } using (var context = new UserAccountDbContext(options, StoreOptions)) { var store = new UserAccountStore( context, NullLogger<UserAccountStore>.Create() ); var userAccount2 = store.LoadByIdAsync(userAccountId).Result; userAccount2.VerificationKeySentAt = now; userAccount2.VerificationPurpose = 1; userAccount2.VerificationStorage = "hallo welt"; var claims = userAccount2.Claims as List<UserAccountClaim>; // Update one claim claims.FirstOrDefault(c => c.Type.Equals("name") && c.Value.Equals("foo")) .Value = "bar"; // Remove another claim claims.Remove(claims .FirstOrDefault(c => c.Type.Equals("email"))); // Add one extra claim // claims.Add(new UserAccountClaim("bar", "baz")); var accounts = userAccount2.Accounts as List<ExternalAccount>; // Update one external account accounts.FirstOrDefault(c => c.Email.Equals("[email protected]") && c.Provider.Equals("facebook") && c.Subject.Equals("123456712")) .Email = "[email protected]"; // remove another external account accounts.Remove(accounts.FirstOrDefault(c => c.Email.Equals("[email protected]") && c.Provider.Equals("google") && c.Subject.Equals("789456111"))); //// Add one extra external account //accounts.Add(new ExternalAccount //{ // Email = "[email protected]", // Provider = "yahoo", // Subject = "654987132", //}); var userAccount3 = store.WriteAsync(userAccount2).Result; } using (var context = new UserAccountDbContext(options, StoreOptions)) { var store = new UserAccountStore( context, NullLogger<UserAccountStore>.Create() ); var userAccount4 = store.LoadByIdAsync(userAccountId).Result; Assert.NotNull(userAccount4); Assert.Equal(now, userAccount4.VerificationKeySentAt); Assert.Equal(1, userAccount4.VerificationPurpose); Assert.Equal("hallo welt", userAccount4.VerificationStorage); /* // Assert claims Assert.Equal(2, userAccount4.Claims.Count()); Assert.NotNull(userAccount4.Claims.FirstOrDefault(c => c.Type.Equals("name") && c.Value.Equals("bar"))); Assert.NotNull(userAccount4.Claims.FirstOrDefault(c => c.Type.Equals("bar") && c.Value.Equals("baz"))); // Assert external accounts Assert.Equal(2, userAccount4.Accounts.Count()); Assert.NotNull(userAccount4.Accounts.FirstOrDefault(c => c.Email.Equals("[email protected]") && c.Provider.Equals("facebook") && c.Subject.Equals("123456712"))); Assert.NotNull(userAccount4.Accounts.FirstOrDefault(c => c.Email.Equals("[email protected]") && c.Provider.Equals("yahoo") && c.Subject.Equals("654987132")));*/ } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Web; using ASC.Core; using ASC.Core.Common; using ASC.Core.Users; using ASC.Security.Cryptography; using ASC.Web.Core; using ASC.Web.Core.WhiteLabel; namespace ASC.Web.Studio.Utility { public enum ManagementType { General = 0, Customization = 1, ProductsAndInstruments = 2, PortalSecurity = 3, AccessRights = 4, Backup = 5, LoginHistory = 6, AuditTrail = 7, LdapSettings = 8, ThirdPartyAuthorization = 9, SmtpSettings = 10, Statistic = 11, Monitoring = 12, SingleSignOnSettings = 13, Migration = 14, DeletionPortal = 15, HelpCenter = 16, DocService = 17, FullTextSearch = 18, WhiteLabel = 19, MailService = 20, Storage = 21, PrivacyRoom = 22 } // emp-invite - confirm ivite by email // portal-suspend - confirm portal suspending - Tenant.SetStatus(TenantStatus.Suspended) // portal-continue - confirm portal continuation - Tenant.SetStatus(TenantStatus.Active) // portal-remove - confirm portal deletation - Tenant.SetStatus(TenantStatus.RemovePending) // DnsChange - change Portal Address and/or Custom domain name public enum ConfirmType { EmpInvite, LinkInvite, PortalSuspend, PortalContinue, PortalRemove, DnsChange, PortalOwnerChange, Activation, EmailChange, EmailActivation, PasswordChange, ProfileRemove, PhoneActivation, PhoneAuth, Auth, TfaActivation, TfaAuth } public static class CommonLinkUtility { private static readonly Regex RegFilePathTrim = new Regex("/[^/]*\\.aspx", RegexOptions.IgnoreCase | RegexOptions.Compiled); public const string ParamName_ProductSysName = "product"; public const string ParamName_UserUserName = "user"; public const string ParamName_UserUserID = "uid"; public static void Initialize(string serverUri, bool localhost = true) { BaseCommonLinkUtility.Initialize(serverUri, localhost); } public static string VirtualRoot { get { return BaseCommonLinkUtility.VirtualRoot; } } public static string ServerRootPath { get { return BaseCommonLinkUtility.ServerRootPath; } } public static string GetFullAbsolutePath(string virtualPath) { return BaseCommonLinkUtility.GetFullAbsolutePath(virtualPath); } public static string ToAbsolute(string virtualPath) { return BaseCommonLinkUtility.ToAbsolute(virtualPath); } public static string Logout { get { return ToAbsolute("~/Auth.aspx") + "?t=logout"; } } public static string GetDefault() { return VirtualRoot; } public static string GetMyStaff() { return CoreContext.Configuration.Personal ? ToAbsolute("~/My.aspx") : ToAbsolute("~/Products/People/Profile.aspx"); } public static string GetEmployees() { return GetEmployees(EmployeeStatus.Active); } public static string GetEmployees(EmployeeStatus empStatus) { return ToAbsolute("~/Products/People/") + (empStatus == EmployeeStatus.Terminated ? "#type=disabled" : string.Empty); } public static string GetDepartment(Guid depId) { return depId != Guid.Empty ? ToAbsolute("~/Products/People/#group=") + depId.ToString() : GetEmployees(); } #region user profile link public static string GetUserProfile() { return GetUserProfile(null); } public static string GetUserProfile(Guid userID) { if (!CoreContext.UserManager.UserExists(userID)) return GetEmployees(); return GetUserProfile(userID.ToString()); } public static string GetUserProfile(string user) { return GetUserProfile(user, true); } public static string GetUserProfile(string user, bool absolute) { var queryParams = ""; if (!String.IsNullOrEmpty(user)) { var guid = Guid.Empty; if (!String.IsNullOrEmpty(user) && 32 <= user.Length && user[8] == '-') { try { guid = new Guid(user); } catch { } } queryParams = guid != Guid.Empty ? GetUserParamsPair(guid) : ParamName_UserUserName + "=" + HttpUtility.UrlEncode(user); } var url = absolute ? ToAbsolute("~/Products/People/") : "/Products/People/"; url += "Profile.aspx?"; url += queryParams; return url; } #endregion public static Guid GetProductID() { var productID = Guid.Empty; if (HttpContext.Current != null) { IProduct product; IModule module; GetLocationByRequest(out product, out module); if (product != null) productID = product.ID; } return productID; } public static Guid GetAddonID() { var addonID = Guid.Empty; if (HttpContext.Current != null) { var addonName = GetAddonNameFromUrl(HttpContext.Current.Request.Url.AbsoluteUri); switch (addonName) { case "mail": addonID = WebItemManager.MailProductID; break; case "talk": addonID = WebItemManager.TalkProductID; break; case "calendar": addonID = WebItemManager.CalendarProductID; break; default: break; } } return addonID; } public static void GetLocationByRequest(out IProduct currentProduct, out IModule currentModule) { GetLocationByRequest(out currentProduct, out currentModule, HttpContext.Current); } public static void GetLocationByRequest(out IProduct currentProduct, out IModule currentModule, HttpContext context) { var currentURL = string.Empty; if (context != null && context.Request != null) { currentURL = HttpContext.Current.Request.GetUrlRewriter().AbsoluteUri; // http://[hostname]/[virtualpath]/[AjaxPro.Utility.HandlerPath]/[assembly],[classname].ashx if (currentURL.Contains("/" + AjaxPro.Utility.HandlerPath + "/") && HttpContext.Current.Request.UrlReferrer != null) { currentURL = HttpContext.Current.Request.UrlReferrer.AbsoluteUri; } } GetLocationByUrl(currentURL, out currentProduct, out currentModule); } public static IWebItem GetWebItemByUrl(string currentURL) { if (!String.IsNullOrEmpty(currentURL)) { var itemName = GetWebItemNameFromUrl(currentURL); if (!string.IsNullOrEmpty(itemName)) { foreach (var item in WebItemManager.Instance.GetItemsAll()) { var _itemName = GetWebItemNameFromUrl(item.StartURL); if (String.Compare(itemName, _itemName, StringComparison.InvariantCultureIgnoreCase) == 0) return item; } } else { var urlParams = HttpUtility.ParseQueryString(new Uri(currentURL).Query); var productByName = GetProductBySysName(urlParams[ParamName_ProductSysName]); var pid = productByName == null ? Guid.Empty : productByName.ID; if (pid == Guid.Empty && !String.IsNullOrEmpty(urlParams["pid"])) { try { pid = new Guid(urlParams["pid"]); } catch { pid = Guid.Empty; } } if (pid != Guid.Empty) return WebItemManager.Instance[pid]; } } return null; } public static void GetLocationByUrl(string currentURL, out IProduct currentProduct, out IModule currentModule) { currentProduct = null; currentModule = null; if (String.IsNullOrEmpty(currentURL)) return; var urlParams = HttpUtility.ParseQueryString(new Uri(currentURL).Query); var productByName = GetProductBySysName(urlParams[ParamName_ProductSysName]); var pid = productByName == null ? Guid.Empty : productByName.ID; if (pid == Guid.Empty && !String.IsNullOrEmpty(urlParams["pid"])) { try { pid = new Guid(urlParams["pid"]); } catch { pid = Guid.Empty; } } var productName = GetProductNameFromUrl(currentURL); var moduleName = GetModuleNameFromUrl(currentURL); if (!string.IsNullOrEmpty(productName) || !string.IsNullOrEmpty(moduleName)) { foreach (var product in WebItemManager.Instance.GetItemsAll<IProduct>()) { var _productName = GetProductNameFromUrl(product.StartURL); if (!string.IsNullOrEmpty(_productName)) { if (String.Compare(productName, _productName, StringComparison.InvariantCultureIgnoreCase) == 0) { currentProduct = product; if (!String.IsNullOrEmpty(moduleName)) { foreach (var module in WebItemManager.Instance.GetSubItems(product.ID).OfType<IModule>()) { var _moduleName = GetModuleNameFromUrl(module.StartURL); if (!string.IsNullOrEmpty(_moduleName)) { if (String.Compare(moduleName, _moduleName, StringComparison.InvariantCultureIgnoreCase) == 0) { currentModule = module; break; } } } } else { foreach (var module in WebItemManager.Instance.GetSubItems(product.ID).OfType<IModule>()) { if (!module.StartURL.Equals(product.StartURL) && currentURL.Contains(RegFilePathTrim.Replace(module.StartURL, string.Empty))) { currentModule = module; break; } } } break; } } } } if (pid != Guid.Empty) currentProduct = WebItemManager.Instance[pid] as IProduct; } private static string GetWebItemNameFromUrl(string url) { var name = GetModuleNameFromUrl(url); if (String.IsNullOrEmpty(name)) { name = GetProductNameFromUrl(url); if (String.IsNullOrEmpty(name)) { return GetAddonNameFromUrl(url); } } return name; } private static string GetProductNameFromUrl(string url) { try { var pos = url.IndexOf("/Products/", StringComparison.InvariantCultureIgnoreCase); if (0 <= pos) { url = url.Substring(pos + 10).ToLower(); pos = url.IndexOf('/'); return 0 < pos ? url.Substring(0, pos) : url; } } catch { } return null; } private static string GetAddonNameFromUrl(string url) { try { var pos = url.IndexOf("/addons/", StringComparison.InvariantCultureIgnoreCase); if (0 <= pos) { url = url.Substring(pos + 8).ToLower(); pos = url.IndexOf('/'); return 0 < pos ? url.Substring(0, pos) : url; } } catch { } return null; } private static string GetModuleNameFromUrl(string url) { try { var pos = url.IndexOf("/Modules/", StringComparison.InvariantCultureIgnoreCase); if (0 <= pos) { url = url.Substring(pos + 9).ToLower(); pos = url.IndexOf('/'); return 0 < pos ? url.Substring(0, pos) : url; } } catch { } return null; } private static IProduct GetProductBySysName(string sysName) { IProduct result = null; if (!String.IsNullOrEmpty(sysName)) foreach (var product in WebItemManager.Instance.GetItemsAll<IProduct>()) { if (String.CompareOrdinal(sysName, WebItemExtension.GetSysName(product as IWebItem)) == 0) { result = product; break; } } return result; } public static string GetUserParamsPair(Guid userID) { return CoreContext.UserManager.UserExists(userID) ? GetUserParamsPair(CoreContext.UserManager.GetUsers(userID)) : ""; } public static string GetUserParamsPair(UserInfo user) { if (user == null || string.IsNullOrEmpty(user.UserName)) return ""; return String.Format("{0}={1}", ParamName_UserUserName, HttpUtility.UrlEncode(user.UserName.ToLowerInvariant())); } #region Help Centr public static string GetHelpLink(bool inCurrentCulture = true) { if (!AdditionalWhiteLabelSettings.Instance.HelpCenterEnabled) return String.Empty; var url = AdditionalWhiteLabelSettings.DefaultHelpCenterUrl; if (String.IsNullOrEmpty(url)) return String.Empty; return GetRegionalUrl(url, inCurrentCulture ? CultureInfo.CurrentCulture.TwoLetterISOLanguageName : null); } public static string GetRegionalUrl(string url, string lang) { if (String.IsNullOrEmpty(url)) return url; //-replace language var regex = new Regex("{.*?}"); var matches = regex.Matches(url); if (String.IsNullOrEmpty(lang)) { url = matches.Cast<Match>().Aggregate(url, (current, match) => current.Replace(match.Value, String.Empty)); } else { foreach (Match match in matches) { var values = match.Value.TrimStart('{').TrimEnd('}').Split('|'); url = url.Replace(match.Value, values.Contains(lang) ? lang : String.Empty); } } //- //--remove redundant slashes var uri = new Uri(url); if (uri.Scheme == "mailto") return uri.OriginalString; var baseUri = new UriBuilder(uri.Scheme, uri.Host, uri.Port).Uri; baseUri = uri.Segments.Aggregate(baseUri, (current, segment) => new Uri(current, segment)); //-- //todo: lost query string!!! return baseUri.ToString().TrimEnd('/'); } #endregion #region management links public static string GetAdministration(ManagementType managementType) { if (managementType == ManagementType.General) return ToAbsolute("~/Management.aspx") + string.Empty; return ToAbsolute("~/Management.aspx") + "?" + "type=" + ((int)managementType).ToString(); } #endregion #region confirm links public static string GetConfirmationUrl(string email, ConfirmType confirmType, object postfix = null, Guid userId = default(Guid)) { return GetFullAbsolutePath(GetConfirmationUrlRelative(CoreContext.TenantManager.GetCurrentTenant().TenantId, email, confirmType, postfix, userId)); } public static string GetConfirmationUrlRelative(int tenantId, string email, ConfirmType confirmType, object postfix = null, Guid userId = default(Guid)) { var validationKey = EmailValidationKeyProvider.GetEmailKey(tenantId, email + confirmType + (postfix ?? "")); var link = string.Format("confirm.aspx?type={0}&key={1}", confirmType, validationKey); if (!string.IsNullOrEmpty(email)) { link += "&email=" + HttpUtility.UrlEncode(email); } if (userId != default(Guid)) { link += "&uid=" + userId; } return link; } #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph.Core.Test.Requests { using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Mocks; using Moq; [TestClass] public class HttpProviderTests { private HttpProvider httpProvider; private MockSerializer serializer = new MockSerializer(); private TestHttpMessageHandler testHttpMessageHandler; [TestInitialize] public void Setup() { this.testHttpMessageHandler = new TestHttpMessageHandler(); this.httpProvider = new HttpProvider(this.testHttpMessageHandler, true, this.serializer.Object); } [TestCleanup] public void Teardown() { this.httpProvider.Dispose(); } [TestMethod] public void HttpProvider_CustomCacheHeaderAndTimeout() { var timeout = TimeSpan.FromSeconds(200); var cacheHeader = new CacheControlHeaderValue(); using (var defaultHttpProvider = new HttpProvider(null) { CacheControlHeader = cacheHeader, OverallTimeout = timeout }) { Assert.IsFalse(defaultHttpProvider.httpClient.DefaultRequestHeaders.CacheControl.NoCache, "NoCache true."); Assert.IsFalse(defaultHttpProvider.httpClient.DefaultRequestHeaders.CacheControl.NoStore, "NoStore true."); Assert.AreEqual(timeout, defaultHttpProvider.httpClient.Timeout, "Unexpected default timeout set."); Assert.IsNotNull(defaultHttpProvider.Serializer, "Serializer not initialized."); Assert.IsInstanceOfType(defaultHttpProvider.Serializer, typeof(Serializer), "Unexpected serializer initialized."); } } [TestMethod] public void HttpProvider_CustomHttpClientHandler() { using (var httpClientHandler = new HttpClientHandler()) using (var httpProvider = new HttpProvider(httpClientHandler, false, null)) { Assert.AreEqual(httpClientHandler, httpProvider.httpMessageHandler, "Unexpected message handler set."); Assert.IsFalse(httpProvider.disposeHandler, "Dispose handler set to true."); } } [TestMethod] public void HttpProvider_DefaultConstructor() { using (var defaultHttpProvider = new HttpProvider()) { Assert.IsTrue(defaultHttpProvider.httpClient.DefaultRequestHeaders.CacheControl.NoCache, "NoCache false."); Assert.IsTrue(defaultHttpProvider.httpClient.DefaultRequestHeaders.CacheControl.NoStore, "NoStore false."); Assert.IsTrue(defaultHttpProvider.disposeHandler, "Dispose handler set to false."); Assert.IsNotNull(defaultHttpProvider.httpMessageHandler, "HttpClientHandler not initialized."); Assert.IsFalse(((HttpClientHandler)defaultHttpProvider.httpMessageHandler).AllowAutoRedirect, "AllowAutoRedirect set to true."); Assert.AreEqual(TimeSpan.FromSeconds(100), defaultHttpProvider.httpClient.Timeout, "Unexpected default timeout set."); Assert.IsInstanceOfType(defaultHttpProvider.Serializer, typeof(Serializer), "Unexpected serializer initialized."); } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task OverallTimeout_RequestAlreadySent() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) using (var httpResponseMessage = new HttpResponseMessage()) { this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage); var returnedResponseMessage = await this.httpProvider.SendAsync(httpRequestMessage); } try { this.httpProvider.OverallTimeout = new TimeSpan(0, 0, 30); } catch (ServiceException serviceException) { Assert.IsTrue(serviceException.IsMatch(ErrorConstants.Codes.NotAllowed), "Unexpected error code thrown."); Assert.AreEqual( ErrorConstants.Messages.OverallTimeoutCannotBeSet, serviceException.Error.Message, "Unexpected error message thrown."); Assert.IsInstanceOfType(serviceException.InnerException, typeof(InvalidOperationException), "Unexpected inner exception thrown."); throw; } } [TestMethod] public async Task SendAsync() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) using (var httpResponseMessage = new HttpResponseMessage()) { this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage); var returnedResponseMessage = await this.httpProvider.SendAsync(httpRequestMessage); Assert.AreEqual(httpResponseMessage, returnedResponseMessage, "Unexpected response returned."); } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task SendAsync_ClientGeneralException() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) { this.httpProvider.Dispose(); var clientException = new Exception(); this.httpProvider = new HttpProvider(new ExceptionHttpMessageHandler(clientException), /* disposeHandler */ true, null); try { await this.httpProvider.SendRequestAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None); } catch (ServiceException exception) { Assert.IsTrue(exception.IsMatch(ErrorConstants.Codes.GeneralException), "Unexpected error code returned."); Assert.AreEqual(ErrorConstants.Messages.UnexpectedExceptionOnSend, exception.Error.Message, "Unexpected error message."); Assert.AreEqual(clientException, exception.InnerException, "Inner exception not set."); throw; } } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task SendAsync_ClientTimeout() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) { this.httpProvider.Dispose(); var clientException = new TaskCanceledException(); this.httpProvider = new HttpProvider(new ExceptionHttpMessageHandler(clientException), /* disposeHandler */ true, null); try { await this.httpProvider.SendRequestAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None); } catch (ServiceException exception) { Assert.IsTrue(exception.IsMatch(ErrorConstants.Codes.Timeout), "Unexpected error code returned."); Assert.AreEqual(ErrorConstants.Messages.RequestTimedOut, exception.Error.Message, "Unexpected error message."); Assert.AreEqual(clientException, exception.InnerException, "Inner exception not set."); throw; } } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task SendAsync_InvalidRedirectResponse() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) using (var httpResponseMessage = new HttpResponseMessage()) { httpResponseMessage.StatusCode = HttpStatusCode.Redirect; httpResponseMessage.RequestMessage = httpRequestMessage; this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage); try { var returnedResponseMessage = await this.httpProvider.SendAsync(httpRequestMessage); } catch (ServiceException exception) { Assert.IsTrue(exception.IsMatch(ErrorConstants.Codes.GeneralException), "Unexpected error code returned."); Assert.AreEqual( ErrorConstants.Messages.LocationHeaderNotSetOnRedirect, exception.Error.Message, "Unexpected error message returned."); throw; } } } [TestMethod] public async Task SendAsync_RedirectResponse_VerifyHeadersOnRedirect() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) using (var redirectResponseMessage = new HttpResponseMessage()) using (var finalResponseMessage = new HttpResponseMessage()) { httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", "token"); httpRequestMessage.Headers.Add("testHeader", "testValue"); httpRequestMessage.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true, NoStore = true }; redirectResponseMessage.StatusCode = HttpStatusCode.Redirect; redirectResponseMessage.Headers.Location = new Uri("https://localhost/redirect"); redirectResponseMessage.RequestMessage = httpRequestMessage; this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), redirectResponseMessage); this.testHttpMessageHandler.AddResponseMapping(redirectResponseMessage.Headers.Location.ToString(), finalResponseMessage); var returnedResponseMessage = await this.httpProvider.SendAsync(httpRequestMessage); Assert.AreEqual(3, finalResponseMessage.RequestMessage.Headers.Count(), "Unexpected number of headers on redirect request message."); foreach (var header in httpRequestMessage.Headers) { var actualValues = finalResponseMessage.RequestMessage.Headers.GetValues(header.Key); Assert.AreEqual(actualValues.Count(), header.Value.Count(), "Unexpected header on redirect request message."); foreach (var headerValue in header.Value) { Assert.IsTrue(actualValues.Contains(headerValue), "Unexpected header on redirect request message."); } } } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task SendAsync_MaxRedirects() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) using (var redirectResponseMessage = new HttpResponseMessage()) using (var tooManyRedirectsResponseMessage = new HttpResponseMessage()) { redirectResponseMessage.StatusCode = HttpStatusCode.Redirect; redirectResponseMessage.Headers.Location = new Uri("https://localhost/redirect"); tooManyRedirectsResponseMessage.StatusCode = HttpStatusCode.Redirect; redirectResponseMessage.RequestMessage = httpRequestMessage; this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), redirectResponseMessage); this.testHttpMessageHandler.AddResponseMapping(redirectResponseMessage.Headers.Location.ToString(), tooManyRedirectsResponseMessage); httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue(CoreConstants.Headers.Bearer, "ticket"); try { await this.httpProvider.HandleRedirect( redirectResponseMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None, 5); } catch (ServiceException exception) { Assert.IsTrue(exception.IsMatch(ErrorConstants.Codes.TooManyRedirects), "Unexpected error code returned."); Assert.AreEqual( string.Format(ErrorConstants.Messages.TooManyRedirectsFormatString, "5"), exception.Error.Message, "Unexpected error message returned."); throw; } } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task SendAsync_NotFoundWithoutErrorBody() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://localhost")) using (var stringContent = new StringContent("test")) using (var httpResponseMessage = new HttpResponseMessage()) { httpResponseMessage.Content = stringContent; httpResponseMessage.StatusCode = HttpStatusCode.NotFound; this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage); this.serializer.Setup( serializer => serializer.DeserializeObject<ErrorResponse>( It.IsAny<Stream>())) .Returns((ErrorResponse)null); try { await this.httpProvider.SendAsync(httpRequestMessage); } catch (ServiceException exception) { Assert.IsTrue(exception.IsMatch(ErrorConstants.Codes.ItemNotFound), "Unexpected error code returned."); Assert.IsTrue(string.IsNullOrEmpty(exception.Error.Message), "Unexpected error message returned."); throw; } } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task SendAsync_NotFoundWithBody() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) using (var stringContent = new StringContent("test")) using (var httpResponseMessage = new HttpResponseMessage()) { httpResponseMessage.Content = stringContent; httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError; this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage); var expectedError = new ErrorResponse { Error = new Error { Code = ErrorConstants.Codes.ItemNotFound, Message = "Error message" } }; this.serializer.Setup(serializer => serializer.DeserializeObject<ErrorResponse>(It.IsAny<Stream>())).Returns(expectedError); try { await this.httpProvider.SendAsync(httpRequestMessage); } catch (ServiceException exception) { Assert.AreEqual(expectedError.Error.Code, exception.Error.Code, "Unexpected error code returned."); Assert.AreEqual(expectedError.Error.Message, exception.Error.Message, "Unexpected error message."); throw; } } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task SendAsync_CopyThrowSiteHeader() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) using (var httpResponseMessage = new HttpResponseMessage()) { const string throwSite = "throw site"; httpResponseMessage.StatusCode = HttpStatusCode.BadRequest; httpResponseMessage.Headers.Add(CoreConstants.Headers.ThrowSiteHeaderName, throwSite); httpResponseMessage.RequestMessage = httpRequestMessage; this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage); this.serializer.Setup( serializer => serializer.DeserializeObject<ErrorResponse>( It.IsAny<Stream>())) .Returns(new ErrorResponse { Error = new Error() }); try { var returnedResponseMessage = await this.httpProvider.SendAsync(httpRequestMessage); } catch (ServiceException exception) { Assert.IsNotNull(exception.Error, "Error not set in exception."); Assert.AreEqual( throwSite, exception.Error.ThrowSite, "Unexpected error throw site returned."); throw; } } } [TestMethod] [ExpectedException(typeof(ServiceException))] public async Task SendAsync_CopyThrowSiteHeader_ThrowSiteAlreadyInError() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) using (var stringContent = new StringContent("test")) using (var httpResponseMessage = new HttpResponseMessage()) { httpResponseMessage.Content = stringContent; const string throwSiteBodyValue = "throw site in body"; const string throwSiteHeaderValue = "throw site in header"; httpResponseMessage.StatusCode = HttpStatusCode.BadRequest; httpResponseMessage.Headers.Add(CoreConstants.Headers.ThrowSiteHeaderName, throwSiteHeaderValue); httpResponseMessage.RequestMessage = httpRequestMessage; this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage); this.serializer.Setup( serializer => serializer.DeserializeObject<ErrorResponse>( It.IsAny<Stream>())) .Returns(new ErrorResponse { Error = new Error { ThrowSite = throwSiteBodyValue } }); try { var returnedResponseMessage = await this.httpProvider.SendAsync(httpRequestMessage); } catch (ServiceException exception) { Assert.IsNotNull(exception.Error, "Error not set in exception."); Assert.AreEqual( throwSiteBodyValue, exception.Error.ThrowSite, "Unexpected error throw site returned."); throw; } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.SiteRecovery; namespace Microsoft.Azure.Management.SiteRecovery { public partial class SiteRecoveryManagementClient : ServiceClient<SiteRecoveryManagementClient>, ISiteRecoveryManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private string _resourceGroupName; public string ResourceGroupName { get { return this._resourceGroupName; } set { this._resourceGroupName = value; } } private string _resourceName; public string ResourceName { get { return this._resourceName; } set { this._resourceName = value; } } private string _resourceNamespace; public string ResourceNamespace { get { return this._resourceNamespace; } set { this._resourceNamespace = value; } } private IJobOperations _jobs; /// <summary> /// Definition for Job Operations. /// </summary> public virtual IJobOperations Jobs { get { return this._jobs; } } private IProtectionContainerOperations _protectionContainer; /// <summary> /// Definition of Protection Container operations for the Site Recovery /// extension. /// </summary> public virtual IProtectionContainerOperations ProtectionContainer { get { return this._protectionContainer; } } private IProtectionEntityOperations _protectionEntity; /// <summary> /// Definition of protection entity operations for the Site Recovery /// extension. /// </summary> public virtual IProtectionEntityOperations ProtectionEntity { get { return this._protectionEntity; } } private IProtectionProfileOperations _protectionProfile; /// <summary> /// Definition of Protection Profile operations for the Site Recovery /// extension. /// </summary> public virtual IProtectionProfileOperations ProtectionProfile { get { return this._protectionProfile; } } private IRecoveryPlanOperations _recoveryPlan; /// <summary> /// Definition of recoveryplan operations for the Site Recovery /// extension. /// </summary> public virtual IRecoveryPlanOperations RecoveryPlan { get { return this._recoveryPlan; } } private IServerOperations _servers; /// <summary> /// Definition of server operations for the Site Recovery extension. /// </summary> public virtual IServerOperations Servers { get { return this._servers; } } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> public SiteRecoveryManagementClient() : base() { this._jobs = new JobOperations(this); this._protectionContainer = new ProtectionContainerOperations(this); this._protectionEntity = new ProtectionEntityOperations(this); this._protectionProfile = new ProtectionProfileOperations(this); this._recoveryPlan = new RecoveryPlanOperations(this); this._servers = new ServerOperations(this); this._apiVersion = "2015-01-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='resourceName'> /// Required. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceNamespace'> /// Required. /// </param> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public SiteRecoveryManagementClient(string resourceName, string resourceGroupName, string resourceNamespace, SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceNamespace == null) { throw new ArgumentNullException("resourceNamespace"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._resourceName = resourceName; this._resourceGroupName = resourceGroupName; this._resourceNamespace = resourceNamespace; this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='resourceName'> /// Required. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceNamespace'> /// Required. /// </param> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public SiteRecoveryManagementClient(string resourceName, string resourceGroupName, string resourceNamespace, SubscriptionCloudCredentials credentials) : this() { if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceNamespace == null) { throw new ArgumentNullException("resourceNamespace"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this._resourceName = resourceName; this._resourceGroupName = resourceGroupName; this._resourceNamespace = resourceNamespace; this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public SiteRecoveryManagementClient(HttpClient httpClient) : base(httpClient) { this._jobs = new JobOperations(this); this._protectionContainer = new ProtectionContainerOperations(this); this._protectionEntity = new ProtectionEntityOperations(this); this._protectionProfile = new ProtectionProfileOperations(this); this._recoveryPlan = new RecoveryPlanOperations(this); this._servers = new ServerOperations(this); this._apiVersion = "2015-01-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='resourceName'> /// Required. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceNamespace'> /// Required. /// </param> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SiteRecoveryManagementClient(string resourceName, string resourceGroupName, string resourceNamespace, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceNamespace == null) { throw new ArgumentNullException("resourceNamespace"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._resourceName = resourceName; this._resourceGroupName = resourceGroupName; this._resourceNamespace = resourceNamespace; this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SiteRecoveryManagementClient /// class. /// </summary> /// <param name='resourceName'> /// Required. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceNamespace'> /// Required. /// </param> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SiteRecoveryManagementClient(string resourceName, string resourceGroupName, string resourceNamespace, SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceNamespace == null) { throw new ArgumentNullException("resourceNamespace"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this._resourceName = resourceName; this._resourceGroupName = resourceGroupName; this._resourceNamespace = resourceNamespace; this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// SiteRecoveryManagementClient instance /// </summary> /// <param name='client'> /// Instance of SiteRecoveryManagementClient to clone to /// </param> protected override void Clone(ServiceClient<SiteRecoveryManagementClient> client) { base.Clone(client); if (client is SiteRecoveryManagementClient) { SiteRecoveryManagementClient clonedClient = ((SiteRecoveryManagementClient)client); clonedClient._resourceName = this._resourceName; clonedClient._resourceGroupName = this._resourceGroupName; clonedClient._resourceNamespace = this._resourceNamespace; clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// 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.Security { using System.Text; using System.Runtime.CompilerServices; using System.Threading; using System; using System.Collections; using System.Security.Permissions; using System.Globalization; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; #if !FEATURE_PAL using Microsoft.Win32.SafeHandles; #endif //FrameSecurityDescriptor.cs // // Internal use only. // DO NOT DOCUMENT // [Serializable] internal class FrameSecurityDescriptor { /* EE has native FrameSecurityDescriptorObject definition in object.h Make sure to update that structure as well, if you make any changes here. */ private PermissionSet m_assertions; // imperative asserts private PermissionSet m_denials; // imperative denials private PermissionSet m_restriction; // imperative permitonlys private PermissionSet m_DeclarativeAssertions; private PermissionSet m_DeclarativeDenials; private PermissionSet m_DeclarativeRestrictions; #if !FEATURE_PAL // if this frame contains a call to any WindowsIdentity.Impersonate(), // we save the previous SafeTokenHandles here (in the next two fields) // Used during exceptionstackwalks to revert impersonation before calling filters [System.Security.SecurityCritical] // auto-generated [NonSerialized] private SafeAccessTokenHandle m_callerToken; [System.Security.SecurityCritical] // auto-generated [NonSerialized] private SafeAccessTokenHandle m_impToken; #endif private bool m_AssertFT; private bool m_assertAllPossible; #pragma warning disable 169 private bool m_declSecComputed; // set from the VM to indicate that the declarative A/PO/D on this frame has been populated #pragma warning restore 169 [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void IncrementOverridesCount(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void DecrementOverridesCount(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void IncrementAssertCount(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void DecrementAssertCount(); // Default constructor. internal FrameSecurityDescriptor() { //m_flags = 0; } //-----------------------------------------------------------+ // H E L P E R //-----------------------------------------------------------+ private PermissionSet CreateSingletonSet(IPermission perm) { PermissionSet permSet = new PermissionSet(false); permSet.AddPermission(perm.Copy()); return permSet; } //-----------------------------------------------------------+ // A S S E R T //-----------------------------------------------------------+ internal bool HasImperativeAsserts() { // we store declarative actions in both fields, so check if they are different return (m_assertions != null); } internal bool HasImperativeDenials() { // we store declarative actions in both fields, so check if they are different return (m_denials != null); } internal bool HasImperativeRestrictions() { // we store declarative actions in both fields, so check if they are different return (m_restriction != null); } [System.Security.SecurityCritical] // auto-generated internal void SetAssert(IPermission perm) { m_assertions = CreateSingletonSet(perm); IncrementAssertCount(); } [System.Security.SecurityCritical] // auto-generated internal void SetAssert(PermissionSet permSet) { m_assertions = permSet.Copy(); m_AssertFT = m_AssertFT || m_assertions.IsUnrestricted(); IncrementAssertCount(); } internal PermissionSet GetAssertions(bool fDeclarative) { return (fDeclarative) ? m_DeclarativeAssertions : m_assertions; } [System.Security.SecurityCritical] // auto-generated internal void SetAssertAllPossible() { m_assertAllPossible = true; IncrementAssertCount(); } internal bool GetAssertAllPossible() { return m_assertAllPossible; } //-----------------------------------------------------------+ // D E N Y //-----------------------------------------------------------+ [System.Security.SecurityCritical] // auto-generated internal void SetDeny(IPermission perm) { #if FEATURE_CAS_POLICY BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Deny is only valid in legacy CAS mode"); #endif // FEATURE_CAS_POLICY m_denials = CreateSingletonSet(perm); IncrementOverridesCount(); } [System.Security.SecurityCritical] // auto-generated internal void SetDeny(PermissionSet permSet) { m_denials = permSet.Copy(); IncrementOverridesCount(); } internal PermissionSet GetDenials(bool fDeclarative) { return (fDeclarative) ? m_DeclarativeDenials: m_denials; } //-----------------------------------------------------------+ // R E S T R I C T //-----------------------------------------------------------+ [System.Security.SecurityCritical] // auto-generated internal void SetPermitOnly(IPermission perm) { m_restriction = CreateSingletonSet(perm); IncrementOverridesCount(); } [System.Security.SecurityCritical] // auto-generated internal void SetPermitOnly(PermissionSet permSet) { // permSet must not be null m_restriction = permSet.Copy(); IncrementOverridesCount(); } internal PermissionSet GetPermitOnly(bool fDeclarative) { return (fDeclarative) ? m_DeclarativeRestrictions : m_restriction; } #if !FEATURE_PAL //-----------------------------------------------------------+ // SafeAccessTokenHandle (Impersonation + EH purposes) //-----------------------------------------------------------+ [System.Security.SecurityCritical] // auto-generated internal void SetTokenHandles (SafeAccessTokenHandle callerToken, SafeAccessTokenHandle impToken) { m_callerToken = callerToken; m_impToken = impToken; } #endif //-----------------------------------------------------------+ // R E V E R T //-----------------------------------------------------------+ [System.Security.SecurityCritical] // auto-generated internal void RevertAssert() { if (m_assertions != null) { m_assertions = null; DecrementAssertCount(); } if (m_DeclarativeAssertions != null) { m_AssertFT = m_DeclarativeAssertions.IsUnrestricted(); } else { m_AssertFT = false; } } [System.Security.SecurityCritical] // auto-generated internal void RevertAssertAllPossible() { if (m_assertAllPossible) { m_assertAllPossible = false; DecrementAssertCount(); } } [System.Security.SecurityCritical] // auto-generated internal void RevertDeny() { if (HasImperativeDenials()) { DecrementOverridesCount(); m_denials = null; } } [System.Security.SecurityCritical] // auto-generated internal void RevertPermitOnly() { if (HasImperativeRestrictions()) { DecrementOverridesCount(); m_restriction= null;; } } [System.Security.SecurityCritical] // auto-generated internal void RevertAll() { RevertAssert(); RevertAssertAllPossible(); RevertDeny(); RevertPermitOnly(); } //-----------------------------------------------------------+ // Demand Evaluation //-----------------------------------------------------------+ // This will get called when we hit a FSD while evaluating a demand on the call stack or compressedstack [System.Security.SecurityCritical] // auto-generated internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh) { // imperative security bool fContinue = CheckDemand2(demand, permToken, rmh, false); if (fContinue == SecurityRuntime.StackContinue) { // declarative security fContinue = CheckDemand2(demand, permToken, rmh, true); } return fContinue; } [System.Security.SecurityCritical] // auto-generated internal bool CheckDemand2(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, bool fDeclarative) { PermissionSet permSet; // If the demand is null, there is no need to continue Contract.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point"); // decode imperative if (GetPermitOnly(fDeclarative) != null) GetPermitOnly(fDeclarative).CheckDecoded(demand, permToken); if (GetDenials(fDeclarative) != null) GetDenials(fDeclarative).CheckDecoded(demand, permToken); if (GetAssertions(fDeclarative) != null) GetAssertions(fDeclarative).CheckDecoded(demand, permToken); // NOTE: See notes about exceptions and exception handling in FrameDescSetHelper bool bThreadSecurity = SecurityManager._SetThreadSecurity(false); // Check Reduction try { permSet = GetPermitOnly(fDeclarative); if (permSet != null) { CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand); // If the permit only set does not contain the demanded permission, throw a security exception if (perm == null) { if (!permSet.IsUnrestricted()) throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demand, demand); } else { bool bNeedToThrow = true; try { bNeedToThrow = !demand.CheckPermitOnly(perm); } catch (ArgumentException) { } if (bNeedToThrow) throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demand, demand); } } // Check Denials permSet = GetDenials(fDeclarative); if (permSet != null) { CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand); // If an unrestricted set was denied and the demand implements IUnrestricted if (permSet.IsUnrestricted()) throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demand, demand); // If the deny set does contain the demanded permission, throw a security exception bool bNeedToThrow = true; try { bNeedToThrow = !demand.CheckDeny(perm); } catch (ArgumentException) { } if (bNeedToThrow) throw new SecurityException(String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Security_Generic"), demand.GetType().AssemblyQualifiedName), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demand, demand); } if (GetAssertAllPossible()) { return SecurityRuntime.StackHalt; } permSet = GetAssertions(fDeclarative); // Check Assertions if (permSet != null) { CodeAccessPermission perm = (CodeAccessPermission)permSet.GetPermission(demand); // If the assert set does contain the demanded permission, halt the stackwalk try { if (permSet.IsUnrestricted() || demand.CheckAssert(perm)) { return SecurityRuntime.StackHalt; } } catch (ArgumentException) { } } } finally { if (bThreadSecurity) SecurityManager._SetThreadSecurity(true); } return SecurityRuntime.StackContinue; } [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemand(PermissionSet demandSet, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh) { // imperative security PermissionSet altPset1 = null, altPset2 = null; bool fContinue = CheckSetDemand2(demandSet, out altPset1, rmh, false); if (altPset1 != null) { demandSet = altPset1; } if (fContinue == SecurityRuntime.StackContinue) { // declarative security fContinue = CheckSetDemand2(demandSet, out altPset2, rmh, true); } // Return the most recent altered set // If both declarative and imperative asserts modified the demand set: return altPset2 // Else if imperative asserts modified the demand set: return altPset1 // else no alteration: return null if (altPset2 != null) alteredDemandSet = altPset2; else if (altPset1 != null) alteredDemandSet = altPset1; else alteredDemandSet = null; return fContinue; } [System.Security.SecurityCritical] // auto-generated internal bool CheckSetDemand2(PermissionSet demandSet, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh, bool fDeclarative) { PermissionSet permSet; // In the common case we are not going to alter the demand set, so just to // be safe we'll set it to null up front. alteredDemandSet = null; // There's some oddness in here to deal with exceptions. The general idea behind // this is that we need some way of dealing with custom permissions that may not // handle all possible scenarios of Union(), Intersect(), and IsSubsetOf() properly // (they don't support it, throw null reference exceptions, etc.). // An empty demand always succeeds. if (demandSet == null || demandSet.IsEmpty()) return SecurityRuntime.StackHalt; if (GetPermitOnly(fDeclarative) != null) GetPermitOnly(fDeclarative).CheckDecoded( demandSet ); if (GetDenials(fDeclarative) != null) GetDenials(fDeclarative).CheckDecoded( demandSet ); if (GetAssertions(fDeclarative) != null) GetAssertions(fDeclarative).CheckDecoded( demandSet ); bool bThreadSecurity = SecurityManager._SetThreadSecurity(false); try { // In the case of permit only, we define an exception to be failure of the check // and therefore we throw a security exception. permSet = GetPermitOnly(fDeclarative); if (permSet != null) { IPermission permFailed = null; bool bNeedToThrow = true; try { bNeedToThrow = !demandSet.CheckPermitOnly(permSet, out permFailed); } catch (ArgumentException) { } if (bNeedToThrow) throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"), null, permSet, SecurityRuntime.GetMethodInfo(rmh), demandSet, permFailed); } // In the case of denial, we define an exception to be failure of the check // and therefore we throw a security exception. permSet = GetDenials(fDeclarative); if (permSet != null) { IPermission permFailed = null; bool bNeedToThrow = true; try { bNeedToThrow = !demandSet.CheckDeny(permSet, out permFailed); } catch (ArgumentException) { } if (bNeedToThrow) throw new SecurityException(Environment.GetResourceString("Security_GenericNoType"), permSet, null, SecurityRuntime.GetMethodInfo(rmh), demandSet, permFailed); } // The assert case is more complex. Since asserts have the ability to "bleed through" // (where part of a demand is handled by an assertion, but the rest is passed on to // continue the stackwalk), we need to be more careful in handling the "failure" case. // Therefore, if an exception is thrown in performing any operation, we make sure to keep // that permission in the demand set thereby continuing the demand for that permission // walking down the stack. if (GetAssertAllPossible()) { return SecurityRuntime.StackHalt; } permSet = GetAssertions(fDeclarative); if (permSet != null) { // If this frame asserts a superset of the demand set we're done if (demandSet.CheckAssertion( permSet )) return SecurityRuntime.StackHalt; // Determine whether any of the demand set asserted. We do this by // copying the demand set and removing anything in it that is asserted. if (!permSet.IsUnrestricted()) { PermissionSet.RemoveAssertedPermissionSet(demandSet, permSet, out alteredDemandSet); } } } finally { if (bThreadSecurity) SecurityManager._SetThreadSecurity(true); } return SecurityRuntime.StackContinue; } } #if FEATURE_COMPRESSEDSTACK // Used by the stack compressor to communicate a DynamicResolver to managed code during a stackwalk. // The JIT will not actually place these on frames. internal class FrameSecurityDescriptorWithResolver : FrameSecurityDescriptor { private System.Reflection.Emit.DynamicResolver m_resolver; public System.Reflection.Emit.DynamicResolver Resolver { get { return m_resolver; } } } #endif // FEATURE_COMPRESSEDSTACK }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Documents; using NeuroSpeech.XamlToPDF.Objects; using System.Windows.Media; using System.Windows; using System.Diagnostics; using System.IO; using System.IO.Packaging; using System.Windows.Xps.Packaging; using System.Windows.Xps.Serialization; using System.ComponentModel.Composition.Hosting; using System.Reflection; using System.ComponentModel.Composition; using NeuroSpeech.XamlToPDF.Writer; using System.Windows.Controls; namespace NeuroSpeech.XamlToPDF.Xaml { public class XamlPdfContext { public PDFDocument PDFDocument { get; set; } public FlowDocument FlowDocument { get; set; } public XpsDocument XpsDocument { get; set; } public FixedDocument FixedDocument { get; set; } public FixedPage FixedPage { get; set; } public PDFPage PDFPage { get; set; } public Package Package { get; set; } public byte[] GetResource(Uri partUri) { var p = Package.GetPart(partUri); MemoryStream ms = new MemoryStream(); using (Stream s = p.GetStream()) { s.CopyTo(ms); } return ms.ToArray(); } public System.Windows.Media.FontFamily GetFont(Uri partUri) { byte[] data = GetResource(partUri); XpsFont xf = null; foreach (var item in XpsDocument.FixedDocumentSequenceReader.FixedDocuments) { foreach (var fp in item.FixedPages) { foreach (var f in fp.Fonts) { if (f.Uri == partUri) xf = f; } } } MemoryStream reader = new MemoryStream(data); MemoryStream writer = new MemoryStream(); if (xf.IsObfuscated) { ObfuscationSwitcher(partUri.ToString(), reader, writer); } else { reader.CopyTo(writer); } string tmp = Path.GetTempFileName(); File.WriteAllBytes(tmp,writer.ToArray()); return new FontFamily("file:///" + tmp); } public static void ObfuscationSwitcher(string uri, MemoryStream font, Stream streamOut) { if (font == null || streamOut == null) throw new ArgumentNullException(); int count1 = 4096; int length1 = 16; int count2 = 32; string originalString = uri; int startIndex = originalString.LastIndexOf('/') + 1; int length2 = originalString.LastIndexOf('.') - startIndex; string str = new Guid(originalString.Substring(startIndex, length2)).ToString("N"); byte[] numArray = new byte[length1]; for (int index = 0; index < numArray.Length; ++index) numArray[index] = Convert.ToByte(str.Substring(index * 2, 2), 16); byte[] buffer1 = new byte[count2]; font.Read(buffer1, 0, count2); for (int index1 = 0; index1 < count2; ++index1) { int index2 = numArray.Length - index1 % numArray.Length - 1; buffer1[index1] ^= numArray[index2]; } streamOut.Write(buffer1, 0, count2); byte[] buffer2 = new byte[count1]; int count3; while ((count3 = font.Read(buffer2, 0, count1)) > 0) streamOut.Write(buffer2, 0, count3); streamOut.Position = 0L; } private Visual lastVisual = null; #region internal object TransformY(LineSegment visual,double p) internal Point TransformPoint(Visual visual, Point p) { lastVisual = visual; p = Transform(visual,p); p.Y = PDFPage.MediaBox.Height - p.Y; return p; } #region private Point Transform(Visual visual,Point p) private Point Transform(Visual visual, Point p) { if (visual == FixedPage) return p; Point r = p; UIElement e = visual as UIElement; if (e!=null) { Transform t = e.RenderTransform; Matrix m = t.Value; if (m != null && !m.IsIdentity) { r = t.Transform(p); } } return Transform((Visual) VisualTreeHelper.GetParent(visual),r) ; } #endregion #endregion #region internal object TransformY(double p) internal Point TransformPoint(Point p) { return TransformPoint(lastVisual, p); } #endregion Dictionary<GlyphTypeface, string> fonts = new Dictionary<GlyphTypeface, string>(); #region internal object GetFont(System.Windows.Media.GlyphTypeface glyphTypeface) internal string GetFont(PDFResources resources, System.Windows.Media.GlyphTypeface typeFace) { string familyName = typeFace.FamilyNames.Values.FirstOrDefault(); string key = null; if (!fonts.TryGetValue(typeFace, out key)) { key = "R" + resources.ID + "F" + fonts.Count; PDFFont pf = PDFDocument.CreateObject<PDFFont>(); pf.BaseFont = familyName; pf.Subtype = "Type1"; pf.Encoding = "MacRomanEncoding"; resources.Font[key] = pf; var pd = PDFDocument.CreateObject<PDFFontDescriptor>(); pf.FontDescriptor = pd; pd.FontName = familyName; pd.FontFamily = familyName; pd.FontWeight = typeFace.Weight.ToOpenTypeWeight(); pd.XHeight = typeFace.XHeight; pd.CapHeight = typeFace.CapsHeight; pd.StemV = typeFace.StrikethroughThickness; pd.Flags = PDFFontFlags.None; if (typeFace.Weight == FontWeights.Bold) { pd.Flags |= PDFFontFlags.ForceBold; } if (typeFace.Symbol) { pd.Flags |= PDFFontFlags.Symbolic; } else { pd.Flags |= PDFFontFlags.Nonsymbolic; } pd.Ascent = typeFace.AdvanceHeights.Select(x=>x.Value).Max() - typeFace.Baseline; pd.Descent = - ( typeFace.DistancesFromHorizontalBaselineToBlackBoxBottom.Select(x => x.Value).Max() ); pd.FontBBox = new PDFRect(); pd.FontBBox.Width = (int)typeFace.AdvanceWidths.Select(x => x.Value).Sum(); pd.FontBBox.Height = (int)typeFace.AdvanceHeights.Select(x => x.Value).Sum(); fonts[typeFace] = key; } return key; } #endregion } }
namespace Hydra.SharedCache.Notify { // // ********************************************************************** /// <summary> /// <b>about window with several additional information.</b> /// </summary> // ********************************************************************** // partial class About { // // ********************************************************************** /// <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(About)); this.Version = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.installedVersionNumber = new System.Windows.Forms.Label(); this.VersionNumber = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.linkLabel6 = new System.Windows.Forms.LinkLabel(); this.label7 = new System.Windows.Forms.Label(); this.linkLabel5 = new System.Windows.Forms.LinkLabel(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.linkLabel4 = new System.Windows.Forms.LinkLabel(); this.linkLabel3 = new System.Windows.Forms.LinkLabel(); this.label4 = new System.Windows.Forms.Label(); this.linkLabel2 = new System.Windows.Forms.LinkLabel(); this.label3 = new System.Windows.Forms.Label(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.label2 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.copyright = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // Version // this.Version.AutoSize = true; this.Version.Location = new System.Drawing.Point(42, 25); this.Version.Name = "Version"; this.Version.Size = new System.Drawing.Size(45, 13); this.Version.TabIndex = 1; this.Version.Text = "Version:"; // // groupBox1 // this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.installedVersionNumber); this.groupBox1.Controls.Add(this.VersionNumber); this.groupBox1.Controls.Add(this.Version); this.groupBox1.Location = new System.Drawing.Point(106, 9); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(372, 68); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "LBSView Shared Cache Info:"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 43); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(81, 13); this.label1.TabIndex = 4; this.label1.Text = "Latest Release:"; // // installedVersionNumber // this.installedVersionNumber.AutoSize = true; this.installedVersionNumber.Location = new System.Drawing.Point(93, 25); this.installedVersionNumber.Name = "installedVersionNumber"; this.installedVersionNumber.Size = new System.Drawing.Size(82, 13); this.installedVersionNumber.TabIndex = 3; this.installedVersionNumber.Text = "installed version"; // // VersionNumber // this.VersionNumber.AutoSize = true; this.VersionNumber.Location = new System.Drawing.Point(93, 43); this.VersionNumber.Name = "VersionNumber"; this.VersionNumber.Size = new System.Drawing.Size(165, 13); this.VersionNumber.TabIndex = 2; this.VersionNumber.Text = "online version number.. searching"; // // pictureBox1 // this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.pictureBox1.Image = global::Hydra.SharedCache.Notify.Resource.SanscastleDocLogo; this.pictureBox1.InitialImage = global::Hydra.SharedCache.Notify.Resource.indexus; this.pictureBox1.Location = new System.Drawing.Point(24, 14); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(59, 63); this.pictureBox1.TabIndex = 3; this.pictureBox1.TabStop = false; // // groupBox2 // this.groupBox2.Controls.Add(this.linkLabel6); this.groupBox2.Controls.Add(this.label7); this.groupBox2.Controls.Add(this.linkLabel5); this.groupBox2.Controls.Add(this.label6); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.linkLabel4); this.groupBox2.Controls.Add(this.linkLabel3); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.linkLabel2); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.linkLabel1); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Location = new System.Drawing.Point(13, 92); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(465, 196); this.groupBox2.TabIndex = 4; this.groupBox2.TabStop = false; this.groupBox2.Text = "References: "; // // linkLabel6 // this.linkLabel6.AutoSize = true; this.linkLabel6.Location = new System.Drawing.Point(99, 128); this.linkLabel6.Name = "linkLabel6"; this.linkLabel6.Size = new System.Drawing.Size(298, 13); this.linkLabel6.TabIndex = 11; this.linkLabel6.TabStop = true; this.linkLabel6.Text = "http://www.lbsview.com/SharedCache/WorkItem/List.aspx"; this.linkLabel6.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel6_LinkClicked); // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(53, 128); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(34, 13); this.label7.TabIndex = 10; this.label7.Text = "Bugs:"; // // linkLabel5 // this.linkLabel5.AutoSize = true; this.linkLabel5.Location = new System.Drawing.Point(99, 101); this.linkLabel5.Name = "linkLabel5"; this.linkLabel5.Size = new System.Drawing.Size(286, 13); this.linkLabel5.TabIndex = 9; this.linkLabel5.TabStop = true; this.linkLabel5.Text = "http://www.lbsview.com/SharedCache/Thread/List.aspx"; this.linkLabel5.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel5_LinkClicked); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(21, 101); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(66, 13); this.label6.TabIndex = 8; this.label6.Text = "Diskussions:"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(29, 73); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(58, 13); this.label5.TabIndex = 7; this.label5.Text = "Download:"; // // linkLabel4 // this.linkLabel4.AutoSize = true; this.linkLabel4.Location = new System.Drawing.Point(99, 73); this.linkLabel4.Name = "linkLabel4"; this.linkLabel4.Size = new System.Drawing.Size(352, 13); this.linkLabel4.TabIndex = 6; this.linkLabel4.TabStop = true; this.linkLabel4.Text = "http://www.lbsview.com/SharedCache/ProjectReleases.aspx"; this.linkLabel4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel4_LinkClicked); // // linkLabel3 // this.linkLabel3.AutoSize = true; this.linkLabel3.Location = new System.Drawing.Point(99, 158); this.linkLabel3.Name = "linkLabel3"; this.linkLabel3.Size = new System.Drawing.Size(306, 13); this.linkLabel3.TabIndex = 5; this.linkLabel3.TabStop = true; this.linkLabel3.Text = "http://www.lbsview.com/SharedCache/License.aspx"; this.linkLabel3.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel3_LinkClicked); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(40, 158); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(47, 13); this.label4.TabIndex = 4; this.label4.Text = "License:"; // // linkLabel2 // this.linkLabel2.AutoSize = true; this.linkLabel2.Location = new System.Drawing.Point(99, 43); this.linkLabel2.Name = "linkLabel2"; this.linkLabel2.Size = new System.Drawing.Size(137, 13); this.linkLabel2.TabIndex = 3; this.linkLabel2.TabStop = true; this.linkLabel2.Text = "[email protected]"; this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(29, 43); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(58, 13); this.label3.TabIndex = 2; this.label3.Text = "Feedback:"; // // linkLabel1 // this.linkLabel1.AutoSize = true; this.linkLabel1.Location = new System.Drawing.Point(99, 19); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(158, 13); this.linkLabel1.TabIndex = 1; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "http://www.lbsview.com/"; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(2, 19); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(85, 13); this.label2.TabIndex = 0; this.label2.Text = "Project Website:"; // // button1 // this.button1.Location = new System.Drawing.Point(12, 357); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(466, 23); this.button1.TabIndex = 5; this.button1.Text = "OK"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // groupBox3 // this.groupBox3.Controls.Add(this.copyright); this.groupBox3.Location = new System.Drawing.Point(13, 306); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(465, 45); this.groupBox3.TabIndex = 6; this.groupBox3.TabStop = false; this.groupBox3.Text = "Warranty and Copyright: "; // // copyright // this.copyright.AutoSize = true; this.copyright.Location = new System.Drawing.Point(8, 20); this.copyright.Name = "copyright"; this.copyright.Size = new System.Drawing.Size(50, 13); this.copyright.TabIndex = 0; this.copyright.Text = "copyright"; // // About // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.ClientSize = new System.Drawing.Size(490, 389); this.Controls.Add(this.groupBox3); this.Controls.Add(this.button1); this.Controls.Add(this.groupBox2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.groupBox1); this.Cursor = System.Windows.Forms.Cursors.Default; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "About"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "About"; this.Load += new System.EventHandler(this.About_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label Version; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label VersionNumber; private System.Windows.Forms.Label installedVersionNumber; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button button1; private System.Windows.Forms.LinkLabel linkLabel2; private System.Windows.Forms.Label label3; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Label label2; private System.Windows.Forms.LinkLabel linkLabel3; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Label copyright; private System.Windows.Forms.LinkLabel linkLabel4; private System.Windows.Forms.LinkLabel linkLabel6; private System.Windows.Forms.Label label7; private System.Windows.Forms.LinkLabel linkLabel5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label5; } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using System.IO; using System.Web; using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; using RestSharp; namespace IO.Swagger.Client { /// <summary> /// API client is mainly responible for making the HTTP call to the API backend. /// </summary> public class ApiClient { /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration and base path (https://api.landregistry.gov.uk/v1). /// </summary> public ApiClient() { Configuration = Configuration.Default; RestClient = new RestClient("https://api.landregistry.gov.uk/v1"); } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default base path (https://api.landregistry.gov.uk/v1). /// </summary> /// <param name="config">An instance of Configuration.</param> public ApiClient(Configuration config = null) { if (config == null) Configuration = Configuration.Default; else Configuration = config; RestClient = new RestClient("https://api.landregistry.gov.uk/v1"); } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration. /// </summary> /// <param name="basePath">The base path.</param> public ApiClient(String basePath = "https://api.landregistry.gov.uk/v1") { if (String.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); RestClient = new RestClient(basePath); Configuration = Configuration.Default; } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The default API client.</value> public static ApiClient Default = new ApiClient(Configuration.Default); /// <summary> /// Gets or sets the Configuration. /// </summary> /// <value>An instance of the Configuration.</value> public Configuration Configuration { get; set; } /// <summary> /// Gets or sets the RestClient. /// </summary> /// <value>An instance of the RestClient</value> public RestClient RestClient { get; set; } // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams) { var request = new RestRequest(path, method); // add path parameter, if any foreach(var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); // add header parameter, if any foreach(var param in headerParams) request.AddHeader(param.Key, param.Value); // add query parameter, if any foreach(var param in queryParams) request.AddQueryParameter(param.Key, param.Value); // add form parameter, if any foreach(var param in formParams) request.AddParameter(param.Key, param.Value); // add file parameter, if any foreach(var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); if (postBody != null) // http body (model) parameter request.AddParameter("application/json", postBody, ParameterType.RequestBody); return request; } /// <summary> /// Makes the HTTP request (Sync). /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="pathParams">Path parameters.</param> /// <returns>Object</returns> public Object CallApi( String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); var response = RestClient.Execute(request); return (Object) response; } /// <summary> /// Makes the asynchronous HTTP request. /// </summary> /// <param name="path">URL path.</param> /// <param name="method">HTTP method.</param> /// <param name="queryParams">Query parameters.</param> /// <param name="postBody">HTTP body (POST request).</param> /// <param name="headerParams">Header parameters.</param> /// <param name="formParams">Form parameters.</param> /// <param name="fileParams">File parameters.</param> /// <param name="pathParams">Path parameters.</param> /// <returns>The Task instance.</returns> public async System.Threading.Tasks.Task<Object> CallApiAsync( String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody, Dictionary<String, String> headerParams, Dictionary<String, String> formParams, Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams) { var request = PrepareRequest( path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); var response = await RestClient.ExecuteTaskAsync(request); return (Object)response; } /// <summary> /// Escape string (url-encoded). /// </summary> /// <param name="str">String to be escaped.</param> /// <returns>Escaped string.</returns> public string EscapeString(string str) { return UrlEncode(str); } /// <summary> /// Create FileParameter based on Stream. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="stream">Input stream.</param> /// <returns>FileParameter.</returns> public FileParameter ParameterToFile(string name, Stream stream) { if (stream is FileStream) return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name)); else return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided"); } /// <summary> /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// </summary> /// <param name="obj">The parameter (header, path, query, form).</param> /// <returns>Formatted string.</returns> public string ParameterToString(object obj) { if (obj is DateTime) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString (Configuration.DateTimeFormat); else if (obj is DateTimeOffset) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); foreach (var param in (IList)obj) { if (flattenedString.Length > 0) flattenedString.Append(","); flattenedString.Append(param); } return flattenedString.ToString(); } else return Convert.ToString (obj); } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> public object Deserialize(IRestResponse response, Type type) { byte[] data = response.RawBytes; string content = response.Content; IList<Parameter> headers = response.Headers; if (type == typeof(Object)) // return an object { return content; } if (type == typeof(Stream)) { if (headers != null) { var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) ? Path.GetTempPath() : Configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); foreach (var header in headers) { var match = regex.Match(header.ToString()); if (match.Success) { string fileName = filePath + match.Groups[1].Value.Replace("\"", "").Replace("'", ""); File.WriteAllBytes(fileName, data); return new FileStream(fileName, FileMode.Open); } } } var stream = new MemoryStream(data); return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { return ConvertType(content, type); } // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(content, type); } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Serialize an object into JSON string. /// </summary> /// <param name="obj">Object.</param> /// <returns>JSON string.</returns> public string Serialize(object obj) { try { return obj != null ? JsonConvert.SerializeObject(obj) : null; } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; /// otherwise use all of them (joining into a string) /// </summary> /// <param name="accepts">The accepts array to select from.</param> /// <returns>The Accept header to use.</returns> public String SelectHeaderAccept(String[] accepts) { if (accepts.Length == 0) return null; if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; return String.Join(",", accepts); } /// <summary> /// Encode string in base64 format. /// </summary> /// <param name="text">String to be encoded.</param> /// <returns>Encoded string.</returns> public static string Base64Encode(string text) { return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); } /// <summary> /// Dynamically cast the object into target type. /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast /// </summary> /// <param name="source">Object to be casted</param> /// <param name="dest">Target type</param> /// <returns>Casted object</returns> public static dynamic ConvertType(dynamic source, Type dest) { return Convert.ChangeType(source, dest); } /// <summary> /// Convert stream to byte array /// Credit/Ref: http://stackoverflow.com/a/221941/677735 /// </summary> /// <param name="input">Input stream to be converted</param> /// <returns>Byte array</returns> public static byte[] ReadAsBytes(Stream input) { byte[] buffer = new byte[16*1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } /// <summary> /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// </summary> /// <param name="input">String to be URL encoded</param> /// <returns>Byte array</returns> public static string UrlEncode(string input) { const int maxLength = 32766; if (input == null) { throw new ArgumentNullException("input"); } if (input.Length <= maxLength) { return Uri.EscapeDataString(input); } StringBuilder sb = new StringBuilder(input.Length * 2); int index = 0; while (index < input.Length) { int length = Math.Min(input.Length - index, maxLength); string subString = input.Substring(index, length); sb.Append(Uri.EscapeDataString(subString)); index += subString.Length; } return sb.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Reflection; using System.Globalization; namespace DPStressHarness { public static class TestMetrics { private const string _defaultValue = "unknown"; private static bool s_valid = false; private static bool s_reset = true; private static Stopwatch s_stopwatch = new Stopwatch(); private static long s_workingSet; private static long s_peakWorkingSet; private static long s_privateBytes; private static Assembly s_targetAssembly; private static string s_fileVersion = _defaultValue; private static string s_privateBuild = _defaultValue; private static string s_runLabel = DateTime.Now.ToString(); private static Dictionary<string, string> s_overrides; private static List<string> s_variations = null; private static List<string> s_selectedTests = null; private static bool s_isOfficial = false; private static string s_milestone = _defaultValue; private static string s_branch = _defaultValue; private static List<string> s_categories = null; private static bool s_profileMeasuredCode = false; private static int s_stressThreads = 16; private static int s_stressDuration = -1; private static int? s_exceptionThreshold = null; private static bool s_monitorenabled = false; private static string s_monitormachinename = "localhost"; private static int s_randomSeed = 0; private static string s_filter = null; private static bool s_printMethodName = false; /// <summary>Starts the sample profiler.</summary> /// <remarks> /// Do not inline to avoid errors when the functionality is not used /// and the profiling DLL is not available. /// </remarks> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void InternalStartProfiling() { // Microsoft.VisualStudio.Profiler.DataCollection.StartProfile( // Microsoft.VisualStudio.Profiler.ProfileLevel.Global, // Microsoft.VisualStudio.Profiler.DataCollection.CurrentId); } /// <summary>Stops the sample profiler.</summary> /// <remarks> /// Do not inline to avoid errors when the functionality is not used /// and the profiling DLL is not available. /// </remarks> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void InternalStopProfiling() { // Microsoft.VisualStudio.Profiler.DataCollection.StopProfile( // Microsoft.VisualStudio.Profiler.ProfileLevel.Global, // Microsoft.VisualStudio.Profiler.DataCollection.CurrentId); } public static void StartCollection() { s_valid = false; s_stopwatch.Reset(); s_stopwatch.Start(); s_reset = true; } public static void StartProfiling() { if (s_profileMeasuredCode) { InternalStartProfiling(); } } public static void StopProfiling() { if (s_profileMeasuredCode) { InternalStopProfiling(); } } public static void StopCollection() { s_stopwatch.Stop(); Process p = Process.GetCurrentProcess(); s_workingSet = p.WorkingSet64; s_peakWorkingSet = p.PeakWorkingSet64; s_privateBytes = p.PrivateMemorySize64; s_valid = true; } public static void PauseTimer() { s_stopwatch.Stop(); } public static void UnPauseTimer() { if (s_reset) { s_stopwatch.Reset(); s_reset = false; } s_stopwatch.Start(); } private static void ThrowIfInvalid() { if (!s_valid) throw new InvalidOperationException("Collection must be stopped before accessing this metric."); } public static void Reset() { s_valid = false; s_reset = true; s_stopwatch = new Stopwatch(); s_workingSet = new long(); s_peakWorkingSet = new long(); s_privateBytes = new long(); s_targetAssembly = null; s_fileVersion = _defaultValue; s_privateBuild = _defaultValue; s_runLabel = DateTime.Now.ToString(); s_overrides = null; s_variations = null; s_selectedTests = null; s_isOfficial = false; s_milestone = _defaultValue; s_branch = _defaultValue; s_categories = null; s_profileMeasuredCode = false; s_stressThreads = 16; s_stressDuration = -1; s_exceptionThreshold = null; s_monitorenabled = false; s_monitormachinename = "localhost"; s_randomSeed = 0; s_filter = null; s_printMethodName = false; } public static string FileVersion { get { return s_fileVersion; } set { s_fileVersion = value; } } public static string PrivateBuild { get { return s_privateBuild; } set { s_privateBuild = value; } } public static Assembly TargetAssembly { get { return s_targetAssembly; } set { s_targetAssembly = value; s_fileVersion = VersionUtil.GetFileVersion(s_targetAssembly.ManifestModule.FullyQualifiedName); s_privateBuild = VersionUtil.GetPrivateBuild(s_targetAssembly.ManifestModule.FullyQualifiedName); } } public static string RunLabel { get { return s_runLabel; } set { s_runLabel = value; } } public static string Milestone { get { return s_milestone; } set { s_milestone = value; } } public static string Branch { get { return s_branch; } set { s_branch = value; } } public static bool IsOfficial { get { return s_isOfficial; } set { s_isOfficial = value; } } public static bool IsDefaultValue(string val) { return val.Equals(_defaultValue); } public static double ElapsedSeconds { get { ThrowIfInvalid(); return s_stopwatch.ElapsedMilliseconds / 1000.0; } } public static long WorkingSet { get { ThrowIfInvalid(); return s_workingSet; } } public static long PeakWorkingSet { get { ThrowIfInvalid(); return s_peakWorkingSet; } } public static long PrivateBytes { get { ThrowIfInvalid(); return s_privateBytes; } } public static Dictionary<string, string> Overrides { get { if (s_overrides == null) { s_overrides = new Dictionary<string, string>(8); } return s_overrides; } } public static List<string> Variations { get { if (s_variations == null) { s_variations = new List<string>(8); } return s_variations; } } public static List<string> SelectedTests { get { if (s_selectedTests == null) { s_selectedTests = new List<string>(8); } return s_selectedTests; } } public static bool IncludeTest(TestAttributeBase test) { if (s_selectedTests == null || s_selectedTests.Count == 0) return true; // user has no selection - run all else return s_selectedTests.Contains(test.Title); } public static List<string> Categories { get { if (s_categories == null) { s_categories = new List<string>(8); } return s_categories; } } public static bool ProfileMeasuredCode { get { return s_profileMeasuredCode; } set { s_profileMeasuredCode = value; } } public static int StressDuration { get { return s_stressDuration; } set { s_stressDuration = value; } } public static int StressThreads { get { return s_stressThreads; } set { s_stressThreads = value; } } public static int? ExceptionThreshold { get { return s_exceptionThreshold; } set { s_exceptionThreshold = value; } } public static bool MonitorEnabled { get { return s_monitorenabled; } set { s_monitorenabled = value; } } public static string MonitorMachineName { get { return s_monitormachinename; } set { s_monitormachinename = value; } } public static int RandomSeed { get { return s_randomSeed; } set { s_randomSeed = value; } } public static string Filter { get { return s_filter; } set { s_filter = value; } } public static bool PrintMethodName { get { return s_printMethodName; } set { s_printMethodName = value; } } } }