context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //========================================================================== // File: SocketManager.cs // // Summary: Class for managing a socket connection. // //========================================================================== using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Runtime.Remoting.Messaging; using System.Security.Principal; using System.Text; using System.Threading; namespace System.Runtime.Remoting.Channels { internal delegate bool ValidateByteDelegate(byte b); internal abstract class SocketHandler { // socket manager data protected Socket NetSocket; // network socket protected Stream NetStream; // network stream private DateTime _creationTime; private RequestQueue _requestQueue; // request queue to use for this connection private byte[] _dataBuffer; // buffered data private int _dataBufferSize; // size of data buffer private int _dataOffset; // offset of remaining data in buffer private int _dataCount; // count of remaining bytes in buffer private AsyncCallback _beginReadCallback; // callback to use when doing an async read private IAsyncResult _beginReadAsyncResult; // async result from doing a begin read private WaitCallback _dataArrivedCallback; // callback to signal once data is available private Object _dataArrivedCallbackState; // state object to go along with callback #if !FEATURE_PAL private WindowsIdentity _impersonationIdentity; // Identity to impersonate #endif // !FEATURE_PAL private byte[] _byteBuffer = new byte[4]; // buffer for reading bytes // control cookie - // The control cookie is used for synchronization when a "user" // wants to retrieve this client socket manager from the socket // cache. private int _controlCookie = 1; // hide default constructor private SocketHandler(){} public SocketHandler(Socket socket, Stream netStream) { _beginReadCallback = new AsyncCallback(this.BeginReadMessageCallback); _creationTime = DateTime.UtcNow; NetSocket = socket; NetStream = netStream; _dataBuffer = CoreChannel.BufferPool.GetBuffer(); _dataBufferSize = _dataBuffer.Length; _dataOffset = 0; _dataCount = 0; } // SocketHandler internal SocketHandler(Socket socket, RequestQueue requestQueue, Stream netStream) : this(socket, netStream) { _requestQueue = requestQueue; } // SocketHandler public DateTime CreationTime { get { return _creationTime; } } // If this method returns true, then whoever called it can assume control // of the client socket manager. If it returns false, the caller is on // their honor not to do anything further with this object. public bool RaceForControl() { if (1 == Interlocked.Exchange(ref _controlCookie, 0)) return true; return false; } // RaceForControl public void ReleaseControl() { _controlCookie = 1; } // ReleaseControl // Determines if the remote connection is from localhost. internal bool IsLocalhost() { if (NetSocket == null || NetSocket.RemoteEndPoint == null) return true; IPAddress remoteAddr = ((IPEndPoint)NetSocket.RemoteEndPoint).Address; return IPAddress.IsLoopback(remoteAddr) || CoreChannel.IsLocalIpAddress(remoteAddr); } // IsLocalhost // Determines if the remote connection is from localhost. internal bool IsLocal() { if (NetSocket == null) return true; IPAddress remoteAddr = ((IPEndPoint)NetSocket.RemoteEndPoint).Address; return IPAddress.IsLoopback(remoteAddr); } // IsLocal internal bool CustomErrorsEnabled() { try { return RemotingConfiguration.CustomErrorsEnabled(IsLocalhost()); } catch { return true; } } // does any necessary cleanup before reading the incoming message protected abstract void PrepareForNewMessage(); // allows derived classes to send an error message if the async read // in BeginReadMessage fails. protected virtual void SendErrorMessageIfPossible(Exception e) { } // allows socket handler to do something when an input stream it handed // out is closed. The input stream is responsible for calling this method. // (usually, only client socket handlers will do anything with this). // (input stream refers to data being read off of the network) public virtual void OnInputStreamClosed() { } public virtual void Close() { try { if (_requestQueue != null) _requestQueue.ScheduleMoreWorkIfNeeded(); if (NetStream != null) { NetStream.Close(); NetStream = null; } if (NetSocket != null) { NetSocket.Close(); NetSocket = null; } } finally { ReturnBufferToPool(); } } // Close private byte[] DataBuffer { get { // Detect and prevent a NullReferenceException if the DataBuffer is // accessed after it has been returned to the byte buffer pool. // This is a risk mitigation. It doesn't appear to be hit in practice // and we should consider removing it in future versions. if (_dataBuffer == null) { InternalRemotingServices.RemotingAssert(false, "SocketHandler claiming a byte buffer after it has been returned to the pool"); _dataBuffer = CoreChannel.BufferPool.GetBuffer(); } return _dataBuffer; } } protected void ReturnBufferToPool() { // return buffer to the pool if (_dataBuffer != null) { byte[] bufferToReturn = Interlocked.Exchange(ref _dataBuffer, null); if (bufferToReturn != null) { CoreChannel.BufferPool.ReturnBuffer(bufferToReturn); } } } // ReturnBufferToPool public WaitCallback DataArrivedCallback { set { _dataArrivedCallback = value; } } // DataArrivedCallback public Object DataArrivedCallbackState { get { return _dataArrivedCallbackState; } set { _dataArrivedCallbackState = value; } } // DataArrivedCallbackState #if !FEATURE_PAL public WindowsIdentity ImpersonationIdentity { get { return _impersonationIdentity;} set { _impersonationIdentity = value;} } #endif // !FEATURE_PAL public void BeginReadMessage() { bool bProcessNow = false; try { if (_requestQueue != null) _requestQueue.ScheduleMoreWorkIfNeeded(); PrepareForNewMessage(); if (_dataCount == 0) { _beginReadAsyncResult = NetStream.BeginRead(DataBuffer, 0, _dataBufferSize, _beginReadCallback, null); } else { // just queue the request if we already have some data // (note: we intentionally don't call the callback directly to avoid // overflowing the stack if we service a bunch of calls) bProcessNow = true; } } catch (Exception e) { CloseOnFatalError(e); } if (bProcessNow) { if (_requestQueue != null) _requestQueue.ProcessNextRequest(this); else ProcessRequestNow(); _beginReadAsyncResult = null; } } // BeginReadMessage public void BeginReadMessageCallback(IAsyncResult ar) { bool bProcessRequest = false; // data has been buffered; proceed to call provided callback try { _beginReadAsyncResult = null; _dataOffset = 0; _dataCount = NetStream.EndRead(ar); if (_dataCount <= 0) { // socket has been closed Close(); } else { bProcessRequest = true; } } catch (Exception e) { CloseOnFatalError(e); } if (bProcessRequest) { if (_requestQueue != null) _requestQueue.ProcessNextRequest(this); else ProcessRequestNow(); } } // BeginReadMessageCallback internal void CloseOnFatalError(Exception e) { try { SendErrorMessageIfPossible(e); // Something bad happened, so we should just close everything and // return any buffers to the pool. Close(); } catch { try { Close(); } catch { // this is to prevent any weird errors with closing // a socket from showing up as an unhandled exception. } } } // CloseOnFatalError // Called when the SocketHandler is pulled off the pending request queue. internal void ProcessRequestNow() { try { WaitCallback waitCallback = _dataArrivedCallback; if (waitCallback != null) waitCallback(this); } catch (Exception e) { CloseOnFatalError(e); } } // ProcessRequestNow internal void RejectRequestNowSinceServerIsBusy() { CloseOnFatalError( new RemotingException( CoreChannel.GetResourceString("Remoting_ServerIsBusy"))); } // RejectRequestNow public int ReadByte() { if (Read(_byteBuffer, 0, 1) != -1) return _byteBuffer[0]; else return -1; } // ReadByte public void WriteByte(byte value, Stream outputStream) { _byteBuffer[0] = value; outputStream.Write(_byteBuffer, 0, 1); } // WriteUInt16 public UInt16 ReadUInt16() { Read(_byteBuffer, 0, 2); return (UInt16)(_byteBuffer[0] & 0xFF | _byteBuffer[1] << 8); } // ReadUInt16 public void WriteUInt16(UInt16 value, Stream outputStream) { _byteBuffer[0] = (byte)value; _byteBuffer[1] = (byte)(value >> 8); outputStream.Write(_byteBuffer, 0, 2); } // WriteUInt16 public int ReadInt32() { Read(_byteBuffer, 0, 4); return (int)((_byteBuffer[0] & 0xFF) | _byteBuffer[1] << 8 | _byteBuffer[2] << 16 | _byteBuffer[3] << 24); } // ReadInt32 public void WriteInt32(int value, Stream outputStream) { _byteBuffer[0] = (byte)value; _byteBuffer[1] = (byte)(value >> 8); _byteBuffer[2] = (byte)(value >> 16); _byteBuffer[3] = (byte)(value >> 24); outputStream.Write(_byteBuffer, 0, 4); } // WriteInt32 protected bool ReadAndMatchFourBytes(byte[] buffer) { InternalRemotingServices.RemotingAssert(buffer.Length == 4, "expecting 4 byte buffer."); Read(_byteBuffer, 0, 4); bool bMatch = (_byteBuffer[0] == buffer[0]) && (_byteBuffer[1] == buffer[1]) && (_byteBuffer[2] == buffer[2]) && (_byteBuffer[3] == buffer[3]); return bMatch; } // ReadAndMatchFourBytes public int Read(byte[] buffer, int offset, int count) { int totalBytesRead = 0; byte[] dataBuffer = this.DataBuffer; // see if we have buffered data if (_dataCount > 0) { // copy minimum of buffered data size and bytes left to read int readCount = Math.Min(_dataCount, count); StreamHelper.BufferCopy(dataBuffer, _dataOffset, buffer, offset, readCount); _dataCount -= readCount; _dataOffset += readCount; count -= readCount; offset += readCount; totalBytesRead += readCount; } // keep reading (whoever is calling this will make sure that they // don't try to read too much). while (count > 0) { if (count < 256) { // if count is less than 256 bytes, I will buffer more data // because it's not worth making a socket request for less. BufferMoreData(dataBuffer); // copy minimum of buffered data size and bytes left to read int readCount = Math.Min(_dataCount, count); StreamHelper.BufferCopy(dataBuffer, _dataOffset, buffer, offset, readCount); _dataCount -= readCount; _dataOffset += readCount; count -= readCount; offset += readCount; totalBytesRead += readCount; } else { // just go directly to the socket // the internal buffer is guaranteed to be empty at this point, so just // read directly into the array given int readCount = ReadFromSocket(buffer, offset, count); count -= readCount; offset += readCount; totalBytesRead += readCount; } } return totalBytesRead; } // Read // This should only be called when _dataCount is 0. private int BufferMoreData(byte[] dataBuffer) { InternalRemotingServices.RemotingAssert(_dataCount == 0, "SocketHandler::BufferMoreData called with data still in buffer." + "DataCount=" + _dataCount + "; DataOffset" + _dataOffset); int bytesRead = ReadFromSocket(dataBuffer, 0, _dataBufferSize); _dataOffset = 0; _dataCount = bytesRead; return bytesRead; } // BufferMoreData private int ReadFromSocket(byte[] buffer, int offset, int count) { int bytesRead = NetStream.Read(buffer, offset, count); if (bytesRead <= 0) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_Socket_UnderlyingSocketClosed")); } return bytesRead; } // ReadFromSocket protected byte[] ReadToByte(byte b) { return ReadToByte(b, null); } /// ReadToByte protected byte[] ReadToByte(byte b, ValidateByteDelegate validator) { byte[] readBytes = null; byte[] dataBuffer = this.DataBuffer; // start at current position and return byte array consisting of bytes // up to where we found the byte. if (_dataCount == 0) BufferMoreData(dataBuffer); int dataEnd = _dataOffset + _dataCount; // one byte past last valid byte int startIndex = _dataOffset; // current position int endIndex = startIndex; // current index bool foundByte = false; bool bufferEnd; while (!foundByte) { InternalRemotingServices.RemotingAssert(endIndex <= dataEnd, "endIndex shouldn't pass dataEnd"); bufferEnd = endIndex == dataEnd; foundByte = !bufferEnd && (dataBuffer[endIndex] == b); // validate character if necessary if ((validator != null) && !bufferEnd && !foundByte) { if (!validator(dataBuffer[endIndex])) { throw new RemotingException( CoreChannel.GetResourceString( "Remoting_Http_InvalidDataReceived")); } } // we're at the end of the currently buffered data or we've found our byte if (bufferEnd || foundByte) { // store processed byte in the readBytes array int count = endIndex - startIndex; if (readBytes == null) { readBytes = new byte[count]; StreamHelper.BufferCopy(dataBuffer, startIndex, readBytes, 0, count); } else { int oldSize = readBytes.Length; byte[] newBytes = new byte[oldSize + count]; StreamHelper.BufferCopy(readBytes, 0, newBytes, 0, oldSize); StreamHelper.BufferCopy(dataBuffer, startIndex, newBytes, oldSize, count); readBytes = newBytes; } // update data counters _dataOffset += count; _dataCount -= count; if (bufferEnd) { // we still haven't found the byte, so buffer more data // and keep looking. BufferMoreData(dataBuffer); // reset indices dataEnd = _dataOffset + _dataCount; // last valid byte startIndex = _dataOffset; // current position endIndex = startIndex; // current index } else if (foundByte) { // skip over the byte that we were looking for _dataOffset += 1; _dataCount -= 1; } } else { // still haven't found character or end of buffer, so advance position endIndex++; } } return readBytes; } // ReadToByte protected String ReadToChar(char ch) { return ReadToChar(ch, null); } // ReadToChar protected String ReadToChar(char ch, ValidateByteDelegate validator) { byte[] strBytes = ReadToByte((byte)ch, validator); if (strBytes == null) return null; if (strBytes.Length == 0) return String.Empty; String str = Encoding.ASCII.GetString(strBytes); return str; } // ReadToChar public String ReadToEndOfLine() { String str = ReadToChar('\r'); if (ReadByte() == '\n') return str; else return null; } // ReadToEndOfLine } // SocketHandler } // namespace System.Runtime.Remoting.Channels
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using RimWorld; using Verse; using Verse.AI; namespace CommunityCoreLibrary { public class DetourInjector : SpecialInjector { private const BindingFlags UniversalBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; public override bool Inject() { // Change CompGlower into CompGlowerToggleable FixGlowers(); // Change Building_NutrientPasteDispenser into Building_AdvancedPasteDispenser UpgradeNutrientPasteDispensers(); // Detour RimWorld.JoyGiver_SocialRelax.TryGiveJobInt MethodInfo RimWorld_JoyGiver_SocialRelax_TryGiveJobInt = typeof( JoyGiver_SocialRelax ).GetMethod( "TryGiveJobInt", UniversalBindingFlags ); MethodInfo CCL_JoyGiver_SocialRelax_TryGiveJobInt = typeof( Detour._JoyGiver_SocialRelax ).GetMethod( "_TryGiveJobInt", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_JoyGiver_SocialRelax_TryGiveJobInt, CCL_JoyGiver_SocialRelax_TryGiveJobInt ) ) return false; // Detour RimWorld.ThingSelectionUtility.SelectableNow MethodInfo RimWorld_ThingSelectionUtility_SelectableNow = typeof( ThingSelectionUtility ).GetMethod( "SelectableNow", UniversalBindingFlags ); MethodInfo CCL_ThingSelectionUtility_SelectableNow = typeof( Detour._ThingSelectionUtility ).GetMethod( "_SelectableNow", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_ThingSelectionUtility_SelectableNow, CCL_ThingSelectionUtility_SelectableNow ) ) return false; // Detour RimWorld.FoodUtility.GetFoodDef MethodInfo RimWorld_FoodUtility_GetFoodDef = typeof( FoodUtility ).GetMethod( "GetFoodDef", UniversalBindingFlags ); MethodInfo CCL_FoodUtility_GetFoodDef = typeof( Detour._FoodUtility ).GetMethod( "_GetFoodDef", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_FoodUtility_GetFoodDef, CCL_FoodUtility_GetFoodDef ) ) return false; // Detour RimWorld.FoodUtility.FoodSourceOptimality MethodInfo RimWorld_FoodUtility_FoodSourceOptimality = typeof( FoodUtility ).GetMethod( "FoodSourceOptimality", UniversalBindingFlags ); MethodInfo CCL_FoodUtility_FoodSourceOptimality = typeof( Detour._FoodUtility ).GetMethod( "_FoodSourceOptimality", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_FoodUtility_FoodSourceOptimality, CCL_FoodUtility_FoodSourceOptimality ) ) return false; // Detour RimWorld.FoodUtility.ThoughtsFromIngesting MethodInfo RimWorld_FoodUtility_ThoughtsFromIngesting = typeof( FoodUtility ).GetMethod( "ThoughtsFromIngesting", UniversalBindingFlags ); MethodInfo CCL_FoodUtility_ThoughtsFromIngesting = typeof( Detour._FoodUtility ).GetMethod( "_ThoughtsFromIngesting", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_FoodUtility_ThoughtsFromIngesting, CCL_FoodUtility_ThoughtsFromIngesting ) ) return false; // Detour RimWorld.FoodUtility.BestFoodSourceOnMap MethodInfo RimWorld_FoodUtility_BestFoodSourceOnMap = typeof( FoodUtility ).GetMethod( "BestFoodSourceOnMap", UniversalBindingFlags ); MethodInfo CCL_FoodUtility_BestFoodSourceOnMap = typeof( Detour._FoodUtility ).GetMethod( "_BestFoodSourceOnMap", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_FoodUtility_BestFoodSourceOnMap, CCL_FoodUtility_BestFoodSourceOnMap ) ) return false; // Detour RimWorld.JobDriver_FoodDeliver.MakeNewToils MethodInfo RimWorld_JobDriver_FoodDeliver_MakeNewToils = typeof( JobDriver_FoodDeliver ).GetMethod( "MakeNewToils", UniversalBindingFlags ); MethodInfo CCL_JobDriver_FoodDeliver_MakeNewToils = typeof( Detour._JobDriver_FoodDeliver ).GetMethod( "_MakeNewToils", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_JobDriver_FoodDeliver_MakeNewToils, CCL_JobDriver_FoodDeliver_MakeNewToils ) ) return false; // Detour RimWorld.JobDriver_FoodFeedPatient.MakeNewToils MethodInfo RimWorld_JobDriver_FoodFeedPatient_MakeNewToils = typeof( JobDriver_FoodFeedPatient ).GetMethod( "MakeNewToils", UniversalBindingFlags ); MethodInfo CCL_JobDriver_FoodFeedPatient_MakeNewToils = typeof( Detour._JobDriver_FoodFeedPatient ).GetMethod( "_MakeNewToils", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_JobDriver_FoodFeedPatient_MakeNewToils, CCL_JobDriver_FoodFeedPatient_MakeNewToils ) ) return false; // Detour RimWorld.JobDriver_Ingest.UsingNutrientPasteDispenser PropertyInfo RimWorld_JobDriver_Ingest_UsingNutrientPasteDispenser = typeof( JobDriver_Ingest ).GetProperty( "UsingNutrientPasteDispenser", UniversalBindingFlags ); MethodInfo RimWorld_JobDriver_Ingest_UsingNutrientPasteDispenser_get = RimWorld_JobDriver_Ingest_UsingNutrientPasteDispenser.GetGetMethod( true ); MethodInfo CCL_JobDriver_Ingest_UsingNutrientPasteDispenser = typeof( Detour._JobDriver_Ingest ).GetMethod( "_UsingNutrientPasteDispenser", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_JobDriver_Ingest_UsingNutrientPasteDispenser_get, CCL_JobDriver_Ingest_UsingNutrientPasteDispenser ) ) return false; // Detour RimWorld.JobDriver_Ingest.GetReport MethodInfo RimWorld_JobDriver_Ingest_GetReport = typeof( JobDriver_Ingest ).GetMethod( "GetReport", UniversalBindingFlags ); MethodInfo CCL_JobDriver_Ingest_GetReport = typeof( Detour._JobDriver_Ingest ).GetMethod( "_GetReport", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_JobDriver_Ingest_GetReport, CCL_JobDriver_Ingest_GetReport ) ) return false; // Detour RimWorld.JobDriver_Ingest.PrepareToEatToils_Dispenser MethodInfo RimWorld_JobDriver_Ingest_PrepareToEatToils_Dispenser = typeof( JobDriver_Ingest ).GetMethod( "PrepareToEatToils_Dispenser", UniversalBindingFlags ); MethodInfo CCL_JobDriver_Ingest_PrepareToEatToils_Dispenser = typeof( Detour._JobDriver_Ingest ).GetMethod( "_PrepareToEatToils_Dispenser", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_JobDriver_Ingest_PrepareToEatToils_Dispenser, CCL_JobDriver_Ingest_PrepareToEatToils_Dispenser ) ) return false; // Detour RimWorld.Toils_Ingest.TakeMealFromDispenser MethodInfo RimWorld_Toils_Ingest_TakeMealFromDispenser = typeof( Toils_Ingest ).GetMethod( "TakeMealFromDispenser", UniversalBindingFlags ); MethodInfo CCL_Toils_Ingest_TakeMealFromDispenser = typeof( Detour._Toils_Ingest ).GetMethod( "_TakeMealFromDispenser", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_Toils_Ingest_TakeMealFromDispenser, CCL_Toils_Ingest_TakeMealFromDispenser ) ) return false; // Detour RimWorld.JobGiver_GetFood.TryGiveJob MethodInfo RimWorld_JobGiver_GetFood_TryGiveJob = typeof( JobGiver_GetFood ).GetMethod( "TryGiveJob", UniversalBindingFlags ); MethodInfo CCL_JobGiver_GetFood_TryGiveJob = typeof( Detour._JobGiver_GetFood ).GetMethod( "_TryGiveJob", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_JobGiver_GetFood_TryGiveJob, CCL_JobGiver_GetFood_TryGiveJob ) ) return false; // Detour RimWorld.JobDriver_SocialRelax.MakeNewToils MethodInfo RimWorld_JobDriver_SocialRelax_MakeNewToils = typeof( JobDriver_SocialRelax ).GetMethod( "MakeNewToils", UniversalBindingFlags ); MethodInfo CCL_JobDriver_SocialRelax_MakeNewToils = typeof( Detour._JobDriver_SocialRelax ).GetMethod( "_MakeNewToils", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_JobDriver_SocialRelax_MakeNewToils, CCL_JobDriver_SocialRelax_MakeNewToils ) ) return false; // Detour Verse.MentalStateWorker_BingingAlcohol.StateCanOccur MethodInfo Verse_MentalStateWorker_BingingAlcohol_StateCanOccur = typeof( MentalStateWorker_BingingAlcohol ).GetMethod( "StateCanOccur", UniversalBindingFlags ); MethodInfo CCL_MentalStateWorker_BingingAlcohol_StateCanOccur = typeof( Detour._MentalStateWorker_BingingAlcohol ).GetMethod( "_StateCanOccur", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( Verse_MentalStateWorker_BingingAlcohol_StateCanOccur, CCL_MentalStateWorker_BingingAlcohol_StateCanOccur ) ) return false; // Detour RimWorld.CompRottable.CompTickRare MethodInfo RimWorld_CompRottable_CompTickRare = typeof( CompRottable ).GetMethod( "CompTickRare", UniversalBindingFlags ); MethodInfo CCL_CompRottable_CompTickRare = typeof( Detour._CompRottable ).GetMethod( "_CompTickRare", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_CompRottable_CompTickRare, CCL_CompRottable_CompTickRare ) ) return false; // Detour RimWorld.CompRottable.CompInspectStringExtra MethodInfo RimWorld_CompRottable_CompInspectStringExtra = typeof( CompRottable ).GetMethod( "CompInspectStringExtra", UniversalBindingFlags ); MethodInfo CCL_CompRottable_CompInspectStringExtra = typeof( Detour._CompRottable ).GetMethod( "_CompInspectStringExtra", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_CompRottable_CompInspectStringExtra, CCL_CompRottable_CompInspectStringExtra ) ) return false; // Detour Verse.CompHeatPusherPowered.ShouldPushHeatNow PropertyInfo Verse_CompHeatPusherPowered_ShouldPushHeatNow = typeof( CompHeatPusherPowered ).GetProperty( "ShouldPushHeatNow", UniversalBindingFlags ); #if DEBUG if( Verse_CompHeatPusherPowered_ShouldPushHeatNow == null ) { CCL_Log.Error( "Unable to find 'Verse.CompHeatPusherPowered.ShouldPushHeatNow'" ); return false; } #endif MethodInfo Verse_CompHeatPusherPowered_ShouldPushHeatNow_Getter = Verse_CompHeatPusherPowered_ShouldPushHeatNow.GetGetMethod( true ); MethodInfo CCL_CompHeatPusherPowered_ShouldPushHeatNow = typeof( Detour._CompHeatPusherPowered ).GetMethod( "_ShouldPushHeatNow", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( Verse_CompHeatPusherPowered_ShouldPushHeatNow_Getter, CCL_CompHeatPusherPowered_ShouldPushHeatNow ) ) return false; // Detour Verse.CompGlower.ShouldBeLitNow PropertyInfo Verse_CompGlower_ShouldBeLitNow = typeof( CompGlower ).GetProperty( "ShouldBeLitNow", UniversalBindingFlags ); #if DEBUG if( Verse_CompGlower_ShouldBeLitNow == null ) { CCL_Log.Error( "Unable to find 'Verse.CompGlower.ShouldBeLitNow'" ); return false; } #endif MethodInfo Verse_CompGlower_ShouldBeLitNow_Getter = Verse_CompGlower_ShouldBeLitNow.GetGetMethod( true ); MethodInfo CCL_CompGlower_ShouldBeLitNow = typeof( Detour._CompGlower ).GetMethod( "_ShouldBeLitNow", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( Verse_CompGlower_ShouldBeLitNow_Getter, CCL_CompGlower_ShouldBeLitNow ) ) return false; // Detour RimWorld.MainTabWindow_Research.DrawLeftRect "NotFinished" predicate function // Use build number to get the correct predicate function var RimWorld_MainTabWindow_Research_DrawLeftRect_NotFinished_Name = string.Empty; var RimWorld_Build = RimWorld.VersionControl.CurrentBuild; switch( RimWorld_Build ) { case 1220: case 1230: RimWorld_MainTabWindow_Research_DrawLeftRect_NotFinished_Name = "<DrawLeftRect>m__460"; break; case 1232: RimWorld_MainTabWindow_Research_DrawLeftRect_NotFinished_Name = "<DrawLeftRect>m__45E"; break; case 1234: case 1238: case 1241: case 1249: RimWorld_MainTabWindow_Research_DrawLeftRect_NotFinished_Name = "<DrawLeftRect>m__45F"; break; default: CCL_Log.Trace( Verbosity.Warnings, "CCL needs updating for RimWorld build " + RimWorld_Build.ToString() ); break; } if( RimWorld_MainTabWindow_Research_DrawLeftRect_NotFinished_Name != string.Empty ) { MethodInfo RimWorld_MainTabWindow_Research_DrawLeftRect_NotFinished = typeof( RimWorld.MainTabWindow_Research ).GetMethod( RimWorld_MainTabWindow_Research_DrawLeftRect_NotFinished_Name, UniversalBindingFlags ); MethodInfo CCL_MainTabWindow_Research_DrawLeftRect_NotFinishedNotLockedOut = typeof( Detour._MainTabWindow_Research ).GetMethod( "_NotFinishedNotLockedOut", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_MainTabWindow_Research_DrawLeftRect_NotFinished, CCL_MainTabWindow_Research_DrawLeftRect_NotFinishedNotLockedOut ) ) return false; } // Detour RimWorld.SocialProperness.IsSociallyProper MethodInfo RimWorld_SocialProperness_IsSociallyProper = typeof( SocialProperness ).GetMethods().First<MethodInfo>( ( arg ) => ( ( arg.Name == "IsSociallyProper" ) && ( arg.GetParameters().Count() == 4 ) ) ); MethodInfo CCL_SocialProperness_IsSociallyProper = typeof( Detour._SocialProperness ).GetMethod( "_IsSociallyProper", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_SocialProperness_IsSociallyProper, CCL_SocialProperness_IsSociallyProper ) ) return false; // Detour Verse.ThingListGroupHelper.Includes MethodInfo Verse_ThingListGroupHelper_Includes = typeof( ThingListGroupHelper ).GetMethod( "Includes", UniversalBindingFlags ); MethodInfo CCL_ThingListGroupHelper_Includes = typeof( Detour._ThingListGroupHelper ).GetMethod( "_Includes", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( Verse_ThingListGroupHelper_Includes, CCL_ThingListGroupHelper_Includes ) ) return false; // Detour RimWorld.GenConstruct.CanBuildOnTerrain MethodInfo RimWorld_GenConstruct_CanBuildOnTerrain = typeof( GenConstruct ).GetMethod( "CanBuildOnTerrain", UniversalBindingFlags ); MethodInfo CCL_GenConstruct_CanBuildOnTerrain = typeof( Detour._GenConstruct ).GetMethod( "_CanBuildOnTerrain", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_GenConstruct_CanBuildOnTerrain, CCL_GenConstruct_CanBuildOnTerrain ) ) return false; // Detour RimWorld.WorkGiver_Warden_DeliverFood.FoodAvailableInRoomTo MethodInfo RimWorld_WorkGiver_Warden_DeliverFood_FoodAvailableInRoomTo = typeof( WorkGiver_Warden_DeliverFood ).GetMethod( "FoodAvailableInRoomTo", UniversalBindingFlags ); MethodInfo CCL_WorkGiver_Warden_DeliverFood_FoodAvailableInRoomTo = typeof( Detour._WorkGiver_Warden_DeliverFood ).GetMethod( "_FoodAvailableInRoomTo", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_WorkGiver_Warden_DeliverFood_FoodAvailableInRoomTo, CCL_WorkGiver_Warden_DeliverFood_FoodAvailableInRoomTo ) ) return false; // Detour Verse.PreLoadUtility.CheckVersionAndLoad MethodInfo Verse_PreLoadUtility_CheckVersionAndLoad = typeof( PreLoadUtility ).GetMethod( "CheckVersionAndLoad", UniversalBindingFlags ); MethodInfo CCL_PreLoadUtility_CheckVersionAndLoad = typeof( Detour._PreLoadUtility ).GetMethod( "_CheckVersionAndLoad", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( Verse_PreLoadUtility_CheckVersionAndLoad, CCL_PreLoadUtility_CheckVersionAndLoad ) ) return false; // Detour RimWorld.PageUtility.InitGameStart MethodInfo RimWorld_PageUtility_InitGameStart = typeof( PageUtility ).GetMethod( "InitGameStart", UniversalBindingFlags ); MethodInfo CCL_PageUtility_InitGameStart = typeof( Detour._PageUtility ).GetMethod( "_InitGameStart", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_PageUtility_InitGameStart, CCL_PageUtility_InitGameStart ) ) return false; // Detour Verse.ModLister.InstalledModsListHash MethodInfo Verse_ModLister_InstalledModsListHash = typeof( ModLister ).GetMethod( "InstalledModsListHash", UniversalBindingFlags ); MethodInfo CCL_ModLister_InstalledModsListHash = typeof( Detour._ModLister ).GetMethod( "_InstalledModsListHash", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( Verse_ModLister_InstalledModsListHash, CCL_ModLister_InstalledModsListHash ) ) return false; // Detour RimWorld.OutfitDatabase.GenerateStartingOutfits MethodInfo RimWorld_OutfitDatabase_GenerateStartingOutfits = typeof( OutfitDatabase ).GetMethod( "GenerateStartingOutfits", UniversalBindingFlags ); MethodInfo CCL_OutfitDatabase_GenerateStartingOutfits = typeof( Detour._OutfitDatabase ).GetMethod( "_GenerateStartingOutfits", UniversalBindingFlags ); if (!Detours.TryDetourFromTo( RimWorld_OutfitDatabase_GenerateStartingOutfits, CCL_OutfitDatabase_GenerateStartingOutfits ) ) return false; // Detour RimWorld.Pawn_RelationsTracker.CompatibilityWith MethodInfo RimWorld_Pawn_RelationsTracker_CompatibilityWith = typeof( Pawn_RelationsTracker ).GetMethod( "CompatibilityWith", UniversalBindingFlags ); MethodInfo CCL_Pawn_RelationsTracker_CompatibilityWith = typeof( Detour._Pawn_RelationsTracker ).GetMethod( "_CompatibilityWith", UniversalBindingFlags ); if (!Detours.TryDetourFromTo( RimWorld_Pawn_RelationsTracker_CompatibilityWith, CCL_Pawn_RelationsTracker_CompatibilityWith ) ) return false; // Detour RimWorld.Pawn_RelationsTracker.AttractionTo MethodInfo RimWorld_Pawn_RelationsTracker_AttractionTo = typeof( Pawn_RelationsTracker ).GetMethod( "AttractionTo", UniversalBindingFlags ); MethodInfo CCL_Pawn_RelationsTracker_AttractionTo = typeof( Detour._Pawn_RelationsTracker ).GetMethod( "_AttractionTo", UniversalBindingFlags ); if (!Detours.TryDetourFromTo( RimWorld_Pawn_RelationsTracker_AttractionTo, CCL_Pawn_RelationsTracker_AttractionTo ) ) return false; // Detour RimWorld.PlaySettings.ExposeData MethodInfo RimWorld_PlaySetting_ExposeData = typeof( PlaySettings ).GetMethod( "ExposeData", UniversalBindingFlags ); MethodInfo CCL_PlaySetting_ExposeData = typeof( Detour._PlaySettings ).GetMethod( "_ExposeData", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_PlaySetting_ExposeData, CCL_PlaySetting_ExposeData ) ) return false; // Detour RimWorld.PlaySettings.DoPlaySettingsGlobalControls MethodInfo RimWorld_PlaySettings_DoPlaySettingsGlobalControls = typeof( PlaySettings ).GetMethod( "DoPlaySettingsGlobalControls", UniversalBindingFlags ); MethodInfo CCL_PlaySettings_DoPlaySettingsGlobalControls = typeof( Detour._PlaySettings ).GetMethod( "_DoPlaySettingsGlobalControls", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( RimWorld_PlaySettings_DoPlaySettingsGlobalControls, CCL_PlaySettings_DoPlaySettingsGlobalControls ) ) return false; /* // Detour MethodInfo foo = typeof( foo_class ).GetMethod( "foo_method", UniversalBindingFlags ); MethodInfo CCL_bar = typeof( Detour._bar ).GetMethod( "_bar_method", UniversalBindingFlags ); if( !Detours.TryDetourFromTo( foo, CCL_bar ) ) return false; */ return true; } private void FixGlowers() { foreach( var def in DefDatabase<ThingDef>.AllDefs.Where( def => ( ( def != null )&& ( def.comps != null )&& ( def.HasComp( typeof( CompGlower ) ) ) ) ) ) { var compGlower = def.GetCompProperties<CompProperties_Glower>(); compGlower.compClass = typeof( CompGlowerToggleable ); } } private void UpgradeNutrientPasteDispensers() { foreach( var def in DefDatabase<ThingDef>.AllDefs.Where( def => def.thingClass == typeof( Building_NutrientPasteDispenser ) ) ) { def.thingClass = typeof( Building_AdvancedPasteDispenser ); } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetFullPath : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Set up for the tests"); try { IOTests.IntializeVolume(); } catch { return InitializeResult.Skip; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestGetFullPath(string path, string expected) { string result = Path.GetFullPath(path); Log.Comment("Path: " + path); Log.Comment("Expected: " + expected); if (result != expected) { Log.Exception("Got: " + result); return false; } return true; } #endregion helper methods #region Test Cases [TestMethod] public MFTestResults Null() { MFTestResults result = MFTestResults.Pass; try { try { string path = Path.GetFullPath(""); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { string path = Path.GetFullPath(string.Empty); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { string path = Path.GetFullPath(null); Log.Exception("Expected ArgumentNullException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidCases() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetFullPath(@"file.tmp", Directory.GetCurrentDirectory() + @"\file.tmp")) { return MFTestResults.Fail; } // unrooted if (!TestGetFullPath(@"directory\file.tmp", Directory.GetCurrentDirectory() + @"\directory\file.tmp")) { return MFTestResults.Fail; } if (!TestGetFullPath(@"\ROOT\directory\file.tmp", @"\ROOT\directory\file.tmp")) { return MFTestResults.Fail; } // rooted if (!TestGetFullPath(@"\\machine\directory\file.tmp", @"\\machine\directory\file.tmp")) { return MFTestResults.Fail; } if (!TestGetFullPath(@"\sd1\directory\file", @"\sd1\directory\file")) { return MFTestResults.Fail; } if (!TestGetFullPath(@"\nand1\directory name\file name", @"\nand1\directory name\file name")) { return MFTestResults.Fail; } if (!TestGetFullPath(@"\sd1\directory.t name\file.t name.exe", @"\sd1\directory.t name\file.t name.exe")) { return MFTestResults.Fail; } // special - Might need actuall FS access to create directory structures to navigate if (!TestGetFullPath(".", Directory.GetCurrentDirectory())) { return MFTestResults.Fail; } if (!TestGetFullPath(@".\", Directory.GetCurrentDirectory())) { return MFTestResults.Fail; } //if (!TestGetFullPath("..", "")) //{ // return MFTestResults.Fail; //} } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults TooLongPath() { MFTestResults result = MFTestResults.Pass; try { string longBlock = new string('y', 135); try { string path = Path.GetFullPath(longBlock + longBlock); Log.Exception("Expected IOException(Path Too Long), but got: " + path); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); } // PathTooLong try { string path = Path.GetFullPath(@"\SD1\" + longBlock + "\\" + longBlock + "\\" + longBlock + longBlock + ".exe"); Log.Exception("Expected IOException(Path Too Long), but got: " + path); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); } //PathTooLong try { string path = Path.GetFullPath(new string('a', (int)UInt16.MaxValue + 1)); Log.Exception("Expected IOException(Path Too Long), but got: " + path); return MFTestResults.Fail; } catch (IOException ioe) { /* pass case */ Log.Comment( "Got correct exception: " + ioe.Message ); } //PathTooLong // chech bounds string boundResult; Directory.SetCurrentDirectory(IOTests.Volume.RootDirectory); string currDir = Directory.GetCurrentDirectory(); int len = currDir.Length; int limit = len + 258; // 258 is the FsMaxPathLength if (currDir.Substring(currDir.Length - 1) != (Path.DirectorySeparatorChar.ToString())) len++; for (int i = 225 - len; i < 275 - len; i++) { try { string str1 = new String('a', 100) + "\\" + new String('a', i- 101); // make a string of i length (need a \ in there so we don't have filename over 255) boundResult = Path.GetFullPath(str1); if (boundResult.Length >= limit) { Log.Exception( "Err_3974g! Didn't Throw: " + ( i + len ) + " - " + boundResult.Length ); return MFTestResults.Fail; } } catch (IOException) // PathTooLong { if ((len + i) < limit) { Log.Exception( "Err_245f! Threw too early: " + ( i + len ) ); return MFTestResults.Fail; } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WildCard() { MFTestResults result = MFTestResults.Pass; try { try { string path = Path.GetFullPath("file*"); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } try { string path = Path.GetFullPath(@"\sd1\file*"); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } try { string path = Path.GetFullPath(@"\sd1\file*.txt"); Log.Exception("Expected ArgumentException exception, but got: " + path); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { 'b', 'a', 'd', '\\', invalidChar, 'p', 'a', 't', 'h', invalidChar, '.', 't', 'x', 't' }); string dir = Path.GetFullPath(path); if (invalidChar == 0) { Log.Exception("[Known issue] Expected Argument exception for for '" + path + "' but got: '" + dir + "'"); result = MFTestResults.KnownFailure; } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } catch (Exception) { /// There is one case where String.Split throws System.Exception instead of ArgumentException for certain invalid character. /// Fix String.Split? } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Null, "Null" ), new MFTestMethod( ValidCases, "ValidCases" ), new MFTestMethod( TooLongPath, "TooLongPath" ), new MFTestMethod( WildCard, "WildCard" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } }
// 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: Read-only wrapper for another generic dictionary. ** ===========================================================*/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.Collections.ObjectModel { [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] internal class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> { private readonly IDictionary<TKey, TValue> m_dictionary; private Object m_syncRoot; private KeyCollection m_keys; private ValueCollection m_values; public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } m_dictionary = dictionary; } protected IDictionary<TKey, TValue> Dictionary { get { return m_dictionary; } } public KeyCollection Keys { get { if (m_keys == null) { m_keys = new KeyCollection(m_dictionary.Keys); } return m_keys; } } public ValueCollection Values { get { if (m_values == null) { m_values = new ValueCollection(m_dictionary.Values); } return m_values; } } #region IDictionary<TKey, TValue> Members public bool ContainsKey(TKey key) { return m_dictionary.ContainsKey(key); } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } } public bool TryGetValue(TKey key, out TValue value) { return m_dictionary.TryGetValue(key, out value); } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } } public TValue this[TKey key] { get { return m_dictionary[key]; } } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool IDictionary<TKey, TValue>.Remove(TKey key) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } TValue IDictionary<TKey, TValue>.this[TKey key] { get { return m_dictionary[key]; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members public int Count { get { return m_dictionary.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return m_dictionary.Contains(item); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { m_dictionary.CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return m_dictionary.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_dictionary).GetEnumerator(); } #endregion #region IDictionary Members private static bool IsCompatibleKey(object key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return key is TKey; } void IDictionary.Add(object key, object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IDictionary.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool IDictionary.Contains(object key) { return IsCompatibleKey(key) && ContainsKey((TKey)key); } IDictionaryEnumerator IDictionary.GetEnumerator() { IDictionary d = m_dictionary as IDictionary; if (d != null) { return d.GetEnumerator(); } return new DictionaryEnumerator(m_dictionary); } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { return Keys; } } void IDictionary.Remove(object key) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ICollection IDictionary.Values { get { return Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { return this[(TKey)key]; } return null; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { m_dictionary.CopyTo(pairs, index); } else { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; if (dictEntryArray != null) { foreach (var item in m_dictionary) { dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value); } } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } try { foreach (var item in m_dictionary) { objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value); } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_dictionary as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } private struct DictionaryEnumerator : IDictionaryEnumerator { private readonly IDictionary<TKey, TValue> m_dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary) { m_dictionary = dictionary; m_enumerator = m_dictionary.GetEnumerator(); } public DictionaryEntry Entry { get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); } } public object Key { get { return m_enumerator.Current.Key; } } public object Value { get { return m_enumerator.Current.Value; } } public object Current { get { return Entry; } } public bool MoveNext() { return m_enumerator.MoveNext(); } public void Reset() { m_enumerator.Reset(); } } #endregion #region IReadOnlyDictionary members IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return Keys; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return Values; } } #endregion IReadOnlyDictionary members [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private readonly ICollection<TKey> m_collection; private Object m_syncRoot; internal KeyCollection(ICollection<TKey> collection) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } m_collection = collection; } #region ICollection<T> Members void ICollection<TKey>.Add(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<TKey>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<TKey>.Contains(TKey item) { return m_collection.Contains(item); } public void CopyTo(TKey[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } bool ICollection<TKey>.Remove(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } #endregion #region IEnumerable<T> Members public IEnumerator<TKey> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(m_collection, array, index); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion } [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private readonly ICollection<TValue> m_collection; private Object m_syncRoot; internal ValueCollection(ICollection<TValue> collection) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } m_collection = collection; } #region ICollection<T> Members void ICollection<TValue>.Add(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<TValue>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<TValue>.Contains(TValue item) { return m_collection.Contains(item); } public void CopyTo(TValue[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } bool ICollection<TValue>.Remove(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } #endregion #region IEnumerable<T> Members public IEnumerator<TValue> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(m_collection, array, index); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion ICollection Members } } // To share code when possible, use a non-generic class to get rid of irrelevant type parameters. internal static class ReadOnlyDictionaryHelpers { #region Helper method for our KeyCollection and ValueCollection // Abstracted away to avoid redundant implementations. internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < collection.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } // Easy out if the ICollection<T> implements the non-generic ICollection ICollection nonGenericCollection = collection as ICollection; if (nonGenericCollection != null) { nonGenericCollection.CopyTo(array, index); return; } T[] items = array as T[]; if (items != null) { collection.CopyTo(items, index); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } try { foreach (var item in collection) { objects[index++] = item; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } #endregion Helper method for our KeyCollection and ValueCollection } }
/**********************************************************************/ /* */ /* SharePoint Solution Installer */ /* http://www.codeplex.com/sharepointinstaller */ /* */ /* (c) Copyright 2007 Lars Fastrup Nielsen. */ /* */ /* This source is subject to the Microsoft Permissive License. */ /* http://www.codeplex.com/sharepointinstaller/Project/License.aspx */ /* */ /* KML: Minor update to usage of EULA config property and error text */ /* */ /**********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Security; using System.ServiceProcess; using System.Text; using System.Threading; using System.Timers; using System.Windows.Forms; using Microsoft.Win32; using Microsoft.SharePoint.Administration; using System.Configuration; using System.IO; using CodePlex.SharePointInstaller.Resources; namespace CodePlex.SharePointInstaller { public enum SharePointVersion { SP2007, SP2010, Unrestricted } public partial class SystemCheckControl : InstallerControl { private static readonly ILog log = LogManager.GetLogger(); private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); private bool requireMOSS; private bool requireSearchSKU; private SystemCheckList checks; private int nextCheckIndex; private int errors; #region Constructors public SystemCheckControl() { InitializeComponent(); this.Load += new EventHandler(SystemCheckControl_Load); } #endregion #region Public Properties public SharePointVersion SupportedSharePointVersion { set; get; } public bool RequireMOSS { get { return requireMOSS; } set { requireMOSS = value; } } public bool RequireSearchSKU { get { return requireSearchSKU; } set { requireSearchSKU = value; } } #endregion #region Event Handlers private void SystemCheckControl_Load(object sender, EventArgs e) { } private void TimerEventProcessor(Object myObject, EventArgs myEventArgs) { timer.Stop(); if (nextCheckIndex < checks.Count) { if (ExecuteCheck(nextCheckIndex)) { nextCheckIndex++; timer.Start(); return; } } FinalizeChecks(); } #endregion #region Protected Methods protected internal override void Open(InstallOptions options) { if (checks == null) { Form.NextButton.Enabled = false; Form.PrevButton.Enabled = false; checks = new SystemCheckList(); InitializeChecks(); timer.Interval = 100; timer.Tick += new EventHandler(TimerEventProcessor); timer.Start(); } } protected internal override void Close(InstallOptions options) { } #endregion #region Private Methods private void InitializeChecks() { this.tableLayoutPanel.SuspendLayout(); // // WSS Installed Check // AddCheck(GetWssOrSfInstalledCheck()); // // MOSS Installed Check // if (requireMOSS) { AddCheck(GetMossOrSharePoint2010InstalledCheck()); } // // Admin Rights Check // AdminRightsCheck adminRightsCheck = new AdminRightsCheck(); adminRightsCheck.QuestionText = CommonUIStrings.adminRightsCheckQuestionText; adminRightsCheck.OkText = CommonUIStrings.adminRightsCheckOkText; adminRightsCheck.ErrorText = CommonUIStrings.adminRightsCheckErrorText; AddCheck(adminRightsCheck); // // Admin Service Check // //AdminServiceCheck adminServiceCheck = new AdminServiceCheck(); //adminServiceCheck.QuestionText = CommonUIStrings.adminServiceCheckQuestionText; //adminServiceCheck.OkText = CommonUIStrings.adminServiceCheckOkText; //adminServiceCheck.ErrorText = CommonUIStrings.adminServiceCheckErrorText; //AddCheck(adminServiceCheck); // // Timer Service Check // AddCheck(GetTimerRunningCheck()); // // Solution File Check // SolutionFileCheck solutionFileCheck = new SolutionFileCheck(); solutionFileCheck.QuestionText = CommonUIStrings.solutionFileCheckQuestionText; solutionFileCheck.OkText = CommonUIStrings.solutionFileCheckOkText; AddCheck(solutionFileCheck); // // Solution Check // SolutionCheck solutionCheck = new SolutionCheck(); solutionCheck.QuestionText = InstallConfiguration.FormatString(CommonUIStrings.solutionCheckQuestionText); solutionCheck.OkText = InstallConfiguration.FormatString(CommonUIStrings.solutionFileCheckOkText); solutionCheck.ErrorText = InstallConfiguration.FormatString(CommonUIStrings.solutionCheckErrorText); AddCheck(solutionCheck); // // Add empty row that will eat up the rest of the // row space in the layout table. // this.tableLayoutPanel.RowCount++; this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel.ResumeLayout(false); this.tableLayoutPanel.PerformLayout(); } private SystemCheck GetTimerRunningCheck() { switch (SupportedSharePointVersion) { case SharePointVersion.SP2007: { return GetTimerCheck(12); } case SharePointVersion.SP2010: { return GetTimerCheck(14); } default: { BinaryCheck binaryCheck = new BinaryCheck(GetTimerCheck(12), GetTimerCheck(14)); binaryCheck.QuestionText = CommonUIStrings.mossOrSharePoint2010QuestionText; return binaryCheck; } } } private SystemCheck GetTimerCheck(int version) { TimerServiceCheck timerServiceCheck = new TimerServiceCheck(version); timerServiceCheck.QuestionText = CommonUIStrings.timerServiceCheckQuestionText; timerServiceCheck.OkText = CommonUIStrings.timerServiceCheckOkText; timerServiceCheck.ErrorText = CommonUIStrings.timerServiceCheckErrorText; return timerServiceCheck; } private SystemCheck GetMossCheck() { MOSSInstalledCheck mossCheck = new MOSSInstalledCheck(12); mossCheck.QuestionText = CommonUIStrings.mossCheckQuestionText; mossCheck.OkText = CommonUIStrings.mossCheckOkText; mossCheck.ErrorText = CommonUIStrings.mossCheckErrorText; return mossCheck; } private SystemCheck GetSP2010Check() { MOSSInstalledCheck mossCheck = new MOSSInstalledCheck(14); mossCheck.QuestionText = CommonUIStrings.sharePoint2010QuestionText; mossCheck.OkText = CommonUIStrings.sharePoint2010OkText; mossCheck.ErrorText = CommonUIStrings.sharePoint2010ErrorText; return mossCheck; } private SystemCheck GetMossOrSharePoint2010InstalledCheck() { switch (SupportedSharePointVersion) { case SharePointVersion.SP2007: { return GetMossCheck(); } case SharePointVersion.SP2010: { return GetSP2010Check(); } default: { BinaryCheck binaryCheck = new BinaryCheck(GetMossCheck(), GetSP2010Check()); binaryCheck.QuestionText = CommonUIStrings.mossOrSharePoint2010QuestionText; return binaryCheck; } } } private SystemCheck GetWssOrSfInstalledCheck() { switch (SupportedSharePointVersion) { case SharePointVersion.SP2007: { return GetWssInstalledCheck(); } case SharePointVersion.SP2010: { return GetSfInstalledCheck(); } //all versions are supported by default default: { BinaryCheck binaryCheck = new BinaryCheck(GetWssInstalledCheck(), GetSfInstalledCheck()); binaryCheck.QuestionText = CommonUIStrings.wssOrSfCheckQuestionText; return binaryCheck; } } } private static SystemCheck GetSfInstalledCheck() { WSSInstalledCheck sfCheck = new WSSInstalledCheck(14); sfCheck.QuestionText = CommonUIStrings.sfCheckQuestionText; sfCheck.OkText = CommonUIStrings.sfCheckOkText; sfCheck.ErrorText = CommonUIStrings.sfCheckErrorText; return sfCheck; } private static SystemCheck GetWssInstalledCheck() { WSSInstalledCheck wssCheck = new WSSInstalledCheck(12); wssCheck.QuestionText = CommonUIStrings.wssCheckQuestionText; wssCheck.OkText = CommonUIStrings.wssCheckOkText; wssCheck.ErrorText = CommonUIStrings.wssCheckErrorText; return wssCheck; } private bool ExecuteCheck(int index) { SystemCheck check = checks[index]; string imageLabelName = "imageLabel" + index; string textLabelName = "textLabel" + index; Label imageLabel = (Label)tableLayoutPanel.Controls[imageLabelName]; Label textLabel = (Label)tableLayoutPanel.Controls[textLabelName]; try { SystemCheckResult result = check.Execute(); if (result == SystemCheckResult.Success) { imageLabel.Image = global::CodePlex.SharePointInstaller.Properties.Resources.CheckOk; textLabel.Text = check.OkText; } else if (result == SystemCheckResult.Error) { errors++; imageLabel.Image = global::CodePlex.SharePointInstaller.Properties.Resources.CheckFail; textLabel.Text = check.ErrorText; } // // Show play icon on next check that will run. // int nextIndex = index + 1; string nextImageLabelName = "imageLabel" + nextIndex; Label nextImageLabel = (Label)tableLayoutPanel.Controls[nextImageLabelName]; if (nextImageLabel != null) { nextImageLabel.Image = global::CodePlex.SharePointInstaller.Properties.Resources.CheckPlay; } return true; } catch (InstallException ex) { errors++; imageLabel.Image = global::CodePlex.SharePointInstaller.Properties.Resources.CheckFail; textLabel.Text = ex.Message; } return false; } private void FinalizeChecks() { if (errors == 0) { ConfigureControls(); Form.NextButton.Enabled = true; messageLabel.Text = CommonUIStrings.messageLabelTextSuccess; } else { messageLabel.Text = InstallConfiguration.FormatString(CommonUIStrings.messageLabelTextError); } Form.PrevButton.Enabled = true; } private void AddCheck(SystemCheck check) { int row = tableLayoutPanel.RowCount; Label imageLabel = new Label(); imageLabel.Dock = System.Windows.Forms.DockStyle.Fill; imageLabel.Image = global::CodePlex.SharePointInstaller.Properties.Resources.CheckWait; imageLabel.Location = new System.Drawing.Point(3, 0); imageLabel.Name = "imageLabel" + row; imageLabel.Size = new System.Drawing.Size(24, 20); Label textLabel = new Label(); textLabel.AutoSize = true; textLabel.Dock = System.Windows.Forms.DockStyle.Fill; textLabel.Location = new System.Drawing.Point(33, 0); textLabel.Name = "textLabel" + row; textLabel.Size = new System.Drawing.Size(390, 20); textLabel.Text = check.QuestionText; textLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.tableLayoutPanel.Controls.Add(imageLabel, 0, row); this.tableLayoutPanel.Controls.Add(textLabel, 1, row); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel.RowCount++; checks.Add(check); } private void ConfigureControls() { SolutionCheck check = (SolutionCheck)checks["SolutionCheck"]; SPSolution solution = check.Solution; if (solution == null) { AddInstallControls(); } else { Version installedVersion = InstallConfiguration.InstalledVersion; Version newVersion = InstallConfiguration.SolutionVersion; if (newVersion != installedVersion) { Form.ContentControls.Add(Program.CreateUpgradeControl()); } else { Form.ContentControls.Add(Program.CreateRepairControl()); } } } private void AddInstallControls() { // // Add EULA control if an EULA file was specified. // string filename = InstallConfiguration.EULA; if (!String.IsNullOrEmpty(filename)) { Form.ContentControls.Add(Program.CreateEULAControl()); } Form.ContentControls.Add(Program.CreateDeploymentTargetsControl()); //Form.ContentControls.Add(Program.CreateOptionsControl()); Form.ContentControls.Add(Program.CreateProcessControl()); } #endregion #region Check Classes private enum SystemCheckResult { Inconclusive, Success, Error } /// <summary> /// Base class for all system checks. /// </summary> private abstract class SystemCheck { private readonly string id; private string questionText; private string okText; private string errorText; protected SystemCheck(string id) { this.id = id; } public string Id { get { return id; } } public string QuestionText { get { return questionText; } set { questionText = value; } } public string OkText { get { return okText; } set { okText = value; } } public string ErrorText { get { return errorText; } set { errorText = value; } } internal SystemCheckResult Execute() { if (CanRun) { return DoExecute(); } return SystemCheckResult.Inconclusive; } protected abstract SystemCheckResult DoExecute(); protected virtual bool CanRun { get { return true; } } protected static bool IsWSSInstalled() { return IsWSSInstalled(12) || IsWSSInstalled(14); } protected static bool IsWSSInstalled(int version) { string path = string.Format(@"SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\{0}.0", version); try { RegistryKey key = Registry.LocalMachine.OpenSubKey(path); if (key != null) { object val = key.GetValue("SharePoint"); if (val != null && val.Equals("Installed")) { return true; } } return false; } catch (SecurityException ex) { throw new InstallException(string.Format(Resources.CommonUIStrings.installExceptionAccessDenied, path), ex); } } protected static bool IsMOSSInstalled(int version) { string name = string.Format(@"SOFTWARE\Microsoft\Office Server\{0}.0", version); try { RegistryKey key = Registry.LocalMachine.OpenSubKey(name); if (key != null) { string versionStr = key.GetValue("BuildVersion") as string; if (versionStr != null) { Version buildVersion = new Version(versionStr); if (buildVersion.Major == version) { return true; } } } return false; } catch (SecurityException ex) { throw new InstallException(string.Format(CommonUIStrings.installExceptionAccessDenied, name), ex); } } } private class SystemCheckList : List<SystemCheck> { internal SystemCheck this[string id] { get { foreach (SystemCheck check in this) { if (check.Id == id) return check; } return null; } } } /// <summary> /// Checks if WSS 3.0 is installed. /// </summary> private class WSSInstalledCheck : SystemCheck { int version; internal WSSInstalledCheck(int version) : base("WSSInstalledCheck") { this.version = version; } protected override SystemCheckResult DoExecute() { if (IsWSSInstalled(version)) return SystemCheckResult.Success; return SystemCheckResult.Error; } } /// <summary> /// Checks if one of checks is successful is installed. /// </summary> private class BinaryCheck : SystemCheck { SystemCheck first; SystemCheck second; internal BinaryCheck(SystemCheck first, SystemCheck second) : base("BinaryCheck") { if (first == null) throw new ArgumentNullException("first"); if (second == null) throw new ArgumentNullException("second"); this.first = first; this.second = second; } protected override SystemCheckResult DoExecute() { SystemCheckResult firstResult = first.Execute(); SystemCheckResult secondResult = second.Execute(); if (firstResult == SystemCheckResult.Success) { OkText = first.OkText; return SystemCheckResult.Success; } else { if (secondResult == SystemCheckResult.Success) { OkText = second.OkText; return SystemCheckResult.Success; } else { ErrorText = first.ErrorText; return firstResult; } } } } /// <summary> /// Checks if Microsoft Office Server 2007 is installed. /// </summary> private class MOSSInstalledCheck : SystemCheck { int version; internal MOSSInstalledCheck(int version) : base("MOSSInstalledCheck") { this.version = version; } protected override SystemCheckResult DoExecute() { if (IsMOSSInstalled(version)) return SystemCheckResult.Success; return SystemCheckResult.Error; } } /// <summary> /// Checks if the Windows SharePoint Services Administration service is started. /// </summary> private class AdminServiceCheck : SystemCheck { internal AdminServiceCheck() : base("AdminServiceCheck") { } protected override SystemCheckResult DoExecute() { try { ServiceController sc = new ServiceController("SPAdmin"); if (sc.Status == ServiceControllerStatus.Running) { return SystemCheckResult.Success; } return SystemCheckResult.Error; } catch (Win32Exception ex) { log.Error(ex.Message, ex); } catch (InvalidOperationException ex) { log.Error(ex.Message, ex); } return SystemCheckResult.Inconclusive; } protected override bool CanRun { get { return IsWSSInstalled(); } } } /// <summary> /// Checks if the Windows SharePoint Services Timer service is started. /// </summary> private class TimerServiceCheck : SystemCheck { int version; internal TimerServiceCheck(int version) : base("TimerServiceCheck") { this.version = version; } protected string GetTimerNameForVersion(int version) { switch (version) { case 12: return "SPTimerV3"; case 14: return "SPTimerV4"; default: throw new Exception(string.Format("No timer name defined for version {0}", version)); } } protected override SystemCheckResult DoExecute() { try { string timerName = GetTimerNameForVersion(version); ServiceController sc = new ServiceController(timerName); if (sc.Status == ServiceControllerStatus.Running) { return SystemCheckResult.Success; } return SystemCheckResult.Error; // // LFN 2009-06-21: Do not restart the time service anymore. First it does // not always work with Windows Server 2008 where it seems a local // admin may not necessarily be allowed to start and stop the service. // Secondly, the timer service has become more stable with WSS SP1 and SP2. // /*TimeSpan timeout = new TimeSpan(0, 0, 60); ServiceController sc = new ServiceController("SPTimerV3"); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, timeout); return SystemCheckResult.Success;*/ } catch (System.ServiceProcess.TimeoutException ex) { log.Error(ex.Message, ex); } catch (Win32Exception ex) { log.Error(ex.Message, ex); } catch (InvalidOperationException ex) { log.Error(ex.Message, ex); return SystemCheckResult.Error; } return SystemCheckResult.Inconclusive; } protected override bool CanRun { get { return IsWSSInstalled(); } } } /// <summary> /// Checks if the current user is an administrator. /// </summary> private class AdminRightsCheck : SystemCheck { internal AdminRightsCheck() : base("AdminRightsCheck") { } protected override SystemCheckResult DoExecute() { try { if (SPFarm.Local.CurrentUserIsAdministrator()) { return SystemCheckResult.Success; } return SystemCheckResult.Error; } catch (NullReferenceException) { throw new InstallException(CommonUIStrings.installExceptionDatabase); } catch (Exception ex) { throw new InstallException(ex.Message, ex); } } protected override bool CanRun { get { return IsWSSInstalled(); } } } private class SolutionFileCheck : SystemCheck { internal SolutionFileCheck() : base("SolutionFileCheck") { } protected override SystemCheckResult DoExecute() { string filename = InstallConfiguration.SolutionFile; if (!String.IsNullOrEmpty(filename)) { FileInfo solutionFileInfo = new FileInfo(filename); if (!solutionFileInfo.Exists) { throw new InstallException(string.Format(CommonUIStrings.installExceptionFileNotFound, filename)); } } else { throw new InstallException(CommonUIStrings.installExceptionConfigurationNoWsp); } return SystemCheckResult.Success; } } private class SolutionCheck : SystemCheck { private SPSolution solution; internal SolutionCheck() : base("SolutionCheck") { } protected override SystemCheckResult DoExecute() { Guid solutionId = Guid.Empty; try { solutionId = InstallConfiguration.SolutionId; } catch (ArgumentNullException) { throw new InstallException(CommonUIStrings.installExceptionConfigurationNoId); } catch (FormatException) { throw new InstallException(CommonUIStrings.installExceptionConfigurationInvalidId); } try { solution = SPFarm.Local.Solutions[solutionId]; if (solution != null) { this.OkText = InstallConfiguration.FormatString(CommonUIStrings.solutionCheckOkTextInstalled); } else { this.OkText = InstallConfiguration.FormatString(CommonUIStrings.solutionCheckOkTextNotInstalled); } } catch (NullReferenceException) { throw new InstallException(CommonUIStrings.installExceptionDatabase); } catch (Exception ex) { throw new InstallException(ex.Message, ex); } return SystemCheckResult.Success; } protected override bool CanRun { get { return IsWSSInstalled(); } } internal SPSolution Solution { get { return solution; } } } #endregion } }
//---------------------------------------------------------------------------- // Created on Tue Sep 2 18:09:33 2014 Raphael Thoulouze // // This program is the property of Persistant Studios SARL. // // You may not redistribute it and/or modify it under any conditions // without written permission from Persistant Studios SARL, unless // otherwise stated in the latest Persistant Studios Code License. // // See the Persistant Studios Code License for further details. //---------------------------------------------------------------------------- using UnityEditor; using UnityEngine; using System.IO; using System.Collections; using System.Collections.Generic; using System.Reflection; [CustomEditor(typeof(PKFxFX))] [CanEditMultipleObjects] public class PKFxFXEditor : Editor { SerializedProperty m_FxName; SerializedProperty m_FxAttributes; SerializedProperty m_FxSamplers; SerializedProperty m_PlayOnStart; SerializedProperty m_IsPlaying; SerializedProperty m_Smp; SerializedProperty m_ShapeType; SerializedProperty m_EditorShapeType; SerializedProperty m_ShapeCenter; SerializedProperty m_Dimensions; SerializedProperty m_EulerOrientation; string[] m_FxList; SerializedProperty m_BoundFx; //---------------------------------------------------------------------------- void OnEnable() { PKFxManager.Startup(); if (!PKFxManager.TryLoadPackRelative()) PKFxManager.LoadPack(PKFxManager.m_PackPath + "/PackFx"); this.m_FxName = serializedObject.FindProperty("m_FxName"); this.m_FxAttributes = serializedObject.FindProperty("m_FxAttributesList"); this.m_FxSamplers = serializedObject.FindProperty("m_FxSamplersList"); this.m_IsPlaying = serializedObject.FindProperty("m_IsPlaying"); this.m_PlayOnStart = serializedObject.FindProperty("m_PlayOnStart"); this.m_BoundFx = serializedObject.FindProperty("m_BoundFx"); serializedObject.ApplyModifiedProperties(); Reload(false); } //---------------------------------------------------------------------------- public void OnSceneGUI() { for (int i = 0; i < this.m_FxSamplers.arraySize; i++) { m_Smp = this.m_FxSamplers.GetArrayElementAtIndex(i); if (m_Smp.FindPropertyRelative("m_Descriptor.Type").intValue == (int)PKFxManager.ESamplerType.SamplerShape) { m_ShapeType = m_Smp.FindPropertyRelative("m_ShapeType"); m_ShapeCenter = m_Smp.FindPropertyRelative("m_ShapeCenter"); m_Dimensions = m_Smp.FindPropertyRelative("m_Dimensions"); m_EulerOrientation = m_Smp.FindPropertyRelative("m_EulerOrientation"); if (m_ShapeType.intValue == (int)PKFxManager.EShapeType.BoxShape) DrawCube(i); else if (m_ShapeType.intValue == (int)PKFxManager.EShapeType.SphereShape) DrawSphere(i); else if (m_ShapeType.intValue == (int)PKFxManager.EShapeType.CylinderShape) DrawCylinder(i); else if (m_ShapeType.intValue == (int)PKFxManager.EShapeType.CapsuleShape) DrawCapsule(i); } } } //---------------------------------------------------------------------------- public override void OnInspectorGUI() { serializedObject.Update(); if (!string.IsNullOrEmpty(m_FxName.stringValue) && File.Exists("Assets/StreamingAssets/PackFx/" + m_FxName.stringValue)) { m_BoundFx.objectReferenceValue = AssetDatabase.LoadAssetAtPath("Assets/StreamingAssets/PackFx/" + m_FxName.stringValue, typeof(Object)); } m_BoundFx.objectReferenceValue = EditorGUILayout.ObjectField("FX", m_BoundFx.objectReferenceValue, typeof(Object), false); string tmpPath = ""; if (m_BoundFx.objectReferenceValue != null) tmpPath = AssetDatabase.GetAssetPath(m_BoundFx.objectReferenceValue); if (tmpPath.StartsWith("Assets/StreamingAssets/PackFx/") && tmpPath.EndsWith(".pkfx")) { if (tmpPath.Substring("Assets/StreamingAssets/PackFx/".Length) != m_FxName.stringValue) { m_FxName.stringValue = tmpPath.Substring("Assets/StreamingAssets/PackFx/".Length); serializedObject.ApplyModifiedProperties(); if (!string.IsNullOrEmpty(this.m_FxName.stringValue)) PKFxManager.PreLoadFxIFN(this.m_FxName.stringValue); Reload(true); if (Application.isPlaying) (serializedObject.targetObject as PKFxFX).StartEffect(); } } else { if (!string.IsNullOrEmpty(tmpPath)) Debug.LogError("[PKFX] Invalid FX path.\n" + "Effects must be baked in Assets/StreamingAssets/PackFx/ (case sensitive) and have a .pkfx extension"); else m_FxName.stringValue = ""; m_BoundFx.objectReferenceValue = null; serializedObject.ApplyModifiedProperties(); Reload(false); } EditorGUI.BeginDisabledGroup(true); EditorGUILayout.PropertyField(this.m_IsPlaying); EditorGUI.EndDisabledGroup(); EditorGUILayout.PropertyField(this.m_PlayOnStart); for (int i = 0; i < this.m_FxSamplers.arraySize; i++) { SerializedProperty smp = this.m_FxSamplers.GetArrayElementAtIndex(i); SamplerField(smp); } if (m_FxAttributes.hasMultipleDifferentValues == false) { for (int i = 0; i < this.m_FxAttributes.arraySize; i++) { SerializedProperty attr = this.m_FxAttributes.GetArrayElementAtIndex(i); attr = PKFxEditor.AttributeField(attr); } } serializedObject.ApplyModifiedProperties(); displayPlaybackBtns(); } //---------------------------------------------------------------------------- private void displayPlaybackBtns() { serializedObject.Update(); Object[] effects = serializedObject.targetObjects; EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Reload Attributes")) { PKFxManager.UnloadEffect(m_FxName.stringValue); Reload(false); } if (GUILayout.Button("Reset Attributes To Default")) { foreach (PKFxFX fx in effects) { List<PKFxManager.AttributeDesc> FxAttributesDesc = PKFxManager.ListEffectAttributesFromFx(fx.FxPath); fx.ResetAttributesToDefault(FxAttributesDesc); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Stop")) { foreach (PKFxFX fx in effects) { fx.StopEffect(); } } if (GUILayout.Button("Terminate")) { foreach (PKFxFX fx in effects) { fx.TerminateEffect(); } } if (PKFxManager.KillIndividualEffectEnabled() && GUILayout.Button("Kill")) { foreach (PKFxFX fx in effects) { fx.KillEffect(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUI.BeginDisabledGroup(this.m_IsPlaying.boolValue); if (GUILayout.Button("Start")) { foreach (PKFxFX fx in effects) { fx.StartEffect(); } } EditorGUI.EndDisabledGroup(); if (GUILayout.Button("Restart")) { foreach (PKFxFX fx in effects) { fx.TerminateEffect(); fx.StartEffect(); } } EditorGUILayout.EndHorizontal(); } //---------------------------------------------------------------------------- void Reload(bool flushAttributes) { serializedObject.Update(); Object[] effects = serializedObject.targetObjects; foreach (PKFxFX fx in effects) { List<PKFxManager.AttributeDesc> FxAttributesDesc = PKFxManager.ListEffectAttributesFromFx(fx.FxPath); fx.LoadAttributes(FxAttributesDesc, flushAttributes); List<PKFxManager.SamplerDesc> FxSamplersDesc = PKFxManager.ListEffectSamplersFromFx(fx.FxPath); fx.LoadSamplers(FxSamplersDesc, flushAttributes); } serializedObject.ApplyModifiedProperties(); } //---------------------------------------------------------------------------- private SerializedProperty SamplerField(SerializedProperty sampler) { SerializedProperty m_Name = sampler.FindPropertyRelative("m_Descriptor.Name"); SerializedProperty m_Type = sampler.FindPropertyRelative("m_Descriptor.Type"); if (m_Type.intValue == (int)PKFxManager.ESamplerType.SamplerShape) { m_ShapeType = sampler.FindPropertyRelative("m_ShapeType"); m_EditorShapeType = sampler.FindPropertyRelative("m_EditorShapeType"); EditorGUILayout.LabelField(m_Name.stringValue); EditorGUI.indentLevel++; m_EditorShapeType.intValue = EditorGUILayout.Popup(m_EditorShapeType.intValue + 1, ShapeTypes); m_EditorShapeType.intValue--; // -1 to remove the index of None in ShapeTypes m_ShapeType.intValue = m_EditorShapeType.intValue; if (m_ShapeType.intValue >= 5) m_ShapeType.intValue--; //Remove the index of MESHFILTER in ShapeTypes if (m_EditorShapeType.intValue == (int)PKFxManager.EShapeType.BoxShape) BoxField(sampler); else if (m_EditorShapeType.intValue == (int)PKFxManager.EShapeType.SphereShape) SphereField(sampler); else if (m_EditorShapeType.intValue == (int)PKFxManager.EShapeType.CylinderShape) CylinderField(sampler); else if (m_EditorShapeType.intValue == (int)PKFxManager.EShapeType.CapsuleShape) CapsuleField(sampler); else if (m_EditorShapeType.intValue == (int)PKFxManager.EShapeType.MeshShape) MeshField(sampler); else if (m_EditorShapeType.intValue == (int)PKFxManager.EShapeType.MeshShape + 1) //MeshFilter MeshFilterField(sampler); else if (m_EditorShapeType.intValue == (int)PKFxManager.EShapeType.SkinnedMeshShape + 1) //Offset cause of the MeshFilter SkinnedMeshField(sampler); EditorGUI.indentLevel--; } else if (m_Type.intValue == (int)PKFxManager.ESamplerType.SamplerCurve) { SerializedProperty m_CurvesArray = sampler.FindPropertyRelative("m_CurvesArray"); SerializedProperty m_CurvesTimeKeys = sampler.FindPropertyRelative("m_CurvesTimeKeys"); EditorGUILayout.LabelField(m_Name.stringValue); EditorGUI.indentLevel++; int popupIndex = m_CurvesArray.arraySize == 0 ? 0 : m_CurvesArray.arraySize; int arraySize = EditorGUILayout.Popup(popupIndex, CurveDimensions); MultipleCurvesEditor(m_CurvesArray, arraySize); if (m_CurvesArray.arraySize != 0) { int iKey = 0; m_CurvesTimeKeys.arraySize = m_CurvesArray.GetArrayElementAtIndex(0).animationCurveValue.keys.Length; foreach (var key in m_CurvesArray.GetArrayElementAtIndex(0).animationCurveValue.keys) { m_CurvesTimeKeys.GetArrayElementAtIndex(iKey++).floatValue = key.time; } } else m_CurvesTimeKeys.arraySize = 0; EditorGUI.indentLevel--; } else if (m_Type.intValue == (int)PKFxManager.ESamplerType.SamplerImage) { EditorGUI.DrawRect(new Rect(0,0,10,10), new Color(0,1,0,1)); SerializedProperty m_Tex = sampler.FindPropertyRelative("m_Texture"); SerializedProperty m_TexChanged = sampler.FindPropertyRelative("m_TextureChanged"); SerializedProperty m_TextureTexcoordMode = sampler.FindPropertyRelative("m_TextureTexcoordMode"); m_TexChanged.boolValue = false; Texture2D newTex = (Texture2D)EditorGUILayout.ObjectField(m_Name.stringValue, m_Tex.objectReferenceValue, typeof(Texture2D), false); if (newTex != m_Tex.objectReferenceValue) { m_TexChanged.boolValue = true; m_Tex.objectReferenceValue = newTex; } EditorGUI.indentLevel++; EditorGUILayout.LabelField("Texcoord Mode"); PKFxManager.ETexcoordMode newType = (PKFxManager.ETexcoordMode)EditorGUILayout.EnumPopup((PKFxManager.ETexcoordMode)m_TextureTexcoordMode.intValue); m_TextureTexcoordMode.intValue = (int)newType; EditorGUI.indentLevel--; } else if (m_Type.intValue == (int)PKFxManager.ESamplerType.SamplerText) { SerializedProperty m_Text = sampler.FindPropertyRelative("m_Text"); EditorGUI.DrawRect(new Rect(0,0,10,10), new Color(0,0,1,1)); EditorGUILayout.LabelField(m_Name.stringValue); EditorGUI.indentLevel++; m_Text.stringValue = EditorGUILayout.TextField(m_Text.stringValue); EditorGUI.indentLevel--; } else if (m_Type.intValue == (int)PKFxManager.ESamplerType.SamplerUnsupported) { EditorGUI.BeginDisabledGroup(true); EditorGUI.DrawRect(new Rect(0, 0, 10, 10), new Color(0, 0, 1, 1)); EditorGUILayout.LabelField(m_Name.stringValue); EditorGUI.EndDisabledGroup(); } return sampler; } public void MultipleCurvesEditor(SerializedProperty curvesArray, int curveCount) { //delete curve IFN while (curvesArray.arraySize > curveCount) curvesArray.DeleteArrayElementAtIndex(curvesArray.arraySize - 1); //create curve IFN while (curvesArray.arraySize < curveCount) { curvesArray.InsertArrayElementAtIndex(curvesArray.arraySize); AnimationCurve curve; if (curvesArray.arraySize == 1) { curve = AnimationCurve.Linear(0.0f, 0.0f, 1.0f, 0.0f); curve.postWrapMode = WrapMode.Clamp; curve.preWrapMode = WrapMode.Clamp; } else curve = curvesArray.GetArrayElementAtIndex(0).animationCurveValue; curvesArray.GetArrayElementAtIndex(curvesArray.arraySize - 1).animationCurveValue = curve; } for (int i = 0; i < curvesArray.arraySize; ++i) { Keyframe[] keysCache = curvesArray.GetArrayElementAtIndex(i).animationCurveValue.keys; EditorGUILayout.PropertyField(curvesArray.GetArrayElementAtIndex(i), new GUIContent(CurveDimensionsNames[i])); MultipleCurvesCheckModify(curvesArray, i, keysCache); } } public void MultipleCurvesCheckModify(SerializedProperty curvesArray, int curveIndex, Keyframe[] keysCache) { AnimationCurve curve = curvesArray.GetArrayElementAtIndex(curveIndex).animationCurveValue; if (curve.keys.Length > 0) { if (curve.keys.Length < 2) { curve.keys = keysCache; curvesArray.GetArrayElementAtIndex(curveIndex).animationCurveValue = curve; } //add key else if (curve.keys.Length > keysCache.Length) { List<float> addedKeys = new List<float>(); MultipleCurvesFindKeysCountChanges(curve.keys, keysCache, addedKeys); foreach (var key in addedKeys) MultipleCurvesAddKey(curvesArray, curveIndex, key); } //delete key else if (curve.keys.Length < keysCache.Length) { List<float> deletedKeys = new List<float>(); MultipleCurvesFindKeysCountChanges(keysCache, curve.keys, deletedKeys); foreach (var key in deletedKeys) MultipleCurvesDeleteKey(curvesArray, curveIndex, key); } //change key else if (curve.keys.Length == keysCache.Length) { curvesArray.GetArrayElementAtIndex(curveIndex).animationCurveValue = curve; List<float> oldKeys; List<float> newKeys; MultipleCurvesFindKeysChanges(curve.keys, keysCache, out oldKeys, out newKeys); if (newKeys.Count != 0) { for (int iKey = 0; iKey < newKeys.Count; ++iKey) MultipleCurvesChangeKey(curvesArray, curveIndex, oldKeys[iKey], newKeys[iKey]); } } } } public void MultipleCurvesFindKeysCountChanges(Keyframe[] refKeys, Keyframe[] compKeys, List<float> diffKeys) { foreach (var key in refKeys) { bool found = false; foreach (var othkey in compKeys) { if (key.time == othkey.time) { found = true; break; } } if (!found) diffKeys.Add(key.time); } } public void MultipleCurvesFindKeysChanges(Keyframe[] actualKeys, Keyframe[] cacheKeys, out List<float> oldKeys, out List<float> newKeys) { List<float> addedKeys = new List<float>(); List<float> deletedKeys = new List<float>(); MultipleCurvesFindKeysCountChanges(actualKeys, cacheKeys, addedKeys); MultipleCurvesFindKeysCountChanges(cacheKeys, actualKeys, deletedKeys); if (addedKeys.Count != 0 && addedKeys.Count == deletedKeys.Count) { addedKeys.Sort(); deletedKeys.Sort(); } oldKeys = deletedKeys; newKeys = addedKeys; } public void MultipleCurvesAddKey(SerializedProperty curvesArray, int sourceCurveIndex, float time) { for (int i = 0; i < curvesArray.arraySize; ++i) { if (i == sourceCurveIndex) continue; AnimationCurve curve = curvesArray.GetArrayElementAtIndex(i).animationCurveValue; curve.AddKey(time, curve.Evaluate(time)); curvesArray.GetArrayElementAtIndex(i).animationCurveValue = curve; } } public void MultipleCurvesDeleteKey(SerializedProperty curvesArray, int sourceCurveIndex, float time) { for (int i = 0; i < curvesArray.arraySize; ++i) { if (i == sourceCurveIndex) continue; AnimationCurve curve = curvesArray.GetArrayElementAtIndex(i).animationCurveValue; for (int iKey = 0; iKey < curve.keys.Length; ++iKey) { if (curve.keys[iKey].time == time) { curve.RemoveKey(iKey); curvesArray.GetArrayElementAtIndex(i).animationCurveValue = curve; break; } } } } public void MultipleCurvesChangeKey(SerializedProperty curvesArray, int sourceCurveIndex, float oldTime, float newTime) { for (int i = 0; i < curvesArray.arraySize; ++i) { if (i == sourceCurveIndex) continue; AnimationCurve curve = curvesArray.GetArrayElementAtIndex(i).animationCurveValue; int iKey; for (iKey = 0; iKey < curve.keys.Length; ++iKey) { if (curve.keys[iKey].time == oldTime) { Keyframe keyframe = curve.keys[iKey]; keyframe.time = newTime; curve.RemoveKey(iKey); curve.AddKey(keyframe); curvesArray.GetArrayElementAtIndex(i).animationCurveValue = curve; break; } } } } public void MultipleCurvesUpdateKeys(SerializedProperty curvesArray, int sourceCurveIndex) { AnimationCurve sourceCurve = curvesArray.GetArrayElementAtIndex(sourceCurveIndex).animationCurveValue; for (int i = 0; i < curvesArray.arraySize; ++i) { if (i == sourceCurveIndex) continue; AnimationCurve curve = curvesArray.GetArrayElementAtIndex(i).animationCurveValue; curve.keys = sourceCurve.keys; curvesArray.GetArrayElementAtIndex(i).animationCurveValue = curve; } } //---------------------------------------------------------------------------- private static readonly string[] ShapeTypes = { "None", "BOX", "SPHERE", "CYLINDER", "CAPSULE", "MESH", "MESHFILTER", "SKINNEDMESH" }; private static readonly string[] CurveDimensions = { "None", "1", "2", "3", "4" }; private static readonly string[] CurveDimensionsNames = { "X", "Y", "Z", "W" }; private static void BoxField(SerializedProperty sampler) { SerializedProperty m_ShapeCenter = sampler.FindPropertyRelative("m_ShapeCenter"); SerializedProperty m_Dimensions = sampler.FindPropertyRelative("m_Dimensions"); SerializedProperty m_EulerOrientation = sampler.FindPropertyRelative("m_EulerOrientation"); EditorGUILayout.PropertyField(m_Dimensions); EditorGUILayout.PropertyField(m_ShapeCenter); EditorGUILayout.PropertyField(m_EulerOrientation); } private static void SphereField(SerializedProperty sampler) { SerializedProperty m_ShapeCenter = sampler.FindPropertyRelative("m_ShapeCenter"); SerializedProperty m_Dimensions = sampler.FindPropertyRelative("m_Dimensions"); SerializedProperty m_EulerOrientation = sampler.FindPropertyRelative("m_EulerOrientation"); Vector3 tmp = m_Dimensions.vector3Value; tmp.y = EditorGUILayout.FloatField("Inner Radius", Mathf.Min(tmp.x, tmp.y)); tmp.x = EditorGUILayout.FloatField("Radius", Mathf.Max(tmp.x, tmp.y)); m_Dimensions.vector3Value = tmp; EditorGUILayout.PropertyField(m_ShapeCenter); EditorGUILayout.PropertyField(m_EulerOrientation); } private static void CylinderField(SerializedProperty sampler) { SerializedProperty m_ShapeCenter = sampler.FindPropertyRelative("m_ShapeCenter"); SerializedProperty m_Dimensions = sampler.FindPropertyRelative("m_Dimensions"); SerializedProperty m_EulerOrientation = sampler.FindPropertyRelative("m_EulerOrientation"); Vector3 tmp = m_Dimensions.vector3Value; tmp.y = EditorGUILayout.FloatField("Inner Radius", Mathf.Min(tmp.x, tmp.y)); tmp.x = EditorGUILayout.FloatField("Radius", Mathf.Max(tmp.x, tmp.y)); tmp.z = EditorGUILayout.FloatField("Height", tmp.z); m_Dimensions.vector3Value = tmp; EditorGUILayout.PropertyField(m_ShapeCenter); EditorGUILayout.PropertyField(m_EulerOrientation); } private static void CapsuleField(SerializedProperty sampler) { SerializedProperty m_ShapeCenter = sampler.FindPropertyRelative("m_ShapeCenter"); SerializedProperty m_Dimensions = sampler.FindPropertyRelative("m_Dimensions"); SerializedProperty m_EulerOrientation = sampler.FindPropertyRelative("m_EulerOrientation"); Vector3 tmp = m_Dimensions.vector3Value; tmp.y = EditorGUILayout.FloatField("Inner Radius", Mathf.Min(tmp.x, tmp.y)); tmp.x = EditorGUILayout.FloatField("Radius", Mathf.Max(tmp.x, tmp.y)); tmp.z = EditorGUILayout.FloatField("Height", tmp.z); m_Dimensions.vector3Value = tmp; EditorGUILayout.PropertyField(m_ShapeCenter); EditorGUILayout.PropertyField(m_EulerOrientation); } private static void SamplingChannelsFields(SerializedProperty sampler, bool enableVelocity) { SerializedProperty m_SamplingChannels = sampler.FindPropertyRelative("m_SamplingChannels"); EditorGUILayout.Toggle("Sample Positions", true); m_SamplingChannels.intValue |= (int)PKFxManager.EMeshChannels.Channel_Position; if (EditorGUILayout.Toggle("Sample Normals", (m_SamplingChannels.intValue & (int)PKFxManager.EMeshChannels.Channel_Normal) != 0)) m_SamplingChannels.intValue |= (int)PKFxManager.EMeshChannels.Channel_Normal; else m_SamplingChannels.intValue &= ~(int)PKFxManager.EMeshChannels.Channel_Normal; if (EditorGUILayout.Toggle("Sample Tangents", (m_SamplingChannels.intValue & (int)PKFxManager.EMeshChannels.Channel_Tangent) != 0)) m_SamplingChannels.intValue |= (int)PKFxManager.EMeshChannels.Channel_Tangent; else m_SamplingChannels.intValue &= ~(int)PKFxManager.EMeshChannels.Channel_Tangent; if (!enableVelocity) m_SamplingChannels.intValue &= ~(int)PKFxManager.EMeshChannels.Channel_Velocity; else { if (EditorGUILayout.Toggle("Sample Velocity", (m_SamplingChannels.intValue & (int)PKFxManager.EMeshChannels.Channel_Velocity) != 0)) m_SamplingChannels.intValue |= (int)PKFxManager.EMeshChannels.Channel_Velocity; else m_SamplingChannels.intValue &= ~(int)PKFxManager.EMeshChannels.Channel_Velocity; } if (EditorGUILayout.Toggle("Sample UVs", (m_SamplingChannels.intValue & (int)PKFxManager.EMeshChannels.Channel_UV) != 0)) m_SamplingChannels.intValue |= (int)PKFxManager.EMeshChannels.Channel_UV; else m_SamplingChannels.intValue &= ~(int)PKFxManager.EMeshChannels.Channel_UV; if (EditorGUILayout.Toggle("Sample Vertex Color", (m_SamplingChannels.intValue & (int)PKFxManager.EMeshChannels.Channel_VertexColor) != 0)) m_SamplingChannels.intValue |= (int)PKFxManager.EMeshChannels.Channel_VertexColor; else m_SamplingChannels.intValue &= ~(int)PKFxManager.EMeshChannels.Channel_VertexColor; } private static void MeshField(SerializedProperty sampler) { SerializedProperty m_ShapeCenter = sampler.FindPropertyRelative("m_ShapeCenter"); SerializedProperty m_Dimensions = sampler.FindPropertyRelative("m_Dimensions"); SerializedProperty m_EulerOrientation = sampler.FindPropertyRelative("m_EulerOrientation"); SerializedProperty m_SkinnedMeshRenderer = sampler.FindPropertyRelative("m_SkinnedMeshRenderer"); SerializedProperty m_MeshFilter = sampler.FindPropertyRelative("m_MeshFilter"); SerializedProperty m_Mesh = sampler.FindPropertyRelative("m_Mesh"); SerializedProperty m_MeshHashCode = sampler.FindPropertyRelative("m_MeshHashCode"); EditorGUILayout.PropertyField(m_Mesh); if (m_Mesh.objectReferenceValue != null) m_MeshHashCode.intValue = (m_Mesh.objectReferenceValue as Mesh).name.GetHashCode(); else m_MeshHashCode.intValue = 0; m_SkinnedMeshRenderer.objectReferenceValue = null; m_MeshFilter.objectReferenceValue = null; EditorGUILayout.PropertyField(m_Dimensions); EditorGUILayout.PropertyField(m_ShapeCenter); EditorGUILayout.PropertyField(m_EulerOrientation); SamplingChannelsFields(sampler, false); } private static void MeshFilterField(SerializedProperty sampler) { SerializedProperty m_ShapeCenter = sampler.FindPropertyRelative("m_ShapeCenter"); SerializedProperty m_Dimensions = sampler.FindPropertyRelative("m_Dimensions"); SerializedProperty m_EulerOrientation = sampler.FindPropertyRelative("m_EulerOrientation"); SerializedProperty m_SkinnedMeshRenderer = sampler.FindPropertyRelative("m_SkinnedMeshRenderer"); SerializedProperty m_MeshFilter = sampler.FindPropertyRelative("m_MeshFilter"); SerializedProperty m_Mesh = sampler.FindPropertyRelative("m_Mesh"); SerializedProperty m_MeshHashCode = sampler.FindPropertyRelative("m_MeshHashCode"); EditorGUILayout.PropertyField(m_MeshFilter); if (m_MeshFilter.objectReferenceValue != null) m_Mesh.objectReferenceValue = (m_MeshFilter.objectReferenceValue as MeshFilter).sharedMesh; if (m_Mesh.objectReferenceValue != null) m_MeshHashCode.intValue = (m_Mesh.objectReferenceValue as Mesh).name.GetHashCode(); else m_MeshHashCode.intValue = 0; m_SkinnedMeshRenderer.objectReferenceValue = null; EditorGUILayout.PropertyField(m_Dimensions); EditorGUILayout.PropertyField(m_ShapeCenter); EditorGUILayout.PropertyField(m_EulerOrientation); SamplingChannelsFields(sampler, false); } private static void SkinnedMeshField(SerializedProperty sampler) { SerializedProperty m_ShapeCenter = sampler.FindPropertyRelative("m_ShapeCenter"); SerializedProperty m_Dimensions = sampler.FindPropertyRelative("m_Dimensions"); SerializedProperty m_EulerOrientation = sampler.FindPropertyRelative("m_EulerOrientation"); SerializedProperty m_SkinnedMeshRenderer = sampler.FindPropertyRelative("m_SkinnedMeshRenderer"); SerializedProperty m_MeshFilter = sampler.FindPropertyRelative("m_MeshFilter"); SerializedProperty m_Mesh = sampler.FindPropertyRelative("m_Mesh"); SerializedProperty m_MeshHashCode = sampler.FindPropertyRelative("m_MeshHashCode"); EditorGUILayout.PropertyField(m_SkinnedMeshRenderer); m_MeshFilter.objectReferenceValue = null; if (m_SkinnedMeshRenderer.objectReferenceValue != null) { Mesh mesh = (m_SkinnedMeshRenderer.objectReferenceValue as SkinnedMeshRenderer).sharedMesh; if (mesh != null) { if (System.String.IsNullOrEmpty(mesh.name)) { Debug.LogError("The mesh referenced by the SkinnedMeshRenderer must have a name"); return; } m_MeshHashCode.intValue = mesh.name.GetHashCode(); m_Mesh.objectReferenceValue = mesh; } else { m_MeshHashCode.intValue = 0; m_Mesh.objectReferenceValue = null; } } else { m_Mesh.objectReferenceValue = null; m_MeshHashCode.intValue = 0; } EditorGUILayout.PropertyField(m_Dimensions); EditorGUILayout.PropertyField(m_ShapeCenter); EditorGUILayout.PropertyField(m_EulerOrientation); SamplingChannelsFields(sampler, true); } //---------------------------------------------------------------------------- public void DrawSphere(int i) { PKFxFX fx = (PKFxFX)target; float radius = m_Dimensions.vector3Value.x; float innerRadius = m_Dimensions.vector3Value.y; Vector3 center = m_ShapeCenter.vector3Value; Vector3 objectPos = ((GameObject)fx.gameObject).transform.position; Quaternion rotation = Quaternion.Euler(((GameObject)fx.gameObject).transform.eulerAngles + m_EulerOrientation.vector3Value); Handles.color = Color.blue; innerRadius = Handles.RadiusHandle(rotation, objectPos + center, Mathf.Min(radius, innerRadius)); Handles.color = Color.cyan; radius = Handles.RadiusHandle(rotation, objectPos + center, Mathf.Max(radius, innerRadius)); m_Dimensions.vector3Value = new Vector3(radius, innerRadius, m_Dimensions.vector3Value.z); m_Dimensions.serializedObject.ApplyModifiedProperties(); } //---------------------------------------------------------------------------- private void _PrimitiveCapsule(ref float radius, Vector2 minMax, ref float height, Vector3 center, Quaternion rotation) { Vector3 topCenter = center + new Vector3(0f, height/2f, 0f); Vector3 lowCenter = center - new Vector3(0f, height/2f, 0f); Vector3 dir = topCenter - center; dir = rotation * dir; topCenter = center + dir; dir = lowCenter - center; dir = rotation * dir; lowCenter = center + dir; if (minMax.x != -1) { radius = Handles.RadiusHandle(rotation, topCenter, Mathf.Max(radius, minMax.x)); radius = Handles.RadiusHandle(rotation, lowCenter, Mathf.Max(radius, minMax.x)); } else if (minMax.y != -1) { radius = Handles.RadiusHandle(rotation, topCenter, Mathf.Min(radius, minMax.y)); radius = Handles.RadiusHandle(rotation, lowCenter, Mathf.Min(radius, minMax.y)); } Handles.DrawLine(topCenter + rotation * new Vector3(radius,0f,0f), lowCenter + rotation * new Vector3(radius,0f,0f)); Handles.DrawLine(topCenter - rotation * new Vector3(radius,0f,0f), lowCenter - rotation * new Vector3(radius,0f,0f)); Handles.DrawLine(topCenter + rotation * new Vector3(0f,0f,radius), lowCenter + rotation * new Vector3(0f,0f,radius)); Handles.DrawLine(topCenter - rotation * new Vector3(0f,0f,radius), lowCenter - rotation * new Vector3(0f,0f,radius)); } public void DrawCapsule(int i) { PKFxFX fx = (PKFxFX)target; float radius = m_Dimensions.vector3Value.x; float innerRadius = m_Dimensions.vector3Value.y; float height = m_Dimensions.vector3Value.z; Vector3 center = ((GameObject)fx.gameObject).transform.position + m_ShapeCenter.vector3Value; Quaternion rotation = Quaternion.Euler(((GameObject)fx.gameObject).transform.eulerAngles + m_EulerOrientation.vector3Value); Handles.color = Color.blue; _PrimitiveCapsule(ref innerRadius, new Vector2(-1, radius), ref height, center, rotation); Handles.color = Color.cyan; _PrimitiveCapsule(ref radius, new Vector2(innerRadius, -1), ref height, center, rotation); m_Dimensions.vector3Value = new Vector3(radius, innerRadius, height); m_Dimensions.serializedObject.ApplyModifiedProperties(); } //---------------------------------------------------------------------------- public void _PrimitiveCylinder(ref float radius, ref float height, Vector3 center, Quaternion rotation) { Vector3 topCenter = center + new Vector3(0f, height/2f, 0f); Vector3 lowCenter = center - new Vector3(0f, height/2f, 0f); Vector3 dir = topCenter - center; dir = rotation * dir; topCenter = center + dir; dir = lowCenter - center; dir = rotation * dir; lowCenter = center + dir; Handles.CircleCap(0, topCenter, rotation * Quaternion.FromToRotation(Vector3.forward, Vector3.up), radius); Handles.CircleCap(0, lowCenter, rotation * Quaternion.FromToRotation(Vector3.forward, Vector3.up), radius); Handles.DrawLine(topCenter + rotation * new Vector3(radius,0f,0f), lowCenter + rotation * new Vector3(radius,0f,0f)); Handles.DrawLine(topCenter - rotation * new Vector3(radius,0f,0f), lowCenter - rotation * new Vector3(radius,0f,0f)); Handles.DrawLine(topCenter + rotation * new Vector3(0f,0f,radius), lowCenter + rotation * new Vector3(0f,0f,radius)); Handles.DrawLine(topCenter - rotation * new Vector3(0f,0f,radius), lowCenter - rotation * new Vector3(0f,0f,radius)); } public void DrawCylinder(int i) { PKFxFX fx = (PKFxFX)target; float radius = m_Dimensions.vector3Value.x; float innerRadius = m_Dimensions.vector3Value.y; float height = m_Dimensions.vector3Value.z; Vector3 center = ((GameObject)fx.gameObject).transform.position + m_ShapeCenter.vector3Value; Quaternion rotation = Quaternion.Euler(((GameObject)fx.gameObject).transform.eulerAngles + m_EulerOrientation.vector3Value); Handles.color = Color.blue; _PrimitiveCylinder(ref innerRadius, ref height, center, rotation); Handles.color = Color.cyan; _PrimitiveCylinder(ref radius, ref height, center, rotation); m_Dimensions.vector3Value = new Vector3(radius, innerRadius, height); m_Dimensions.serializedObject.ApplyModifiedProperties(); } //---------------------------------------------------------------------------- public void DrawCube(int i) { PKFxFX fx = (PKFxFX)target; Vector3 center = ((GameObject)fx.gameObject).transform.position + m_ShapeCenter.vector3Value; Quaternion rotation = Quaternion.Euler(((GameObject)fx.gameObject).transform.eulerAngles + m_EulerOrientation.vector3Value); Vector3 size = m_Dimensions.vector3Value; Vector3 A = center + rotation * new Vector3(-size.x/2, size.y/2, size.z/2); Vector3 B = center + rotation * new Vector3(size.x/2, size.y/2, size.z/2); Vector3 C = center + rotation * new Vector3(size.x/2, -size.y/2, size.z/2); Vector3 D = center + rotation * new Vector3(-size.x/2, -size.y/2, size.z/2); Vector3 E = center + rotation * new Vector3(-size.x/2, size.y/2, -size.z/2); Vector3 F = center + rotation * new Vector3(size.x/2, size.y/2, -size.z/2); Vector3 G = center + rotation * new Vector3(size.x/2, -size.y/2, -size.z/2); Vector3 H = center + rotation * new Vector3(-size.x/2, -size.y/2, -size.z/2); Vector3[] face = new Vector3[5]; Handles.color = Color.cyan; face[0] = A; face[1] = B; face[2] = C; face[3] = D; face[4] = A; Handles.DrawPolyLine(face); face[0] = A; face[1] = E; face[2] = H; face[3] = D; face[4] = A; Handles.DrawPolyLine(face); face[0] = B; face[1] = F; face[2] = G; face[3] = C; face[4] = B; Handles.DrawPolyLine(face); face[0] = E; face[1] = F; face[2] = G; face[3] = H; face[4] = E; Handles.DrawPolyLine(face); } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using QuantConnect.Benchmarks; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Orders.Fills; using QuantConnect.Orders.Slippage; using QuantConnect.Securities; namespace QuantConnect.Brokerages { /// <summary> /// Models brokerage transactions, fees, and order /// </summary> public interface IBrokerageModel { /// <summary> /// Gets the account type used by this model /// </summary> AccountType AccountType { get; } /// <summary> /// Gets the brokerages model percentage factor used to determine the required unused buying power for the account. /// From 1 to 0. Example: 0 means no unused buying power is required. 0.5 means 50% of the buying power should be left unused. /// </summary> decimal RequiredFreeBuyingPowerPercent { get; } /// <summary> /// Gets a map of the default markets to be used for each security type /// </summary> IReadOnlyDictionary<SecurityType, string> DefaultMarkets { get; } /// <summary> /// Returns true if the brokerage could accept this order. This takes into account /// order type, security type, and order size limits. /// </summary> /// <remarks> /// For example, a brokerage may have no connectivity at certain times, or an order rate/size limit /// </remarks> /// <param name="security">The security being ordered</param> /// <param name="order">The order to be processed</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be submitted</param> /// <returns>True if the brokerage could process the order, false otherwise</returns> bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message); /// <summary> /// Returns true if the brokerage would allow updating the order as specified by the request /// </summary> /// <param name="security">The security of the order</param> /// <param name="order">The order to be updated</param> /// <param name="request">The requested updated to be made to the order</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be updated</param> /// <returns>True if the brokerage would allow updating the order, false otherwise</returns> bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message); /// <summary> /// Returns true if the brokerage would be able to execute this order at this time assuming /// market prices are sufficient for the fill to take place. This is used to emulate the /// brokerage fills in backtesting and paper trading. For example some brokerages may not perform /// executions during extended market hours. This is not intended to be checking whether or not /// the exchange is open, that is handled in the Security.Exchange property. /// </summary> /// <param name="security">The security being ordered</param> /// <param name="order">The order to test for execution</param> /// <returns>True if the brokerage would be able to perform the execution, false otherwise</returns> bool CanExecuteOrder(Security security, Order order); /// <summary> /// Applies the split to the specified order ticket /// </summary> /// <param name="tickets">The open tickets matching the split event</param> /// <param name="split">The split event data</param> void ApplySplit(List<OrderTicket> tickets, Split split); /// <summary> /// Gets the brokerage's leverage for the specified security /// </summary> /// <param name="security">The security's whose leverage we seek</param> /// <returns>The leverage for the specified security</returns> decimal GetLeverage(Security security); /// <summary> /// Get the benchmark for this model /// </summary> /// <param name="securities">SecurityService to create the security with if needed</param> /// <returns>The benchmark for this brokerage</returns> IBenchmark GetBenchmark(SecurityManager securities); /// <summary> /// Gets a new fill model that represents this brokerage's fill behavior /// </summary> /// <param name="security">The security to get fill model for</param> /// <returns>The new fill model for this brokerage</returns> IFillModel GetFillModel(Security security); /// <summary> /// Gets a new fee model that represents this brokerage's fee structure /// </summary> /// <param name="security">The security to get a fee model for</param> /// <returns>The new fee model for this brokerage</returns> IFeeModel GetFeeModel(Security security); /// <summary> /// Gets a new slippage model that represents this brokerage's fill slippage behavior /// </summary> /// <param name="security">The security to get a slippage model for</param> /// <returns>The new slippage model for this brokerage</returns> ISlippageModel GetSlippageModel(Security security); /// <summary> /// Gets a new settlement model for the security /// </summary> /// <param name="security">The security to get a settlement model for</param> /// <returns>The settlement model for this brokerage</returns> ISettlementModel GetSettlementModel(Security security); /// <summary> /// Gets a new settlement model for the security /// </summary> /// <param name="security">The security to get a settlement model for</param> /// <param name="accountType">The account type</param> /// <returns>The settlement model for this brokerage</returns> [Obsolete("Flagged deprecated and will remove December 1st 2018")] ISettlementModel GetSettlementModel(Security security, AccountType accountType); /// <summary> /// Gets a new buying power model for the security /// </summary> /// <param name="security">The security to get a buying power model for</param> /// <returns>The buying power model for this brokerage/security</returns> IBuyingPowerModel GetBuyingPowerModel(Security security); /// <summary> /// Gets a new buying power model for the security /// </summary> /// <param name="security">The security to get a buying power model for</param> /// <param name="accountType">The account type</param> /// <returns>The buying power model for this brokerage/security</returns> [Obsolete("Flagged deprecated and will remove December 1st 2018")] IBuyingPowerModel GetBuyingPowerModel(Security security, AccountType accountType); /// <summary> /// Gets the shortable provider /// </summary> /// <returns>Shortable provider</returns> IShortableProvider GetShortableProvider(); } /// <summary> /// Provides factory method for creating an <see cref="IBrokerageModel"/> from the <see cref="BrokerageName"/> enum /// </summary> public static class BrokerageModel { /// <summary> /// Creates a new <see cref="IBrokerageModel"/> for the specified <see cref="BrokerageName"/> /// </summary> /// <param name="orderProvider">The order provider</param> /// <param name="brokerage">The name of the brokerage</param> /// <param name="accountType">The account type</param> /// <returns>The model for the specified brokerage</returns> public static IBrokerageModel Create(IOrderProvider orderProvider, BrokerageName brokerage, AccountType accountType) { switch (brokerage) { case BrokerageName.Default: return new DefaultBrokerageModel(accountType); case BrokerageName.InteractiveBrokersBrokerage: return new InteractiveBrokersBrokerageModel(accountType); case BrokerageName.TradierBrokerage: return new TradierBrokerageModel(accountType); case BrokerageName.OandaBrokerage: return new OandaBrokerageModel(accountType); case BrokerageName.FxcmBrokerage: return new FxcmBrokerageModel(accountType); case BrokerageName.Bitfinex: return new BitfinexBrokerageModel(accountType); case BrokerageName.Binance: return new BinanceBrokerageModel(accountType); case BrokerageName.GDAX: return new GDAXBrokerageModel(accountType); case BrokerageName.AlphaStreams: return new AlphaStreamsBrokerageModel(accountType); case BrokerageName.Zerodha: return new ZerodhaBrokerageModel(accountType); case BrokerageName.Atreyu: return new AtreyuBrokerageModel(accountType); case BrokerageName.TradingTechnologies: return new TradingTechnologiesBrokerageModel(accountType); default: throw new ArgumentOutOfRangeException(nameof(brokerage), brokerage, null); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Portions derived from React Native: // Copyright (c) 2015-present, Facebook, Inc. // Licensed under the MIT License. using Newtonsoft.Json.Linq; using ReactNative.Bridge; using ReactNative.Modules.Core; using ReactNative.UIManager; using System.Collections.Concurrent; using System.Linq; using Windows.ApplicationModel.Core; using Windows.Graphics.Display; using Windows.UI.ViewManagement; namespace ReactNative.Modules.DeviceInfo { /// <summary> /// Native module that manages window dimension updates to JavaScript (with support for multi window application). /// </summary> /// <remarks> /// Dimensions are tracked for each application window right after creation of its ReactRootView. /// After any change in dimensions of any tracked window whole list of dimensions is emited and dimensions are available by 3 kinds of ids: /// /// "window" - dimensions of main window /// "{rootViewTag}" - dimensions of window with specified rootViewTag (each view has assigned one) /// "{rootViewId}" - dimensions of window initialized with unique value of "reactxp_rootViewId" property /// /// <example> /// { /// "window": { /* main window dimensions */ }, /// "1": { /* alt-window-dimensions */ }, /// "41": { /* alt-window dimensions */ }, /// "03391df9-750d-465c-b0b0-66ee9dcf4a86": { /* alt-window dimensions */ } /// } /// </example> /// </remarks> class DeviceInfoModule : ReactContextNativeModuleBase { private readonly JObject _constants; private readonly ConcurrentDictionary<ApplicationView, DeviceViewInfo> _registeredViews = new ConcurrentDictionary<ApplicationView, DeviceViewInfo>(); /// <summary> /// Instantiates the <see cref="DeviceInfoModule"/>. /// </summary> /// <param name="reactContext">The React context.</param> public DeviceInfoModule(ReactContext reactContext) : base(reactContext) { _constants = new JObject { { "Dimensions", GetAllDimensions() }, }; } /// <summary> /// The name of the native module. /// </summary> public override string Name { get { return "DeviceInfo"; } } /// <summary> /// Native module constants. /// </summary> public override JObject ModuleConstants { get { return _constants; } } /// <summary> /// Register <paramref name="rootView"/> to keep track of his dimensions /// </summary> /// <param name="rootView">The react root view</param> /// <param name="tag">The react root view tag</param> public void RegisterRootView(ReactRootView rootView, int tag) { DispatcherHelpers.AssertOnDispatcher(rootView); var appView = ApplicationView.GetForCurrentView(); _registeredViews.AddOrUpdate(appView, (v) => { // Register new view info and hook up for events var displayInformation = DisplayInformation.GetForCurrentView(); var info = new DeviceViewInfo(appView, rootView, displayInformation, tag); appView.VisibleBoundsChanged += OnVisibleBoundsChanged; displayInformation.OrientationChanged += OnOrientationChanged; return info; }, (view, info) => { // View is already registered, just update tag in case view is being reregistered info.RootViewTag = tag; return info; }); SendUpdateDimensionsEvent(); } /// <summary> /// Unregister <paramref name="rootView"/> and stop keeping track of his dimensions /// </summary> /// <param name="rootView">The react root view</param> public void UnregisterRootView(ReactRootView rootView) { DispatcherHelpers.AssertOnDispatcher(rootView); var info = _registeredViews.Values.SingleOrDefault(i => i.RootView == rootView); if (info != null && _registeredViews.TryRemove(info.ApplicationView, out info)) { info.ApplicationView.VisibleBoundsChanged -= OnVisibleBoundsChanged; info.DisplayInformation.OrientationChanged -= OnOrientationChanged; } } public void OnVisibleBoundsChanged(ApplicationView sender, object args) { if (_registeredViews.ContainsKey(sender)) { _registeredViews[sender].UpdateDisplayMetrics(); } SendUpdateDimensionsEvent(); } private void OnOrientationChanged(DisplayInformation displayInformation, object args) { var name = default(string); var degrees = default(double); var isLandscape = false; switch (displayInformation.CurrentOrientation) { case DisplayOrientations.Landscape: name = "landscape-primary"; degrees = -90.0; isLandscape = true; break; case DisplayOrientations.Portrait: name = "portrait-primary"; degrees = 0.0; break; case DisplayOrientations.LandscapeFlipped: name = "landscape-secondary"; degrees = 90.0; isLandscape = true; break; case DisplayOrientations.PortraitFlipped: name = "portraitSecondary"; degrees = 180.0; break; } if (name != null) { Context.GetJavaScriptModule<RCTDeviceEventEmitter>() .emit("namedOrientationDidChange", new JObject { { "name", name }, { "rotationDegrees", degrees }, { "isLandscape", isLandscape }, }); } } private void SendUpdateDimensionsEvent() { Context.GetJavaScriptModule<RCTDeviceEventEmitter>() .emit("didUpdateDimensions", GetAllDimensions()); } private JObject GetAllDimensions() { var dimensions = new JObject(); // Default metric for main window // TODO It would make sense to make default actively focused window and not the main in the future var mainView = _registeredViews.Values.FirstOrDefault(v => v.RootView.Dispatcher == DispatcherHelpers.MainDispatcher); var defaultMetrics = mainView == null ? GetDefaultDisplayMetrics() : mainView.CurrentDisplayMetrics; dimensions.Add("window", GetDimensions(defaultMetrics)); foreach (var info in _registeredViews.Values) { dimensions.Add($"{info.RootViewTag}", GetDimensions(info.CurrentDisplayMetrics)); if (info.RootViewId != null) { dimensions.Add($"{info.RootViewId}", GetDimensions(info.CurrentDisplayMetrics)); } } return dimensions; } private static JObject GetDimensions(DisplayMetrics displayMetrics) { return new JObject { { "width", displayMetrics.Width }, { "height", displayMetrics.Height }, { "scale", displayMetrics.Scale }, /* TODO: density and DPI needed? */ }; } private static DisplayMetrics GetDefaultDisplayMetrics() { if (CoreApplication.MainView.CoreWindow != null) { // TODO: blocking call not ideal, but should be inlined in almost all cases return DispatcherHelpers.CallOnDispatcher(DisplayMetrics.GetForCurrentView, true).Result; } return DisplayMetrics.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Reflection { [Serializable] internal class MemberInfoSerializationHolder : ISerializable, IObjectReference { #region Staitc Public Members public static void GetSerializationInfo(SerializationInfo info, String name, RuntimeType reflectedClass, String signature, MemberTypes type) { GetSerializationInfo(info, name, reflectedClass, signature, null, type, null); } public static void GetSerializationInfo( SerializationInfo info, String name, RuntimeType reflectedClass, String signature, String signature2, MemberTypes type, Type[] genericArguments) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); String assemblyName = reflectedClass.Module.Assembly.FullName; String typeName = reflectedClass.FullName; info.SetType(typeof(MemberInfoSerializationHolder)); info.AddValue("Name", name, typeof(String)); info.AddValue("AssemblyName", assemblyName, typeof(String)); info.AddValue("ClassName", typeName, typeof(String)); info.AddValue("Signature", signature, typeof(String)); info.AddValue("Signature2", signature2, typeof(String)); info.AddValue("MemberType", (int)type); info.AddValue("GenericArguments", genericArguments, typeof(Type[])); } #endregion #region Private Data Members private String m_memberName; private RuntimeType m_reflectedType; // m_signature stores the ToString() representation of the member which is sometimes ambiguous. // Mulitple overloads of the same methods or properties can identical ToString(). // m_signature2 stores the SerializationToString() representation which should be unique for each member. // It is only written and used by post 4.0 CLR versions. private String m_signature; private String m_signature2; private MemberTypes m_memberType; private SerializationInfo m_info; #endregion #region Constructor internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); String assemblyName = info.GetString("AssemblyName"); String typeName = info.GetString("ClassName"); if (assemblyName == null || typeName == null) throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState")); Assembly assem = FormatterServices.LoadAssemblyFromString(assemblyName); m_reflectedType = assem.GetType(typeName, true, false) as RuntimeType; m_memberName = info.GetString("Name"); m_signature = info.GetString("Signature"); // Only v4.0 and later generates and consumes Signature2 m_signature2 = (string)info.GetValueNoThrow("Signature2", typeof(string)); m_memberType = (MemberTypes)info.GetInt32("MemberType"); m_info = info; } #endregion #region ISerializable public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Method)); } #endregion #region IObjectReference public virtual Object GetRealObject(StreamingContext context) { if (m_memberName == null || m_reflectedType == null || m_memberType == 0) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_InsufficientState)); BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.OptionalParamBinding; switch (m_memberType) { #region case MemberTypes.Field: case MemberTypes.Field: { FieldInfo[] fields = m_reflectedType.GetMember(m_memberName, MemberTypes.Field, bindingFlags) as FieldInfo[]; if (fields.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); return fields[0]; } #endregion #region case MemberTypes.Event: case MemberTypes.Event: { EventInfo[] events = m_reflectedType.GetMember(m_memberName, MemberTypes.Event, bindingFlags) as EventInfo[]; if (events.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); return events[0]; } #endregion #region case MemberTypes.Property: case MemberTypes.Property: { PropertyInfo[] properties = m_reflectedType.GetMember(m_memberName, MemberTypes.Property, bindingFlags) as PropertyInfo[]; if (properties.Length == 0) throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName)); if (properties.Length == 1) return properties[0]; if (properties.Length > 1) { for (int i = 0; i < properties.Length; i++) { if (m_signature2 != null) { if (((RuntimePropertyInfo)properties[i]).SerializationToString().Equals(m_signature2)) return properties[i]; } else { if ((properties[i]).ToString().Equals(m_signature)) return properties[i]; } } } throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); } #endregion #region case MemberTypes.Constructor: case MemberTypes.Constructor: { if (m_signature == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature)); ConstructorInfo[] constructors = m_reflectedType.GetMember(m_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[]; if (constructors.Length == 1) return constructors[0]; if (constructors.Length > 1) { for (int i = 0; i < constructors.Length; i++) { if (m_signature2 != null) { if (((RuntimeConstructorInfo)constructors[i]).SerializationToString().Equals(m_signature2)) return constructors[i]; } else { if (constructors[i].ToString().Equals(m_signature)) return constructors[i]; } } } throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); } #endregion #region case MemberTypes.Method: case MemberTypes.Method: { MethodInfo methodInfo = null; if (m_signature == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature)); Type[] genericArguments = m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[]; MethodInfo[] methods = m_reflectedType.GetMember(m_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[]; if (methods.Length == 1) methodInfo = methods[0]; else if (methods.Length > 1) { for (int i = 0; i < methods.Length; i++) { if (m_signature2 != null) { if (((RuntimeMethodInfo)methods[i]).SerializationToString().Equals(m_signature2)) { methodInfo = methods[i]; break; } } else { if (methods[i].ToString().Equals(m_signature)) { methodInfo = methods[i]; break; } } // Handle generic methods specially since the signature match above probably won't work (the candidate // method info hasn't been instantiated). If our target method is generic as well we can skip this. if (genericArguments != null && methods[i].IsGenericMethod) { if (methods[i].GetGenericArguments().Length == genericArguments.Length) { MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments); if (m_signature2 != null) { if (((RuntimeMethodInfo)candidateMethod).SerializationToString().Equals(m_signature2)) { methodInfo = candidateMethod; break; } } else { if (candidateMethod.ToString().Equals(m_signature)) { methodInfo = candidateMethod; break; } } } } } } if (methodInfo == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName)); if (!methodInfo.IsGenericMethodDefinition) return methodInfo; if (genericArguments == null) return methodInfo; if (genericArguments[0] == null) return null; return methodInfo.MakeGenericMethod(genericArguments); } #endregion default: throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized")); } } #endregion } }
// // XmlDsigC14NWithCommentsTransformTest.cs // - Test Cases for XmlDsigC14NWithCommentsTransform // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Xml; using System.Xml.Resolvers; using Xunit; namespace System.Security.Cryptography.Xml.Tests { // Note: GetInnerXml is protected in XmlDsigC14NWithCommentsTransform // making it difficult to test properly. This class "open it up" :-) public class UnprotectedXmlDsigC14NWithCommentsTransform : XmlDsigC14NWithCommentsTransform { public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDsigC14NWithCommentsTransformTest { [Fact] public void Constructor() { XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform(); Assert.Null(xmlDsigC14NWithCommentsTransform.Context); Assert.Equal("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments", xmlDsigC14NWithCommentsTransform.Algorithm); Assert.Equal(new[] { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }, xmlDsigC14NWithCommentsTransform.InputTypes); Assert.Equal(new[] { typeof(Stream) }, xmlDsigC14NWithCommentsTransform.OutputTypes); } [Fact] public void GetInnerXml() { UnprotectedXmlDsigC14NWithCommentsTransform transform = new UnprotectedXmlDsigC14NWithCommentsTransform(); XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Null(xnl); } [Theory] [InlineData("")] [InlineData(new byte[] { 0xBA, 0xD })] public void LoadInput_UnsupportedType(object input) { XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform(); Assert.Throws<ArgumentException>(() => xmlDsigC14NWithCommentsTransform.LoadInput(input)); } [Theory] [InlineData(typeof(XmlDocument))] [InlineData(typeof(XmlNodeList))] public void GetOutput_UnsupportedType(Type type) { XmlDsigC14NWithCommentsTransform xmlDsigC14NWithCommentsTransform = new XmlDsigC14NWithCommentsTransform(); Assert.Throws<ArgumentException>(() => xmlDsigC14NWithCommentsTransform.GetOutput(type)); } [Fact] public void C14NSpecExample1() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("world.dtd"), ""); string res = TestHelpers.ExecuteTransform(C14NSpecExample1Input, new XmlDsigC14NWithCommentsTransform(), Encoding.UTF8, resolver); Assert.Equal(C14NSpecExample1Output, res); } [Theory] [InlineData(C14NSpecExample2Input, C14NSpecExample2Output)] [InlineData(C14NSpecExample3Input, C14NSpecExample3Output)] [InlineData(C14NSpecExample4Input, C14NSpecExample4Output)] public void C14NSpecExample(string input, string expectedOutput) { Assert.Equal(expectedOutput, ExecuteXmlDSigC14NTransform(input)); } [Fact] public void C14NSpecExample5() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.txt"), "world"); string input = C14NSpecExample5Input; string result = ExecuteXmlDSigC14NTransform(input, Encoding.UTF8, resolver); string expectedResult = C14NSpecExample5Output; Assert.Equal(expectedResult, result); } [Fact] public void C14NSpecExample6() { string res = ExecuteXmlDSigC14NTransform(C14NSpecExample6Input, Encoding.GetEncoding("ISO-8859-1")); Assert.Equal(C14NSpecExample6Output, res); } private string ExecuteXmlDSigC14NTransform(string inputXml, Encoding encoding = null, XmlResolver resolver = null) { XmlDocument doc = new XmlDocument(); doc.XmlResolver = resolver; doc.PreserveWhitespace = true; doc.LoadXml(inputXml); Encoding actualEncoding = encoding ?? Encoding.UTF8; byte[] data = actualEncoding.GetBytes(inputXml); using (Stream stream = new MemoryStream(data)) using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings { ValidationType = ValidationType.None, DtdProcessing = DtdProcessing.Parse, XmlResolver = resolver })) { doc.Load(reader); XmlDsigC14NWithCommentsTransform transform = new XmlDsigC14NWithCommentsTransform(); transform.LoadInput(doc); return TestHelpers.StreamToString((Stream) transform.GetOutput(), actualEncoding); } } // // Example 1 from C14N spec - PIs, Comments, and Outside of Document Element: // http://www.w3.org/TR/xml-c14n#Example-OutsideDoc // static string C14NSpecExample1Input => "<?xml version=\"1.0\"?>\n" + "\n" + "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "\n" + "<!DOCTYPE doc SYSTEM \"world.dtd\">\n" + "\n" + "<doc>Hello, world!<!-- Comment 1 --></doc>\n" + "\n" + "<?pi-without-data ?>\n\n" + "<!-- Comment 2 -->\n\n" + "<!-- Comment 3 -->\n"; static string C14NSpecExample1Output => "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "<doc>Hello, world!<!-- Comment 1 --></doc>\n" + "<?pi-without-data?>\n" + "<!-- Comment 2 -->\n" + "<!-- Comment 3 -->"; // // Example 2 from C14N spec - Whitespace in Document Content: // http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent // const string C14NSpecExample2Input = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>\n"; const string C14NSpecExample2Output = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>"; // // Example 3 from C14N spec - Start and End Tags: // http://www.w3.org/TR/xml-c14n#Example-SETags // const string C14NSpecExample3Input = "<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" + "<doc>\n" + " <e1 />\n" + " <e2 ></e2>\n" + " <e3 name = \"elem3\" id=\"elem3\" />\n" + " <e4 name=\"elem4\" id=\"elem4\" ></e4>\n" + " <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" + " xmlns:b=\"http://www.ietf.org\" \n" + " xmlns:a=\"http://www.w3.org\"\n" + " xmlns=\"http://www.uvic.ca\"/>\n" + " <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>\n"; const string C14NSpecExample3Output = "<doc>\n" + " <e1></e1>\n" + " <e2></e2>\n" + " <e3 id=\"elem3\" name=\"elem3\"></e3>\n" + " <e4 id=\"elem4\" name=\"elem4\"></e4>\n" + " <e5 xmlns=\"http://www.uvic.ca\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" + " <e6 xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\">\n" + " <e9 xmlns:a=\"http://www.ietf.org\" attr=\"default\"></e9>\n" + // " <e9 xmlns:a=\"http://www.ietf.org\"></e9>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>"; // // Example 4 from C14N spec - Character Modifications and Character References: // http://www.w3.org/TR/xml-c14n#Example-Chars // // Aleksey: // This test does not include "normId" element // because it has an invalid ID attribute "id" which // should be normalized by XML parser. Currently Mono // does not support this (see comment after this example // in the spec). const string C14NSpecExample4Input = "<!DOCTYPE doc [<!ATTLIST normId id ID #IMPLIED>]>\n" + "<doc>\n" + " <text>First line&#x0d;&#10;Second line</text>\n" + " <value>&#x32;</value>\n" + " <compute><![CDATA[value>\"0\" && value<\"10\" ?\"valid\":\"error\"]]></compute>\n" + " <compute expr=\'value>\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"\'>valid</compute>\n" + " <norm attr=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + // " <normId id=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + "</doc>\n"; const string C14NSpecExample4Output = "<doc>\n" + " <text>First line&#xD;\n" + "Second line</text>\n" + " <value>2</value>\n" + " <compute>value&gt;\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"</compute>\n" + " <compute expr=\"value>&quot;0&quot; &amp;&amp; value&lt;&quot;10&quot; ?&quot;valid&quot;:&quot;error&quot;\">valid</compute>\n" + " <norm attr=\" \' &#xD;&#xA;&#x9; \' \"></norm>\n" + // " <normId id=\"\' &#xD;&#xA;&#x9; \'\"></normId>\n" + "</doc>"; // // Example 5 from C14N spec - Entity References: // http://www.w3.org/TR/xml-c14n#Example-Entities // static string C14NSpecExample5Input => "<!DOCTYPE doc [\n" + "<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" + "<!ENTITY ent1 \"Hello\">\n" + $"<!ENTITY ent2 SYSTEM \"doc.txt\">\n" + "<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" + "<!NOTATION gif SYSTEM \"viewgif.exe\">\n" + "]>\n" + "<doc attrExtEnt=\"entExt\">\n" + " &ent1;, &ent2;!\n" + "</doc>\n" + "\n" + $"<!-- Let doc.txt contain \"world\" (excluding the quotes) -->\n"; static string C14NSpecExample5Output => "<doc attrExtEnt=\"entExt\">\n" + " Hello, world!\n" + "</doc>\n" + $"<!-- Let doc.txt contain \"world\" (excluding the quotes) -->"; // // Example 6 from C14N spec - UTF-8 Encoding: // http://www.w3.org/TR/xml-c14n#Example-UTF8 // static string C14NSpecExample6Input = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + "<doc>&#169;</doc>\n"; static string C14NSpecExample6Output = "<doc>\xC2\xA9</doc>"; } }
// 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.ServiceBus { 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> /// Operations operations. /// </summary> internal partial class Operations : IServiceOperations<ServiceBusManagementClient>, IOperations { /// <summary> /// Initializes a new instance of the Operations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal Operations(ServiceBusManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ServiceBusManagementClient /// </summary> public ServiceBusManagementClient Client { get; private set; } /// <summary> /// Lists all of the available ServiceBus REST API operations. /// </summary> /// <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<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.ServiceBus/operations").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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<Operation>>(); _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<Operation>>(_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> /// Lists all of the available ServiceBus REST API operations. /// </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<Operation>>> 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<Operation>>(); _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<Operation>>(_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; } } }
using System; using System.IO; using System.Runtime.CompilerServices; using BTDB.Buffer; using BTDB.StreamLayer; namespace BTDB.EventStoreLayer; public class ReadOnlyEventStore : IReadEventStore { protected IEventFileStorage File; protected readonly ITypeSerializersMapping Mapping; protected readonly ICompressionStrategy CompressionStrategy; protected ulong NextReadPosition; const int FirstReadAhead = 4096; protected const int HeaderSize = 8; protected const uint SectorSize = 512; protected const ulong SectorMask = ~(ulong)(SectorSize - 1); protected const uint SectorMaskUInt = (uint)(SectorMask & uint.MaxValue); protected ulong EndBufferPosition; protected readonly byte[] EndBuffer = new byte[SectorSize]; protected uint EndBufferLen; protected readonly uint MaxBlockSize; bool _knownAsCorrupted; internal bool KnownAsFinished; protected WeakReference<byte[]> ReadBufferWeakReference = new WeakReference<byte[]>(null); public ReadOnlyEventStore(IEventFileStorage file, ITypeSerializersMapping mapping, ICompressionStrategy compressionStrategy) { File = file; Mapping = mapping; CompressionStrategy = compressionStrategy; EndBufferPosition = ulong.MaxValue; MaxBlockSize = Math.Min(File.MaxBlockSize, 0x1000000); // For Length there is only 3 bytes so maximum could be less if (MaxBlockSize < FirstReadAhead) throw new ArgumentException("file.MaxBlockSize is less than FirstReadAhead"); } public void ReadFromStartToEnd(IEventStoreObserver observer) { NextReadPosition = 0; ReadToEnd(observer); } internal byte[] GetReadBuffer() { byte[] res; if (ReadBufferWeakReference.TryGetTarget(out res)) return res; res = new byte[FirstReadAhead + MaxBlockSize]; ReadBufferWeakReference.SetTarget(res); return res; } public void ReadToEnd(IEventStoreObserver observer) { var overflowWriter = default(SpanWriter); var wasFirstBlock = false; var bufferBlock = GetReadBuffer(); var bufferStartPosition = NextReadPosition & SectorMask; var bufferFullLength = 0; var bufferReadOffset = (int)(NextReadPosition - bufferStartPosition); var currentReadAhead = FirstReadAhead; var buf = ByteBuffer.NewSync(bufferBlock, bufferFullLength, currentReadAhead); var bufReadLength = (int)File.Read(buf, bufferStartPosition); bufferFullLength = bufReadLength; while (true) { if (bufferStartPosition + (ulong)bufferReadOffset + HeaderSize > File.MaxFileSize) { KnownAsFinished = true; return; } if (bufferReadOffset == bufferFullLength) { break; } if (bufferReadOffset + HeaderSize > bufferFullLength) { for (var i = bufferReadOffset; i < bufferFullLength; i++) { if (bufferBlock[i] != 0) { SetCorrupted(); return; } } break; } var blockCheckSum = PackUnpack.UnpackUInt32LE(bufferBlock, bufferReadOffset); bufferReadOffset += 4; var blockLen = PackUnpack.UnpackUInt32LE(bufferBlock, bufferReadOffset); if (blockCheckSum == 0 && blockLen == 0) { bufferReadOffset -= 4; break; } var blockType = (BlockType)(blockLen & 0xff); blockLen >>= 8; if (blockType == BlockType.LastBlock && blockLen == 0) { if (Checksum.CalcFletcher32(bufferBlock, (uint)bufferReadOffset, 4) != blockCheckSum) { SetCorrupted(); return; } KnownAsFinished = true; return; } if (blockLen == 0 && blockType != (BlockType.FirstBlock | BlockType.LastBlock)) { SetCorrupted(); return; } if (blockLen + HeaderSize > MaxBlockSize) { SetCorrupted(); return; } bufferReadOffset += 4; var bufferLenToFill = (uint)(bufferReadOffset + (int)blockLen + FirstReadAhead) & SectorMaskUInt; if (bufferLenToFill > bufferBlock.Length) bufferLenToFill = (uint)bufferBlock.Length; buf = ByteBuffer.NewSync(bufferBlock, bufferFullLength, (int)(bufferLenToFill - bufferFullLength)); if (buf.Length > 0) { bufferLenToFill = (uint)(bufferReadOffset + (int)blockLen + currentReadAhead) & SectorMaskUInt; if (bufferLenToFill > bufferBlock.Length) bufferLenToFill = (uint)bufferBlock.Length; if (bufferStartPosition + bufferLenToFill > File.MaxFileSize) { bufferLenToFill = (uint)(File.MaxFileSize - bufferStartPosition); } buf = ByteBuffer.NewSync(bufferBlock, bufferFullLength, (int)(bufferLenToFill - bufferFullLength)); if (buf.Length > 0) { if (currentReadAhead * 4 < MaxBlockSize) { currentReadAhead = currentReadAhead * 2; } bufReadLength = (int)File.Read(buf, bufferStartPosition + (ulong)bufferFullLength); bufferFullLength += bufReadLength; } } if (bufferReadOffset + (int)blockLen > bufferFullLength) { SetCorrupted(); return; } if (Checksum.CalcFletcher32(bufferBlock, (uint)bufferReadOffset - 4, blockLen + 4) != blockCheckSum) { SetCorrupted(); return; } var blockTypeBlock = blockType & (BlockType.FirstBlock | BlockType.MiddleBlock | BlockType.LastBlock); var stopReadingRequested = false; if (blockTypeBlock == (BlockType.FirstBlock | BlockType.LastBlock)) { stopReadingRequested = Process(blockType, bufferBlock.AsSpan(bufferReadOffset, (int)blockLen), observer); } else { if (blockTypeBlock == BlockType.FirstBlock) { overflowWriter.Reset(); wasFirstBlock = true; } else if (blockTypeBlock == BlockType.MiddleBlock || blockTypeBlock == BlockType.LastBlock) { if (!wasFirstBlock) { SetCorrupted(); return; } } else { SetCorrupted(); return; } overflowWriter.WriteBlock(bufferBlock.AsSpan(bufferReadOffset, (int)blockLen)); if (blockTypeBlock == BlockType.LastBlock) { stopReadingRequested = Process(blockType, overflowWriter.GetSpan(), observer); overflowWriter.Reset(); wasFirstBlock = false; } } bufferReadOffset += (int)blockLen; if (!wasFirstBlock) NextReadPosition = bufferStartPosition + (ulong)bufferReadOffset; if (stopReadingRequested) { return; } var nextBufferStartPosition = (bufferStartPosition + (ulong)bufferReadOffset) & SectorMask; var bufferMoveDistance = (int)(nextBufferStartPosition - bufferStartPosition); if (bufferMoveDistance <= 0) continue; Array.Copy(bufferBlock, bufferMoveDistance, bufferBlock, 0, bufferFullLength - bufferMoveDistance); bufferStartPosition = nextBufferStartPosition; bufferFullLength -= bufferMoveDistance; bufferReadOffset -= bufferMoveDistance; } if (wasFirstBlock) { // It is not corrupted here just unfinished, but definitely not appendable EndBufferPosition = ulong.MaxValue; return; } EndBufferLen = (uint)(bufferReadOffset - (bufferReadOffset & SectorMaskUInt)); EndBufferPosition = bufferStartPosition + (ulong)bufferReadOffset - EndBufferLen; Array.Copy(bufferBlock, bufferReadOffset - EndBufferLen, EndBuffer, 0, EndBufferLen); } public bool IsKnownAsCorrupted() { return _knownAsCorrupted; } public bool IsKnownAsFinished() { return KnownAsFinished; } public bool IsKnownAsAppendable() { return EndBufferPosition != ulong.MaxValue; } bool Process(BlockType blockType, ReadOnlySpan<byte> block, IEventStoreObserver observer) { if ((blockType & BlockType.Compressed) != 0) { CompressionStrategy.Decompress(ref block); } var reader = new SpanReader(block); if ((blockType & BlockType.HasTypeDeclaration) != 0) { Mapping.LoadTypeDescriptors(ref reader); } var metadata = (blockType & BlockType.HasMetadata) != 0 ? Mapping.LoadObject(ref reader) : null; uint eventCount; if ((blockType & BlockType.HasOneEvent) != 0) { eventCount = 1; } else if ((blockType & BlockType.HasMoreEvents) != 0) { eventCount = reader.ReadVUInt32(); } else { eventCount = 0; } var readEvents = observer.ObservedMetadata(metadata, eventCount); if (!readEvents) return observer.ShouldStopReadingNextEvents(); var events = new object[eventCount]; var successfulEventCount = 0; for (var i = 0; i < eventCount; i++) { var ev = Mapping.LoadObject(ref reader); if (ev == null) continue; events[successfulEventCount] = ev; successfulEventCount++; } if (eventCount != successfulEventCount) { Array.Resize(ref events, successfulEventCount); } observer.ObservedEvents(events); return observer.ShouldStopReadingNextEvents(); } void SetCorrupted([CallerLineNumber] int sourceLineNumber = 0) { _knownAsCorrupted = true; EndBufferPosition = ulong.MaxValue; throw new InvalidDataException($"EventStore is corrupted (detailed line number {sourceLineNumber})"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System.Diagnostics; using System.Collections.Generic; /* * This class describes an attribute type and potential values. * This encapsulates the information for one Attdef * in an * Attlist in a DTD as described below: */ internal sealed class SchemaAttDef : SchemaDeclBase, IDtdDefaultAttributeInfo { internal enum Reserve { None, XmlSpace, XmlLang }; private String _defExpanded; // default value in its expanded form private int _lineNum; private int _linePos; private int _valueLineNum; private int _valueLinePos; private Reserve _reserved = Reserve.None; // indicate the attribute type, such as xml:lang or xml:space private bool _defaultValueChecked; private XmlSchemaAttribute _schemaAttribute; public static readonly SchemaAttDef Empty = new SchemaAttDef(); // // Constructors // public SchemaAttDef(XmlQualifiedName name, String prefix) : base(name, prefix) { } public SchemaAttDef(XmlQualifiedName name) : base(name, null) { } private SchemaAttDef() { } // // IDtdAttributeInfo interface // #region IDtdAttributeInfo Members string IDtdAttributeInfo.Prefix { get { return ((SchemaAttDef)this).Prefix; } } string IDtdAttributeInfo.LocalName { get { return ((SchemaAttDef)this).Name.Name; } } int IDtdAttributeInfo.LineNumber { get { return ((SchemaAttDef)this).LineNumber; } } int IDtdAttributeInfo.LinePosition { get { return ((SchemaAttDef)this).LinePosition; } } bool IDtdAttributeInfo.IsNonCDataType { get { return this.TokenizedType != XmlTokenizedType.CDATA; } } bool IDtdAttributeInfo.IsDeclaredInExternal { get { return ((SchemaAttDef)this).IsDeclaredInExternal; } } bool IDtdAttributeInfo.IsXmlAttribute { get { return this.Reserved != SchemaAttDef.Reserve.None; } } #endregion // // IDtdDefaultAttributeInfo interface // #region IDtdDefaultAttributeInfo Members string IDtdDefaultAttributeInfo.DefaultValueExpanded { get { return ((SchemaAttDef)this).DefaultValueExpanded; } } object IDtdDefaultAttributeInfo.DefaultValueTyped { get { return ((SchemaAttDef)this).DefaultValueTyped; } } int IDtdDefaultAttributeInfo.ValueLineNumber { get { return ((SchemaAttDef)this).ValueLineNumber; } } int IDtdDefaultAttributeInfo.ValueLinePosition { get { return ((SchemaAttDef)this).ValueLinePosition; } } #endregion // // Internal properties // internal int LinePosition { get { return _linePos; } set { _linePos = value; } } internal int LineNumber { get { return _lineNum; } set { _lineNum = value; } } internal int ValueLinePosition { get { return _valueLinePos; } set { _valueLinePos = value; } } internal int ValueLineNumber { get { return _valueLineNum; } set { _valueLineNum = value; } } internal String DefaultValueExpanded { get { return (_defExpanded != null) ? _defExpanded : String.Empty; } set { _defExpanded = value; } } internal XmlTokenizedType TokenizedType { get { return Datatype.TokenizedType; } set { this.Datatype = XmlSchemaDatatype.FromXmlTokenizedType(value); } } internal Reserve Reserved { get { return _reserved; } set { _reserved = value; } } internal bool DefaultValueChecked { get { return _defaultValueChecked; } } internal XmlSchemaAttribute SchemaAttribute { get { return _schemaAttribute; } set { _schemaAttribute = value; } } internal void CheckXmlSpace(IValidationEventHandling validationEventHandling) { if (datatype.TokenizedType == XmlTokenizedType.ENUMERATION && (values != null) && (values.Count <= 2)) { String s1 = values[0].ToString(); if (values.Count == 2) { String s2 = values[1].ToString(); if ((s1 == "default" || s2 == "default") && (s1 == "preserve" || s2 == "preserve")) { return; } } else { if (s1 == "default" || s1 == "preserve") { return; } } } validationEventHandling.SendEvent(new XmlSchemaException(SR.Sch_XmlSpace, string.Empty), XmlSeverityType.Error); } internal SchemaAttDef Clone() { return (SchemaAttDef)MemberwiseClone(); } } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; namespace Xamarin { internal abstract class ExpressionVisitor { public virtual Expression Visit (Expression expression) { if (expression == null) throw new ArgumentNullException ("expression"); switch (expression.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: return VisitUnary ((UnaryExpression)expression); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.Power: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return VisitBinary ((BinaryExpression)expression); case ExpressionType.TypeIs: return VisitTypeIs ((TypeBinaryExpression)expression); case ExpressionType.Conditional: return VisitConditional ((ConditionalExpression)expression); case ExpressionType.Constant: return VisitConstant ((ConstantExpression)expression); case ExpressionType.Parameter: return VisitParameter ((ParameterExpression)expression); case ExpressionType.MemberAccess: return VisitMemberAccess ((MemberExpression)expression); case ExpressionType.Call: return VisitMethodCall ((MethodCallExpression)expression); case ExpressionType.Lambda: return VisitLambda ((LambdaExpression) expression); case ExpressionType.New: return VisitNew ((NewExpression) expression); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return VisitNewArray ((NewArrayExpression)expression); case ExpressionType.Invoke: return VisitInvocation ((InvocationExpression)expression); default: throw new ArgumentException (string.Format ("Unhandled expression type: '{0}'", expression.NodeType)); } } protected virtual MemberBinding VisitBinding (MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment ((MemberAssignment)binding); default: throw new ArgumentException (string.Format ("Unhandled binding type '{0}'", binding.BindingType)); } } protected virtual ElementInit VisitElementInitializer (ElementInit initializer) { Expression[] args; if (VisitExpressionList (initializer.Arguments, out args)) return Expression.ElementInit (initializer.AddMethod, args); return initializer; } protected virtual Expression VisitUnary (UnaryExpression unary) { Expression e = Visit (unary.Operand); if (e != unary.Operand) return Expression.MakeUnary (unary.NodeType, e, unary.Type, unary.Method); return unary; } protected virtual Expression VisitBinary (BinaryExpression binary) { Expression left = Visit (binary.Left); Expression right = Visit (binary.Right); LambdaExpression conv = null; if (binary.Conversion != null) conv = (LambdaExpression)Visit (binary.Conversion); if (left != binary.Left || right != binary.Right || conv != binary.Conversion) return Expression.MakeBinary (binary.NodeType, left, right, binary.IsLiftedToNull, binary.Method, conv); return binary; } protected virtual Expression VisitTypeIs (TypeBinaryExpression type) { Expression e = Visit (type.Expression); if (e != type.Expression) return Expression.TypeIs (e, type.TypeOperand); return type; } protected virtual Expression VisitConstant (ConstantExpression constant) { return constant; } protected virtual Expression VisitConditional (ConditionalExpression conditional) { Expression test = Visit (conditional.Test); Expression ifTrue = Visit (conditional.IfTrue); Expression ifFalse = Visit (conditional.IfFalse); if (test != conditional.Test || ifTrue != conditional.IfTrue || ifFalse != conditional.IfFalse) return Expression.Condition (test, ifTrue, ifFalse); return conditional; } protected virtual Expression VisitParameter (ParameterExpression parameter) { return parameter; } protected virtual Expression VisitMemberAccess (MemberExpression member) { Expression e = Visit (member.Expression); if (e != member.Expression) return Expression.MakeMemberAccess (e, member.Member); return member; } protected bool VisitExpressionList (IEnumerable<Expression> expressions, out Expression[] newExpressions) { Expression[] args = expressions.ToArray(); newExpressions = new Expression[args.Length]; bool changed = false; for (int i = 0; i < args.Length; ++i) { Expression original = args[i]; Expression current = Visit (original); newExpressions[i] = current; if (original != current) changed = true; } return changed; } protected virtual Expression VisitMethodCall (MethodCallExpression methodCall) { bool changed = false; Expression obj = null; if (methodCall.Object != null) { obj = Visit (methodCall.Object); changed = (obj != methodCall.Object); } Expression[] args; changed = VisitExpressionList (methodCall.Arguments, out args) || changed; if (changed) return Expression.Call (obj, methodCall.Method, args); return methodCall; } protected virtual MemberAssignment VisitMemberAssignment (MemberAssignment assignment) { Expression e = Visit (assignment.Expression); if (e != assignment.Expression) return Expression.Bind (assignment.Member, e); return assignment; } protected virtual Expression VisitLambda (LambdaExpression lambda) { Expression body = Visit (lambda.Body); bool changed = (body != lambda.Body); Expression[] parameters; changed = VisitExpressionList (lambda.Parameters.Cast<Expression>(), out parameters) || changed; if (changed) return Expression.Lambda (body, parameters.Cast<ParameterExpression>().ToArray()); return lambda; } protected virtual Expression VisitNew (NewExpression nex) { Expression[] args; if (VisitExpressionList (nex.Arguments, out args)) return Expression.New (nex.Constructor, args, nex.Members); return nex; } protected virtual Expression VisitNewArray (NewArrayExpression newArray) { Expression[] args; if (VisitExpressionList (newArray.Expressions, out args)) return Expression.NewArrayInit (newArray.Type, args); return newArray; } protected virtual Expression VisitInvocation (InvocationExpression invocation) { Expression[] args; bool changed = VisitExpressionList (invocation.Arguments, out args); Expression e = Visit (invocation.Expression); changed = (e != invocation.Expression) || changed; if (changed) return Expression.Invoke (e, args); return invocation; } } }
namespace AngleSharp.Css.Tests.Values { using AngleSharp.Css.Values; using NUnit.Framework; [TestFixture] public class ColorTests { [Test] public void ColorInvalidHexDigitString() { Color hc; var color = "BCDEFG"; var result = Color.TryFromHex(color, out hc); Assert.IsFalse(result); } [Test] public void ColorValidFourLetterString() { Color hc; var color = "abcd"; var result = Color.TryFromHex(color, out hc); Assert.AreEqual(new Color(170, 187, 204, 221), hc); Assert.IsTrue(result); } [Test] public void ColorInvalidLengthString() { Color hc; var color = "abcde"; var result = Color.TryFromHex(color, out hc); Assert.IsFalse(result); } [Test] public void ColorValidLengthShortString() { Color hc; var color = "fff"; var result = Color.TryFromHex(color, out hc); Assert.IsTrue(result); } [Test] public void ColorValidLengthLongString() { Color hc; var color = "fffabc"; var result = Color.TryFromHex(color, out hc); Assert.IsTrue(result); } [Test] public void ColorWhiteShortString() { var color = "fff"; var result = Color.FromHex(color); Assert.AreEqual(Color.FromRgb(255, 255, 255), result); } [Test] public void ColorRedShortString() { var color = "f00"; var result = Color.FromHex(color); Assert.AreEqual(Color.FromRgb(255, 0, 0), result); } [Test] public void ColorFromRedName() { var color = "red"; var result = Color.FromName(color); Assert.IsTrue(result.HasValue); Assert.AreEqual(Color.Red, result); } [Test] public void ColorFromWhiteName() { var color = "white"; var result = Color.FromName(color); Assert.IsTrue(result.HasValue); Assert.AreEqual(Color.White, result); } [Test] public void ColorFromUnknownName() { var color = "bla"; var result = Color.FromName(color); Assert.IsFalse(result.HasValue); } [Test] public void ColorMixedLongString() { var color = "facc36"; var result = Color.FromHex(color); Assert.AreEqual(Color.FromRgb(250, 204, 54), result); } [Test] public void ColorMixedEightDigitLongStringTransparent() { var color = "facc3600"; var result = Color.FromHex(color); Assert.AreEqual(Color.FromRgba(250, 204, 54, 0), result); } [Test] public void ColorMixedEightDigitLongStringOpaque() { var color = "facc36ff"; var result = Color.FromHex(color); Assert.AreEqual(Color.FromRgba(250, 204, 54, 1), result); } [Test] public void ColorMixBlackOnWhite50Percent() { var color1 = Color.Black; var color2 = Color.White; var mix = Color.Mix(0.5, color1, color2); Assert.AreEqual(Color.FromRgb(127, 127, 127), mix); } [Test] public void ColorMixRedOnWhite75Percent() { var color1 = Color.Red; var color2 = Color.White; var mix = Color.Mix(0.75, color1, color2); Assert.AreEqual(Color.FromRgb(255, 63, 63), mix); } [Test] public void ColorMixBlueOnWhite10Percent() { var color1 = Color.Blue; var color2 = Color.White; var mix = Color.Mix(0.1, color1, color2); Assert.AreEqual(Color.FromRgb(229, 229, 255), mix); } [Test] public void ColorMixGreenOnRed30Percent() { var color1 = Color.PureGreen; var color2 = Color.Red; var mix = Color.Mix(0.3, color1, color2); Assert.AreEqual(Color.FromRgb(178, 76, 0), mix); } [Test] public void ColorMixWhiteOnBlack20Percent() { var color1 = Color.White; var color2 = Color.Black; var mix = Color.Mix(0.2, color1, color2); Assert.AreEqual(Color.FromRgb(51, 51, 51), mix); } [Test] public void ColorHslBlackMixed() { var color = Color.FromHsl(0, 1, 0); Assert.AreEqual(Color.Black, color); } [Test] public void ColorHslBlackMixed1() { var color = Color.FromHsl(0, 1, 0); Assert.AreEqual(Color.Black, color); } [Test] public void ColorHslBlackMixed2() { var color = Color.FromHsl(0.5f, 1, 0); Assert.AreEqual(Color.Black, color); } [Test] public void ColorHslRedPure() { var color = Color.FromHsl(0, 1, 0.5f); Assert.AreEqual(Color.Red, color); } [Test] public void ColorHslGreenPure() { var color = Color.FromHsl(1f / 3f, 1, 0.5f); Assert.AreEqual(Color.PureGreen, color); } [Test] public void ColorHslBluePure() { var color = Color.FromHsl(2f / 3f, 1, 0.5f); Assert.AreEqual(Color.Blue, color); } [Test] public void ColorHslBlackPure() { var color = Color.FromHsl(0, 0, 0); Assert.AreEqual(Color.Black, color); } [Test] public void ColorHslMagentaPure() { var color = Color.FromHsl(300f / 360f, 1, 0.5f); Assert.AreEqual(Color.Magenta, color); } [Test] public void ColorHslYellowGreenMixed() { var color = Color.FromHsl(1f / 4f, 0.75f, 0.63f); Assert.AreEqual(Color.FromRgb(161, 232, 90), color); } [Test] public void ColorHslGrayBlueMixed() { var color = Color.FromHsl(210f / 360f, 0.25f, 0.25f); Assert.AreEqual(Color.FromRgb(48, 64, 80), color); } [Test] public void ColorFlexHexOneLetter() { var color = Color.FromFlexHex("F"); Assert.AreEqual(Color.FromRgb(0xf, 0x0, 0x0), color); } [Test] public void ColorFlexHexTwoLetters() { var color = Color.FromFlexHex("0F"); Assert.AreEqual(Color.FromRgb(0x0, 0xf, 0x0), color); } [Test] public void ColorFlexHexFourLetters() { var color = Color.FromFlexHex("0F0F"); Assert.AreEqual(Color.FromRgb(0xf, 0xf, 0x0), color); } [Test] public void ColorFlexHexSevenLetters() { var color = Color.FromFlexHex("0F0F0F0"); Assert.AreEqual(Color.FromRgb(0xf, 0xf0, 0x0), color); } [Test] public void ColorFlexHexFifteenLetters() { var color = Color.FromFlexHex("1234567890ABCDE"); Assert.AreEqual(Color.FromRgb(0x12, 0x67, 0xab), color); } [Test] public void ColorFlexHexExtremelyLong() { var color = Color.FromFlexHex("1234567890ABCDE1234567890ABCDE"); Assert.AreEqual(Color.FromRgb(0x34, 0xcd, 0x89), color); } [Test] public void ColorFlexHexRandomString() { var color = Color.FromFlexHex("6db6ec49efd278cd0bc92d1e5e072d68"); Assert.AreEqual(Color.FromRgb(0x6e, 0xcd, 0xe0), color); } [Test] public void ColorFlexHexSixLettersInvalid() { var color = Color.FromFlexHex("zqbttv"); Assert.AreEqual(Color.FromRgb(0x0, 0xb0, 0x0), color); } [Test] public void ColorFromGraySimple() { var color = Color.FromGray(25); Assert.AreEqual(Color.FromRgb(25, 25, 25), color); } [Test] public void ColorFromGrayWithAlpha() { var color = Color.FromGray(25, 0.5f); Assert.AreEqual(Color.FromRgba(25, 25, 25, 0.5f), color); } [Test] public void ColorFromGrayPercent() { var color = Color.FromGray(0.5f, 0.5f); Assert.AreEqual(Color.FromRgba(128, 128, 128, 0.5f), color); } [Test] public void ColorFromHwbRed() { var color = Color.FromHwb(0f, 0.2f, 0.2f); Assert.AreEqual(Color.FromRgb(204, 51, 51), color); } [Test] public void ColorFromHwbGreen() { var color = Color.FromHwb(1f / 3f, 0.2f, 0.6f); Assert.AreEqual(Color.FromRgb(51, 102, 51), color); } [Test] public void ColorFromHwbMagentaTransparent() { var color = Color.FromHwba(5f / 6f, 0.4f, 0.2f, 0.5f); Assert.AreEqual(Color.FromRgba(204, 102, 204, 0.5f), color); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.Windows.Threading; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; namespace Microsoft.PythonTools.EnvironmentsList { internal sealed partial class PipExtension : UserControl, ICanFocus { public static readonly ICommand InstallPackage = new RoutedCommand(); public static readonly ICommand UpgradePackage = new RoutedCommand(); public static readonly ICommand UninstallPackage = new RoutedCommand(); public static readonly ICommand InstallPip = new RoutedCommand(); public static readonly ICommand PipSecurityLearnMore = new RoutedCommand(); private readonly PipExtensionProvider _provider; private readonly Timer _focusTimer; public PipExtension(PipExtensionProvider provider) { _provider = provider; DataContextChanged += PackageExtension_DataContextChanged; _focusTimer = new Timer(FocusWaitExpired); InitializeComponent(); } void ICanFocus.Focus() { Dispatcher.BeginInvoke((Action)(() => { try { Focus(); if (SearchQueryText.IsVisible && SearchQueryText.IsEnabled) { Keyboard.Focus(SearchQueryText); } else { // Package manager may still be initializing itself // Search box is disabled if package manager is not ready if (!SearchQueryText.IsEnabled) { SearchQueryText.IsEnabledChanged += SearchQueryText_IsEnabledChanged; } if (!SearchQueryText.IsVisible) { SearchQueryText.IsVisibleChanged += SearchQueryText_IsVisibleChanged; } // It may never become ready/enabled, so don't wait for too long. _focusTimer.Change(1000, Timeout.Infinite); } } catch (Exception ex) when (!ex.IsCriticalException()) { } }), DispatcherPriority.Loaded); } private void FocusWaitExpired(object state) { // Waited long enough, the user might start clicking around soon, // so cancel focus operation. SearchQueryText.IsEnabledChanged -= SearchQueryText_IsEnabledChanged; SearchQueryText.IsVisibleChanged -= SearchQueryText_IsVisibleChanged; } private void SearchQueryText_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { SearchQueryText.IsVisibleChanged -= SearchQueryText_IsVisibleChanged; if (SearchQueryText.IsVisible && SearchQueryText.IsEnabled) { SearchQueryText.IsEnabledChanged -= SearchQueryText_IsEnabledChanged; Keyboard.Focus(SearchQueryText); _focusTimer.Change(Timeout.Infinite, Timeout.Infinite); } } private void SearchQueryText_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e) { SearchQueryText.IsEnabledChanged -= SearchQueryText_IsEnabledChanged; if (SearchQueryText.IsVisible && SearchQueryText.IsEnabled) { SearchQueryText.IsVisibleChanged -= SearchQueryText_IsVisibleChanged; Keyboard.Focus(SearchQueryText); _focusTimer.Change(Timeout.Infinite, Timeout.Infinite); } } private void PackageExtension_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var view = e.NewValue as EnvironmentView; if (view != null) { var current = Subcontext.DataContext as PipEnvironmentView; if (current == null || current.EnvironmentView != view) { if (current != null) { current.Dispose(); } Subcontext.DataContext = new PipEnvironmentView(view, _provider); } } } private void UninstallPackage_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as PipPackageView; e.CanExecute = _provider.CanExecute && view != null && _provider._packageManager.CanUninstall(view.Package); e.Handled = true; } private void UninstallPackage_Executed(object sender, ExecutedRoutedEventArgs e) { UninstallPackage_ExecutedAsync(sender, e).DoNotWait(); } private async Task UninstallPackage_ExecutedAsync(object sender, ExecutedRoutedEventArgs e) { try { var view = (PipPackageView)e.Parameter; await _provider.UninstallPackage(view.Package); } catch (OperationCanceledException) { } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(this, ExceptionDispatchInfo.Capture(ex)); } } private void UpgradePackage_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.Handled = true; if (!_provider.CanExecute) { e.CanExecute = false; return; } var view = e.Parameter as PipPackageView; if (view == null) { e.CanExecute = false; return; } e.CanExecute = !view.UpgradeVersion.IsEmpty && view.UpgradeVersion.CompareTo(view.Version) > 0; } private void UpgradePackage_Executed(object sender, ExecutedRoutedEventArgs e) { UpgradePackage_ExecutedAsync(sender, e).DoNotWait(); } private async Task UpgradePackage_ExecutedAsync(object sender, ExecutedRoutedEventArgs e) { try { var view = (PipPackageView)e.Parameter; // Construct a PackageSpec with the upgraded version. await _provider.InstallPackage(new PackageSpec(view.Package.Name, view.UpgradeVersion)); } catch (OperationCanceledException) { } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(this, ExceptionDispatchInfo.Capture(ex)); } } private void InstallPackage_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = _provider.CanExecute && !string.IsNullOrEmpty(e.Parameter as string) && (_provider.IsPipInstalled ?? false); e.Handled = true; } private void InstallPackage_Executed(object sender, ExecutedRoutedEventArgs e) { InstallPackage_ExecutedAsync(sender, e).DoNotWait(); } private async Task InstallPackage_ExecutedAsync(object sender, ExecutedRoutedEventArgs e) { try { await _provider.InstallPackage(new PackageSpec((string)e.Parameter)); } catch (OperationCanceledException) { } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(this, ExceptionDispatchInfo.Capture(ex)); } } private void PipSecurityLearnMore_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; e.Handled = true; } private void PipSecurityLearnMore_Executed(object sender, ExecutedRoutedEventArgs e) { Process.Start("https://go.microsoft.com/fwlink/?linkid=874576"); } private void InstallPip_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = _provider.CanExecute; e.Handled = true; } private void InstallPip_Executed(object sender, ExecutedRoutedEventArgs e) { InstallPip_ExecutedAsync(sender, e).DoNotWait(); } private async Task InstallPip_ExecutedAsync(object sender, ExecutedRoutedEventArgs e) { try { await _provider.InstallPip(); } catch (OperationCanceledException) { } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(this, ExceptionDispatchInfo.Capture(ex)); } } private void ForwardMouseWheel(object sender, MouseWheelEventArgs e) { PackagesList.RaiseEvent(new MouseWheelEventArgs( e.MouseDevice, e.Timestamp, e.Delta ) { RoutedEvent = UIElement.MouseWheelEvent }); e.Handled = true; } private void Delete_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var tb = e.OriginalSource as TextBox; if (tb != null) { e.Handled = true; e.CanExecute = !string.IsNullOrEmpty(tb.Text); return; } } private void Delete_Executed(object sender, ExecutedRoutedEventArgs e) { var tb = e.OriginalSource as TextBox; if (tb != null) { tb.Clear(); e.Handled = true; return; } } } sealed class PipEnvironmentView : DependencyObject, IDisposable { private readonly EnvironmentView _view; private readonly ObservableCollection<PipPackageView> _installed; private readonly List<PackageResultView> _installable; private readonly ObservableCollection<PackageResultView> _installableFiltered; private CollectionViewSource _installedView; private CollectionViewSource _installableView; private readonly Timer _installableViewRefreshTimer; internal readonly PipExtensionProvider _provider; private readonly InstallPackageView _installCommandView; private readonly FuzzyStringMatcher _matcher; internal PipEnvironmentView( EnvironmentView view, PipExtensionProvider provider ) { _view = view; _provider = provider; _provider.OperationStarted += PipExtensionProvider_UpdateStarted; _provider.OperationFinished += PipExtensionProvider_UpdateComplete; _provider.IsPipInstalledChanged += PipExtensionProvider_IsPipInstalledChanged; _provider.InstalledPackagesChanged += PipExtensionProvider_InstalledPackagesChanged; IsPipInstalled = _provider.IsPipInstalled ?? true; ShowSecurityWarning = provider._packageManager.UniqueKey == "pip" && view.Configuration.Version != new Version(2, 7) && view.Configuration.Version < new Version(3, 3); _installCommandView = new InstallPackageView(this); _matcher = new FuzzyStringMatcher(FuzzyMatchMode.FuzzyIgnoreCase); _installed = new ObservableCollection<PipPackageView>(); _installedView = new CollectionViewSource { Source = _installed }; _installedView.Filter += InstalledView_Filter; _installedView.View.CurrentChanged += InstalledView_CurrentChanged; _installable = new List<PackageResultView>(); _installableFiltered = new ObservableCollection<PackageResultView>(); _installableView = new CollectionViewSource { Source = _installableFiltered }; _installableView.View.CurrentChanged += InstallableView_CurrentChanged; _installableViewRefreshTimer = new Timer(InstallablePackages_Refresh); FinishInitialization().DoNotWait(); } private void PipExtensionProvider_IsPipInstalledChanged(object sender, EventArgs e) { PipExtensionProvider_IsPipInstalledChangedAsync(sender, e).DoNotWait(); } private async Task PipExtensionProvider_IsPipInstalledChangedAsync(object sender, EventArgs e) { await Dispatcher.InvokeAsync(() => { IsPipInstalled = _provider.IsPipInstalled ?? true; }); await RefreshPackages(); } private void InstalledView_CurrentChanged(object sender, EventArgs e) { if (_installedView.View.CurrentItem != null) { _installableView.View.MoveCurrentTo(null); } } private void InstallableView_CurrentChanged(object sender, EventArgs e) { if (_installableView.View.CurrentItem != null) { _installedView.View.MoveCurrentTo(null); } } private async Task FinishInitialization() { try { await RefreshPackages(); } catch (OperationCanceledException) { } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex)); } } public void Dispose() { _provider.OperationStarted -= PipExtensionProvider_UpdateStarted; _provider.OperationFinished -= PipExtensionProvider_UpdateComplete; _provider.IsPipInstalledChanged -= PipExtensionProvider_IsPipInstalledChanged; _provider.InstalledPackagesChanged -= PipExtensionProvider_InstalledPackagesChanged; _installableViewRefreshTimer.Dispose(); } public EnvironmentView EnvironmentView { get { return _view; } } public InstallPackageView InstallCommand { get { return _installCommandView; } } private void PipExtensionProvider_UpdateStarted(object sender, EventArgs e) { PipExtensionProvider_UpdateStartedAsync(sender, e).DoNotWait(); } private async Task PipExtensionProvider_UpdateStartedAsync(object sender, EventArgs e) { try { await Dispatcher.InvokeAsync(() => { IsListRefreshing = true; }); } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex)); } } private void PipExtensionProvider_UpdateComplete(object sender, EventArgs e) { PipExtensionProvider_UpdateCompleteAsync(sender, e).DoNotWait(); } private async Task PipExtensionProvider_UpdateCompleteAsync(object sender, EventArgs e) { try { await RefreshPackages(); } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex)); } } private void PipExtensionProvider_InstalledPackagesChanged(object sender, EventArgs e) { PipExtensionProvider_InstalledPackagesChangedAsync(sender, e).DoNotWait(); } private async Task PipExtensionProvider_InstalledPackagesChangedAsync(object sender, EventArgs e) { try { await RefreshPackages(); } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex)); } } public bool IsPipInstalled { get { return (bool)GetValue(IsPipInstalledProperty); } private set { SetValue(IsPipInstalledPropertyKey, value); } } private static readonly DependencyPropertyKey IsPipInstalledPropertyKey = DependencyProperty.RegisterReadOnly( "IsPipInstalled", typeof(bool), typeof(PipEnvironmentView), new PropertyMetadata(true) ); public static readonly DependencyProperty IsPipInstalledProperty = IsPipInstalledPropertyKey.DependencyProperty; public bool ShowSecurityWarning { get { return (bool)GetValue(ShowSecurityWarningProperty); } private set { SetValue(ShowSecurityWarningPropertyKey, value); } } private static readonly DependencyPropertyKey ShowSecurityWarningPropertyKey = DependencyProperty.RegisterReadOnly( "ShowSecurityWarning", typeof(bool), typeof(PipEnvironmentView), new PropertyMetadata(true) ); public static readonly DependencyProperty ShowSecurityWarningProperty = ShowSecurityWarningPropertyKey.DependencyProperty; public string SearchQuery { get { return (string)GetValue(SearchQueryProperty); } set { SetValue(SearchQueryProperty, value); } } public static readonly DependencyProperty SearchQueryProperty = DependencyProperty.Register( "SearchQuery", typeof(string), typeof(PipEnvironmentView), new PropertyMetadata(Filter_Changed) ); public string InstallPackageText { get { return (string)GetValue(InstallPackageTextProperty); } set { SetValue(InstallPackageTextProperty, value); } } public static readonly DependencyProperty InstallPackageTextProperty = DependencyProperty.Register( "InstallPackageText", typeof(string), typeof(PipEnvironmentView) ); public string SearchWatermark => _provider._packageManager.SearchHelpText; private static void Filter_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) { var view = d as PipEnvironmentView; if (view != null) { try { view._installedView.View.Refresh(); view._installableViewRefreshTimer.Change(500, Timeout.Infinite); view.InstallPackageText = view._provider._packageManager.GetInstallCommandDisplayName(view.SearchQuery); } catch (ObjectDisposedException) { } } } private void InstallablePackages_Refresh(object state) { InstallablePackages_RefreshAsync(state).DoNotWait(); } private async Task InstallablePackages_RefreshAsync(object state) { string query = null; try { query = await Dispatcher.InvokeAsync(() => SearchQuery); } catch (OperationCanceledException) { return; } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex)); } PackageResultView[] installable = null; lock (_installable) { if (_installable.Any() && !string.IsNullOrEmpty(query)) { installable = _installable .Select(p => Tuple.Create(_matcher.GetSortKey(p.Package.PackageSpec, query), p)) .Where(t => _matcher.IsCandidateMatch(t.Item2.Package.PackageSpec, query, t.Item1)) .OrderByDescending(t => t.Item1) .Select(t => t.Item2) .Take(20) .ToArray(); } } try { await Dispatcher.InvokeAsync(() => { if (installable != null && installable.Any()) { _installableFiltered.Merge(installable, PackageViewComparer.Instance, PackageViewComparer.Instance); } else { _installableFiltered.Clear(); } _installableView.View.Refresh(); }); } catch (OperationCanceledException) { } catch (Exception ex) when (!ex.IsCriticalException()) { ToolWindow.SendUnhandledException(_provider.WpfObject, ExceptionDispatchInfo.Capture(ex)); } } public ICollectionView InstalledPackages { get { if (EnvironmentView == null || EnvironmentView.Factory == null) { return null; } return _installedView.View; } } public ICollectionView InstallablePackages { get { if (EnvironmentView == null || EnvironmentView.Factory == null) { return null; } return _installableView.View; } } private void InstalledView_Filter(object sender, FilterEventArgs e) { PipPackageView package; PackageResultView result; var query = SearchQuery; var matcher = string.IsNullOrEmpty(query) ? null : _matcher; if ((package = e.Item as PipPackageView) != null) { e.Accepted = matcher == null || matcher.IsCandidateMatch(package.PackageSpec, query); } else if (e.Item is InstallPackageView) { e.Accepted = matcher != null; } else if ((result = e.Item as PackageResultView) != null) { e.Accepted = matcher != null && matcher.IsCandidateMatch(result.Package.PackageSpec, query); } } private async Task RefreshPackages() { bool isPipInstalled = true; await Dispatcher.InvokeAsync(() => { isPipInstalled = IsPipInstalled; IsListRefreshing = true; CommandManager.InvalidateRequerySuggested(); }); try { if (isPipInstalled) { await Task.WhenAll( RefreshInstalledPackages(), RefreshInstallablePackages() ); } } catch (OperationCanceledException) { // User has probably closed the window or is quitting VS } finally { Dispatcher.Invoke(() => { IsListRefreshing = false; CommandManager.InvalidateRequerySuggested(); }); } } private async Task RefreshInstalledPackages() { var installed = await _provider.GetInstalledPackagesAsync(); if (installed == null || !installed.Any()) { return; } await Dispatcher.InvokeAsync(() => { lock (_installed) { _installed.Merge(installed, PackageViewComparer.Instance, PackageViewComparer.Instance); } }); } private async Task RefreshInstallablePackages() { var installable = await _provider.GetAvailablePackagesAsync(); lock (_installable) { _installable.Clear(); _installable.AddRange(installable.Select(pv => new PackageResultView(this, pv))); } try { _installableViewRefreshTimer.Change(100, Timeout.Infinite); } catch (ObjectDisposedException) { } } public bool IsListRefreshing { get { return (bool)GetValue(IsListRefreshingProperty); } private set { SetValue(IsListRefreshingPropertyKey, value); } } private static readonly DependencyPropertyKey IsListRefreshingPropertyKey = DependencyProperty.RegisterReadOnly( "IsListRefreshing", typeof(bool), typeof(PipEnvironmentView), new PropertyMetadata(true, Filter_Changed) ); public static readonly DependencyProperty IsListRefreshingProperty = IsListRefreshingPropertyKey.DependencyProperty; } class PackageViewComparer : IEqualityComparer<PipPackageView>, IComparer<PipPackageView>, IEqualityComparer<PackageResultView>, IComparer<PackageResultView> { public static readonly PackageViewComparer Instance = new PackageViewComparer(); public bool Equals(PipPackageView x, PipPackageView y) { return StringComparer.OrdinalIgnoreCase.Equals(x.PackageSpec, y.PackageSpec); } public int GetHashCode(PipPackageView obj) { return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.PackageSpec); } public int Compare(PipPackageView x, PipPackageView y) { return StringComparer.OrdinalIgnoreCase.Compare(x.PackageSpec, y.PackageSpec); } public bool Equals(PackageResultView x, PackageResultView y) { return Equals(x.Package, y.Package); } public int GetHashCode(PackageResultView obj) { return StringComparer.OrdinalIgnoreCase.GetHashCode( obj.IndexName + ":" + obj.Package.PackageSpec ); } public int Compare(PackageResultView x, PackageResultView y) { return Compare(x.Package, y.Package); } } class InstallPackageView { public InstallPackageView(PipEnvironmentView view) { View = view; } public PipEnvironmentView View { get; } } class PackageResultView : INotifyPropertyChanged { public PackageResultView(PipEnvironmentView view, PipPackageView package) { View = view; Package = package; Package.PropertyChanged += Package_PropertyChanged; } private void Package_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "Description": case "DisplayName": PropertyChanged?.Invoke(this, e); break; } } public event PropertyChangedEventHandler PropertyChanged; public PipEnvironmentView View { get; } public PipPackageView Package { get; } public string PackageSpec => Package.PackageSpec; public string IndexName => View._provider.IndexName; public string DisplayName => Package.DisplayName; public string Description => Package.Description; } class UpgradeMessageConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values.Length != 2) { return Strings.UpgradeMessage; } var name = (string)values[0]; var version = (PackageVersion)values[1]; return Strings.UpgradeMessage_Package.FormatUI(name, version); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [ValueConversion(typeof(PipPackageView), typeof(string))] class UninstallMessageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var p = value as PipPackageView; if (p == null) { return Strings.UninstallMessage; } return Strings.UninstallMessage_Package.FormatUI(p.Name); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using ClosedXML.Excel; using ClosedXML.Excel.CalcEngine; using ClosedXML.Excel.CalcEngine.Exceptions; using NUnit.Framework; using System; using System.Globalization; using System.Threading; namespace ClosedXML_Tests.Excel.CalcEngine { [TestFixture] public class TextTests { [SetUp] public void Init() { // Make sure tests run on a deterministic culture Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); } [Test] public void Char_Empty_Input_String() { Assert.Throws<CellValueException>(() => XLWorkbook.EvaluateExpr(@"Char("""")")); } [Test] public void Char_Input_Too_Large() { Assert.Throws<CellValueException>(() => XLWorkbook.EvaluateExpr(@"Char(9797)")); } [Test] public void Char_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Char(97)"); Assert.AreEqual("a", actual); } [Test] public void Clean_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Clean("""")"); Assert.AreEqual("", actual); } [Test] public void Clean_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Clean(CHAR(9)&""Monthly report""&CHAR(10))"); Assert.AreEqual("Monthly report", actual); actual = XLWorkbook.EvaluateExpr(@"Clean("" "")"); Assert.AreEqual(" ", actual); } [Test] public void Code_Empty_Input_String() { // Todo: more specific exception - ValueException? Assert.That(() => XLWorkbook.EvaluateExpr(@"Code("""")"), Throws.TypeOf<IndexOutOfRangeException>()); } [Test] public void Code_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Code(""A"")"); Assert.AreEqual(65, actual); actual = XLWorkbook.EvaluateExpr(@"Code(""BCD"")"); Assert.AreEqual(66, actual); } [Test] public void Concat_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Concatenate(""ABC"", ""123"")"); Assert.AreEqual("ABC123", actual); actual = XLWorkbook.EvaluateExpr(@"Concatenate("""", ""123"")"); Assert.AreEqual("123", actual); } [Test] public void Dollar_Empty_Input_String() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Dollar("", 3)"), Throws.TypeOf<ExpressionParseException>()); } [Test] public void Dollar_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Dollar(123.54)"); Assert.AreEqual("$123.54", actual); actual = XLWorkbook.EvaluateExpr(@"Dollar(123.54, 3)"); Assert.AreEqual("$123.540", actual); } [Test] public void Exact_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Exact("""", """")"); Assert.AreEqual(true, actual); } [Test] public void Exact_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Exact(""asdf"", ""asdf"")"); Assert.AreEqual(true, actual); actual = XLWorkbook.EvaluateExpr(@"Exact(""asdf"", ""ASDF"")"); Assert.AreEqual(false, actual); actual = XLWorkbook.EvaluateExpr(@"Exact(123, 123)"); Assert.AreEqual(true, actual); actual = XLWorkbook.EvaluateExpr(@"Exact(321, 123)"); Assert.AreEqual(false, actual); } [Test] public void Find_Start_Position_Too_Large() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Find(""abc"", ""abcdef"", 10)"), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void Find_String_In_Another_Empty_String() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Find(""abc"", """")"), Throws.TypeOf<ArgumentException>()); } [Test] public void Find_String_Not_Found() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Find(""123"", ""asdf"")"), Throws.TypeOf<ArgumentException>()); } [Test] public void Find_Case_Sensitive_String_Not_Found() { // Find is case-sensitive Assert.That(() => XLWorkbook.EvaluateExpr(@"Find(""excel"", ""Microsoft Excel 2010"")"), Throws.TypeOf<ArgumentException>()); } [Test] public void Find_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Find(""Tuesday"", ""Today is Tuesday"")"); Assert.AreEqual(10, actual); actual = XLWorkbook.EvaluateExpr(@"Find("""", """")"); Assert.AreEqual(1, actual); actual = XLWorkbook.EvaluateExpr(@"Find("""", ""asdf"")"); Assert.AreEqual(1, actual); } [Test] public void Fixed_Input_Is_String() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Fixed(""asdf"")"), Throws.TypeOf<ApplicationException>()); } [Test] public void Fixed_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Fixed(17300.67, 4)"); Assert.AreEqual("17,300.6700", actual); actual = XLWorkbook.EvaluateExpr(@"Fixed(17300.67, 2, TRUE)"); Assert.AreEqual("17300.67", actual); actual = XLWorkbook.EvaluateExpr(@"Fixed(17300.67)"); Assert.AreEqual("17,300.67", actual); } [Test] public void Left_Bigger_Than_Length() { Object actual = XLWorkbook.EvaluateExpr(@"Left(""ABC"", 5)"); Assert.AreEqual("ABC", actual); } [Test] public void Left_Default() { Object actual = XLWorkbook.EvaluateExpr(@"Left(""ABC"")"); Assert.AreEqual("A", actual); } [Test] public void Left_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Left("""")"); Assert.AreEqual("", actual); } [Test] public void Left_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Left(""ABC"", 2)"); Assert.AreEqual("AB", actual); } [Test] public void Len_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Len("""")"); Assert.AreEqual(0, actual); } [Test] public void Len_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Len(""word"")"); Assert.AreEqual(4, actual); } [Test] public void Lower_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Lower("""")"); Assert.AreEqual("", actual); } [Test] public void Lower_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Lower(""AbCdEfG"")"); Assert.AreEqual("abcdefg", actual); } [Test] public void Mid_Bigger_Than_Length() { Object actual = XLWorkbook.EvaluateExpr(@"Mid(""ABC"", 1, 5)"); Assert.AreEqual("ABC", actual); } [Test] public void Mid_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Mid("""", 1, 1)"); Assert.AreEqual("", actual); } [Test] public void Mid_Start_After() { Object actual = XLWorkbook.EvaluateExpr(@"Mid(""ABC"", 5, 5)"); Assert.AreEqual("", actual); } [Test] public void Mid_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Mid(""ABC"", 2, 2)"); Assert.AreEqual("BC", actual); } [Test] public void Proper_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Proper("""")"); Assert.AreEqual("", actual); } [Test] public void Proper_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Proper(""my name is francois botha"")"); Assert.AreEqual("My Name Is Francois Botha", actual); } [Test] public void Replace_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Replace("""", 1, 1, ""newtext"")"); Assert.AreEqual("newtext", actual); } [Test] public void Replace_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Replace(""Here is some obsolete text to replace."", 14, 13, ""new text"")"); Assert.AreEqual("Here is some new text to replace.", actual); } [Test] public void Rept_Empty_Input_Strings() { Object actual = XLWorkbook.EvaluateExpr(@"Rept("""", 3)"); Assert.AreEqual("", actual); } [Test] public void Rept_Start_Is_Negative() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Rept(""Francois"", -1)"), Throws.TypeOf<IndexOutOfRangeException>()); } [Test] public void Rept_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Rept(""Francois Botha,"", 3)"); Assert.AreEqual("Francois Botha,Francois Botha,Francois Botha,", actual); actual = XLWorkbook.EvaluateExpr(@"Rept(""123"", 5/2)"); Assert.AreEqual("123123", actual); actual = XLWorkbook.EvaluateExpr(@"Rept(""Francois"", 0)"); Assert.AreEqual("", actual); } [Test] public void Right_Bigger_Than_Length() { Object actual = XLWorkbook.EvaluateExpr(@"Right(""ABC"", 5)"); Assert.AreEqual("ABC", actual); } [Test] public void Right_Default() { Object actual = XLWorkbook.EvaluateExpr(@"Right(""ABC"")"); Assert.AreEqual("C", actual); } [Test] public void Right_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Right("""")"); Assert.AreEqual("", actual); } [Test] public void Right_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Right(""ABC"", 2)"); Assert.AreEqual("BC", actual); } [Test] public void Search_No_Parameters_With_Values() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Search("""", """")"), Throws.TypeOf<ArgumentException>()); } [Test] public void Search_Empty_Search_String() { Object actual = XLWorkbook.EvaluateExpr(@"Search("""", ""asdf"")"); Assert.AreEqual(1, actual); } [Test] public void Search_Start_Position_Too_Large() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Search(""abc"", ""abcdef"", 10)"), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void Search_Empty_Input_String() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Search(""abc"", """")"), Throws.TypeOf<ArgumentException>()); } [Test] public void Search_String_Not_Found() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Search(""123"", ""asdf"")"), Throws.TypeOf<ArgumentException>()); } [Test] public void Search_Wildcard_String_Not_Found() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Search(""soft?2010"", ""Microsoft Excel 2010"")"), Throws.TypeOf<ArgumentException>()); } [Test] public void Search_Start_Position_Too_Large2() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Search(""text"", ""This is some text"", 15)"), Throws.TypeOf<ArgumentException>()); } // http://www.excel-easy.com/examples/find-vs-search.html [Test] public void Search_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Search(""Tuesday"", ""Today is Tuesday"")"); Assert.AreEqual(10, actual); // Find is case-INsensitive actual = XLWorkbook.EvaluateExpr(@"Search(""excel"", ""Microsoft Excel 2010"")"); Assert.AreEqual(11, actual); actual = XLWorkbook.EvaluateExpr(@"Search(""soft*2010"", ""Microsoft Excel 2010"")"); Assert.AreEqual(6, actual); actual = XLWorkbook.EvaluateExpr(@"Search(""Excel 20??"", ""Microsoft Excel 2010"")"); Assert.AreEqual(11, actual); actual = XLWorkbook.EvaluateExpr(@"Search(""text"", ""This is some text"", 14)"); Assert.AreEqual(14, actual); } [Test] public void Substitute_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Substitute(""This is a Tuesday."", ""Tuesday"", ""Monday"")"); Assert.AreEqual("This is a Monday.", actual); actual = XLWorkbook.EvaluateExpr(@"Substitute(""This is a Tuesday. Next week also has a Tuesday."", ""Tuesday"", ""Monday"", 1)"); Assert.AreEqual("This is a Monday. Next week also has a Tuesday.", actual); actual = XLWorkbook.EvaluateExpr(@"Substitute(""This is a Tuesday. Next week also has a Tuesday."", ""Tuesday"", ""Monday"", 2)"); Assert.AreEqual("This is a Tuesday. Next week also has a Monday.", actual); actual = XLWorkbook.EvaluateExpr(@"Substitute("""", """", ""Monday"")"); Assert.AreEqual("", actual); actual = XLWorkbook.EvaluateExpr(@"Substitute(""This is a Tuesday. Next week also has a Tuesday."", """", ""Monday"")"); Assert.AreEqual("This is a Tuesday. Next week also has a Tuesday.", actual); actual = XLWorkbook.EvaluateExpr(@"Substitute(""This is a Tuesday. Next week also has a Tuesday."", ""Tuesday"", """")"); Assert.AreEqual("This is a . Next week also has a .", actual); } [Test] public void T_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"T("""")"); Assert.AreEqual("", actual); } [Test] public void T_Value() { Object actual = XLWorkbook.EvaluateExpr(@"T(""asdf"")"); Assert.AreEqual("asdf", actual); actual = XLWorkbook.EvaluateExpr(@"T(Today())"); Assert.AreEqual("", actual); actual = XLWorkbook.EvaluateExpr(@"T(TRUE)"); Assert.AreEqual("", actual); } [Test] public void Text_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Text(1913415.93, """")"); Assert.AreEqual("", actual); } [Test] public void Text_Value() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Text(Date(2010, 1, 1), ""yyyy-MM-dd"")"); Assert.AreEqual("2010-01-01", actual); actual = XLWorkbook.EvaluateExpr(@"Text(1469.07, ""0,000,000.00"")"); Assert.AreEqual("0,001,469.07", actual); actual = XLWorkbook.EvaluateExpr(@"Text(1913415.93, ""#,000.00"")"); Assert.AreEqual("1,913,415.93", actual); actual = XLWorkbook.EvaluateExpr(@"Text(2800, ""$0.00"")"); Assert.AreEqual("$2800.00", actual); actual = XLWorkbook.EvaluateExpr(@"Text(0.4, ""0%"")"); Assert.AreEqual("40%", actual); actual = XLWorkbook.EvaluateExpr(@"Text(Date(2010, 1, 1), ""MMMM yyyy"")"); Assert.AreEqual("January 2010", actual); actual = XLWorkbook.EvaluateExpr(@"Text(Date(2010, 1, 1), ""M/d/y"")"); Assert.AreEqual("1/1/10", actual); } [Test] public void Text_String_Input() { Object actual = XLWorkbook.EvaluateExpr(@"TEXT(""211x"", ""#00"")"); Assert.AreEqual("211x", actual); } [TestCase(2020, 11, 1, 9, 23, 11, "m/d/yyyy h:mm:ss", "11/1/2020 9:23:11")] [TestCase(2023, 7, 14, 2, 12, 3, "m/d/yyyy h:mm:ss", "7/14/2023 2:12:03")] [TestCase(2025, 10, 14, 2, 48, 55, "m/d/yyyy h:mm:ss", "10/14/2025 2:48:55")] [TestCase(2023, 2, 19, 22, 1, 38, "m/d/yyyy h:mm:ss", "2/19/2023 22:01:38")] [TestCase(2025, 12, 19, 19, 43, 58, "m/d/yyyy h:mm:ss", "12/19/2025 19:43:58")] [TestCase(2034, 11, 16, 1, 48, 9, "m/d/yyyy h:mm:ss", "11/16/2034 1:48:09")] [TestCase(2018, 12, 10, 11, 22, 42, "m/d/yyyy h:mm:ss", "12/10/2018 11:22:42")] public void Text_DateFormats(int year, int months, int days, int hour, int minutes, int seconds, string format, string expected) { Assert.AreEqual(expected, XLWorkbook.EvaluateExpr($@"TEXT(DATE({year}, {months}, {days}) + TIME({hour}, {minutes}, {seconds}), ""{format}"")")); } [Test] public void Trim_EmptyInput_Striong() { Object actual = XLWorkbook.EvaluateExpr(@"Trim("""")"); Assert.AreEqual("", actual); } [Test] public void Trim_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Trim("" some text with padding "")"); Assert.AreEqual("some text with padding", actual); } [Test] public void Upper_Empty_Input_String() { Object actual = XLWorkbook.EvaluateExpr(@"Upper("""")"); Assert.AreEqual("", actual); } [Test] public void Upper_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Upper(""AbCdEfG"")"); Assert.AreEqual("ABCDEFG", actual); } [Test] public void Value_Input_String_Is_Not_A_Number() { Assert.That(() => XLWorkbook.EvaluateExpr(@"Value(""asdf"")"), Throws.TypeOf<FormatException>()); } [Test] public void Value_Value() { Object actual = XLWorkbook.EvaluateExpr(@"Value(""123.54"")"); Assert.AreEqual(123.54, actual); actual = XLWorkbook.EvaluateExpr(@"Value(654.32)"); Assert.AreEqual(654.32, actual); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Settings/Master/CameraSettings.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Settings.Master { /// <summary>Holder for reflection information generated from POGOProtos/Settings/Master/CameraSettings.proto</summary> public static partial class CameraSettingsReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Settings/Master/CameraSettings.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CameraSettingsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci9QT0dPUHJvdG9zL1NldHRpbmdzL01hc3Rlci9DYW1lcmFTZXR0aW5ncy5w", "cm90bxIaUE9HT1Byb3Rvcy5TZXR0aW5ncy5NYXN0ZXIaI1BPR09Qcm90b3Mv", "RW51bXMvQ2FtZXJhVGFyZ2V0LnByb3RvGipQT0dPUHJvdG9zL0VudW1zL0Nh", "bWVyYUludGVycG9sYXRpb24ucHJvdG8i1wMKDkNhbWVyYVNldHRpbmdzEhMK", "C25leHRfY2FtZXJhGAEgASgJEjwKDWludGVycG9sYXRpb24YAiADKA4yJS5Q", "T0dPUHJvdG9zLkVudW1zLkNhbWVyYUludGVycG9sYXRpb24SMwoLdGFyZ2V0", "X3R5cGUYAyADKA4yHi5QT0dPUHJvdG9zLkVudW1zLkNhbWVyYVRhcmdldBIV", "Cg1lYXNlX2luX3NwZWVkGAQgAygCEhYKDmVhc3Rfb3V0X3NwZWVkGAUgAygC", "EhgKEGR1cmF0aW9uX3NlY29uZHMYBiADKAISFAoMd2FpdF9zZWNvbmRzGAcg", "AygCEhoKEnRyYW5zaXRpb25fc2Vjb25kcxgIIAMoAhIUCgxhbmdsZV9kZWdy", "ZWUYCSADKAISGwoTYW5nbGVfb2Zmc2V0X2RlZ3JlZRgKIAMoAhIUCgxwaXRj", "aF9kZWdyZWUYCyADKAISGwoTcGl0Y2hfb2Zmc2V0X2RlZ3JlZRgMIAMoAhIT", "Cgtyb2xsX2RlZ3JlZRgNIAMoAhIXCg9kaXN0YW5jZV9tZXRlcnMYDiADKAIS", "FgoOaGVpZ2h0X3BlcmNlbnQYDyADKAISFgoOdmVydF9jdHJfcmF0aW8YECAD", "KAJiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Enums.CameraTargetReflection.Descriptor, global::POGOProtos.Enums.CameraInterpolationReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.Master.CameraSettings), global::POGOProtos.Settings.Master.CameraSettings.Parser, new[]{ "NextCamera", "Interpolation", "TargetType", "EaseInSpeed", "EastOutSpeed", "DurationSeconds", "WaitSeconds", "TransitionSeconds", "AngleDegree", "AngleOffsetDegree", "PitchDegree", "PitchOffsetDegree", "RollDegree", "DistanceMeters", "HeightPercent", "VertCtrRatio" }, null, null, null) })); } #endregion } #region Messages public sealed partial class CameraSettings : pb::IMessage<CameraSettings> { private static readonly pb::MessageParser<CameraSettings> _parser = new pb::MessageParser<CameraSettings>(() => new CameraSettings()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CameraSettings> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Settings.Master.CameraSettingsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraSettings() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraSettings(CameraSettings other) : this() { nextCamera_ = other.nextCamera_; interpolation_ = other.interpolation_.Clone(); targetType_ = other.targetType_.Clone(); easeInSpeed_ = other.easeInSpeed_.Clone(); eastOutSpeed_ = other.eastOutSpeed_.Clone(); durationSeconds_ = other.durationSeconds_.Clone(); waitSeconds_ = other.waitSeconds_.Clone(); transitionSeconds_ = other.transitionSeconds_.Clone(); angleDegree_ = other.angleDegree_.Clone(); angleOffsetDegree_ = other.angleOffsetDegree_.Clone(); pitchDegree_ = other.pitchDegree_.Clone(); pitchOffsetDegree_ = other.pitchOffsetDegree_.Clone(); rollDegree_ = other.rollDegree_.Clone(); distanceMeters_ = other.distanceMeters_.Clone(); heightPercent_ = other.heightPercent_.Clone(); vertCtrRatio_ = other.vertCtrRatio_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CameraSettings Clone() { return new CameraSettings(this); } /// <summary>Field number for the "next_camera" field.</summary> public const int NextCameraFieldNumber = 1; private string nextCamera_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string NextCamera { get { return nextCamera_; } set { nextCamera_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "interpolation" field.</summary> public const int InterpolationFieldNumber = 2; private static readonly pb::FieldCodec<global::POGOProtos.Enums.CameraInterpolation> _repeated_interpolation_codec = pb::FieldCodec.ForEnum(18, x => (int) x, x => (global::POGOProtos.Enums.CameraInterpolation) x); private readonly pbc::RepeatedField<global::POGOProtos.Enums.CameraInterpolation> interpolation_ = new pbc::RepeatedField<global::POGOProtos.Enums.CameraInterpolation>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::POGOProtos.Enums.CameraInterpolation> Interpolation { get { return interpolation_; } } /// <summary>Field number for the "target_type" field.</summary> public const int TargetTypeFieldNumber = 3; private static readonly pb::FieldCodec<global::POGOProtos.Enums.CameraTarget> _repeated_targetType_codec = pb::FieldCodec.ForEnum(26, x => (int) x, x => (global::POGOProtos.Enums.CameraTarget) x); private readonly pbc::RepeatedField<global::POGOProtos.Enums.CameraTarget> targetType_ = new pbc::RepeatedField<global::POGOProtos.Enums.CameraTarget>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::POGOProtos.Enums.CameraTarget> TargetType { get { return targetType_; } } /// <summary>Field number for the "ease_in_speed" field.</summary> public const int EaseInSpeedFieldNumber = 4; private static readonly pb::FieldCodec<float> _repeated_easeInSpeed_codec = pb::FieldCodec.ForFloat(34); private readonly pbc::RepeatedField<float> easeInSpeed_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> EaseInSpeed { get { return easeInSpeed_; } } /// <summary>Field number for the "east_out_speed" field.</summary> public const int EastOutSpeedFieldNumber = 5; private static readonly pb::FieldCodec<float> _repeated_eastOutSpeed_codec = pb::FieldCodec.ForFloat(42); private readonly pbc::RepeatedField<float> eastOutSpeed_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> EastOutSpeed { get { return eastOutSpeed_; } } /// <summary>Field number for the "duration_seconds" field.</summary> public const int DurationSecondsFieldNumber = 6; private static readonly pb::FieldCodec<float> _repeated_durationSeconds_codec = pb::FieldCodec.ForFloat(50); private readonly pbc::RepeatedField<float> durationSeconds_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> DurationSeconds { get { return durationSeconds_; } } /// <summary>Field number for the "wait_seconds" field.</summary> public const int WaitSecondsFieldNumber = 7; private static readonly pb::FieldCodec<float> _repeated_waitSeconds_codec = pb::FieldCodec.ForFloat(58); private readonly pbc::RepeatedField<float> waitSeconds_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> WaitSeconds { get { return waitSeconds_; } } /// <summary>Field number for the "transition_seconds" field.</summary> public const int TransitionSecondsFieldNumber = 8; private static readonly pb::FieldCodec<float> _repeated_transitionSeconds_codec = pb::FieldCodec.ForFloat(66); private readonly pbc::RepeatedField<float> transitionSeconds_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> TransitionSeconds { get { return transitionSeconds_; } } /// <summary>Field number for the "angle_degree" field.</summary> public const int AngleDegreeFieldNumber = 9; private static readonly pb::FieldCodec<float> _repeated_angleDegree_codec = pb::FieldCodec.ForFloat(74); private readonly pbc::RepeatedField<float> angleDegree_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> AngleDegree { get { return angleDegree_; } } /// <summary>Field number for the "angle_offset_degree" field.</summary> public const int AngleOffsetDegreeFieldNumber = 10; private static readonly pb::FieldCodec<float> _repeated_angleOffsetDegree_codec = pb::FieldCodec.ForFloat(82); private readonly pbc::RepeatedField<float> angleOffsetDegree_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> AngleOffsetDegree { get { return angleOffsetDegree_; } } /// <summary>Field number for the "pitch_degree" field.</summary> public const int PitchDegreeFieldNumber = 11; private static readonly pb::FieldCodec<float> _repeated_pitchDegree_codec = pb::FieldCodec.ForFloat(90); private readonly pbc::RepeatedField<float> pitchDegree_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> PitchDegree { get { return pitchDegree_; } } /// <summary>Field number for the "pitch_offset_degree" field.</summary> public const int PitchOffsetDegreeFieldNumber = 12; private static readonly pb::FieldCodec<float> _repeated_pitchOffsetDegree_codec = pb::FieldCodec.ForFloat(98); private readonly pbc::RepeatedField<float> pitchOffsetDegree_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> PitchOffsetDegree { get { return pitchOffsetDegree_; } } /// <summary>Field number for the "roll_degree" field.</summary> public const int RollDegreeFieldNumber = 13; private static readonly pb::FieldCodec<float> _repeated_rollDegree_codec = pb::FieldCodec.ForFloat(106); private readonly pbc::RepeatedField<float> rollDegree_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> RollDegree { get { return rollDegree_; } } /// <summary>Field number for the "distance_meters" field.</summary> public const int DistanceMetersFieldNumber = 14; private static readonly pb::FieldCodec<float> _repeated_distanceMeters_codec = pb::FieldCodec.ForFloat(114); private readonly pbc::RepeatedField<float> distanceMeters_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> DistanceMeters { get { return distanceMeters_; } } /// <summary>Field number for the "height_percent" field.</summary> public const int HeightPercentFieldNumber = 15; private static readonly pb::FieldCodec<float> _repeated_heightPercent_codec = pb::FieldCodec.ForFloat(122); private readonly pbc::RepeatedField<float> heightPercent_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> HeightPercent { get { return heightPercent_; } } /// <summary>Field number for the "vert_ctr_ratio" field.</summary> public const int VertCtrRatioFieldNumber = 16; private static readonly pb::FieldCodec<float> _repeated_vertCtrRatio_codec = pb::FieldCodec.ForFloat(130); private readonly pbc::RepeatedField<float> vertCtrRatio_ = new pbc::RepeatedField<float>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<float> VertCtrRatio { get { return vertCtrRatio_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CameraSettings); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CameraSettings other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (NextCamera != other.NextCamera) return false; if(!interpolation_.Equals(other.interpolation_)) return false; if(!targetType_.Equals(other.targetType_)) return false; if(!easeInSpeed_.Equals(other.easeInSpeed_)) return false; if(!eastOutSpeed_.Equals(other.eastOutSpeed_)) return false; if(!durationSeconds_.Equals(other.durationSeconds_)) return false; if(!waitSeconds_.Equals(other.waitSeconds_)) return false; if(!transitionSeconds_.Equals(other.transitionSeconds_)) return false; if(!angleDegree_.Equals(other.angleDegree_)) return false; if(!angleOffsetDegree_.Equals(other.angleOffsetDegree_)) return false; if(!pitchDegree_.Equals(other.pitchDegree_)) return false; if(!pitchOffsetDegree_.Equals(other.pitchOffsetDegree_)) return false; if(!rollDegree_.Equals(other.rollDegree_)) return false; if(!distanceMeters_.Equals(other.distanceMeters_)) return false; if(!heightPercent_.Equals(other.heightPercent_)) return false; if(!vertCtrRatio_.Equals(other.vertCtrRatio_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (NextCamera.Length != 0) hash ^= NextCamera.GetHashCode(); hash ^= interpolation_.GetHashCode(); hash ^= targetType_.GetHashCode(); hash ^= easeInSpeed_.GetHashCode(); hash ^= eastOutSpeed_.GetHashCode(); hash ^= durationSeconds_.GetHashCode(); hash ^= waitSeconds_.GetHashCode(); hash ^= transitionSeconds_.GetHashCode(); hash ^= angleDegree_.GetHashCode(); hash ^= angleOffsetDegree_.GetHashCode(); hash ^= pitchDegree_.GetHashCode(); hash ^= pitchOffsetDegree_.GetHashCode(); hash ^= rollDegree_.GetHashCode(); hash ^= distanceMeters_.GetHashCode(); hash ^= heightPercent_.GetHashCode(); hash ^= vertCtrRatio_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (NextCamera.Length != 0) { output.WriteRawTag(10); output.WriteString(NextCamera); } interpolation_.WriteTo(output, _repeated_interpolation_codec); targetType_.WriteTo(output, _repeated_targetType_codec); easeInSpeed_.WriteTo(output, _repeated_easeInSpeed_codec); eastOutSpeed_.WriteTo(output, _repeated_eastOutSpeed_codec); durationSeconds_.WriteTo(output, _repeated_durationSeconds_codec); waitSeconds_.WriteTo(output, _repeated_waitSeconds_codec); transitionSeconds_.WriteTo(output, _repeated_transitionSeconds_codec); angleDegree_.WriteTo(output, _repeated_angleDegree_codec); angleOffsetDegree_.WriteTo(output, _repeated_angleOffsetDegree_codec); pitchDegree_.WriteTo(output, _repeated_pitchDegree_codec); pitchOffsetDegree_.WriteTo(output, _repeated_pitchOffsetDegree_codec); rollDegree_.WriteTo(output, _repeated_rollDegree_codec); distanceMeters_.WriteTo(output, _repeated_distanceMeters_codec); heightPercent_.WriteTo(output, _repeated_heightPercent_codec); vertCtrRatio_.WriteTo(output, _repeated_vertCtrRatio_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (NextCamera.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NextCamera); } size += interpolation_.CalculateSize(_repeated_interpolation_codec); size += targetType_.CalculateSize(_repeated_targetType_codec); size += easeInSpeed_.CalculateSize(_repeated_easeInSpeed_codec); size += eastOutSpeed_.CalculateSize(_repeated_eastOutSpeed_codec); size += durationSeconds_.CalculateSize(_repeated_durationSeconds_codec); size += waitSeconds_.CalculateSize(_repeated_waitSeconds_codec); size += transitionSeconds_.CalculateSize(_repeated_transitionSeconds_codec); size += angleDegree_.CalculateSize(_repeated_angleDegree_codec); size += angleOffsetDegree_.CalculateSize(_repeated_angleOffsetDegree_codec); size += pitchDegree_.CalculateSize(_repeated_pitchDegree_codec); size += pitchOffsetDegree_.CalculateSize(_repeated_pitchOffsetDegree_codec); size += rollDegree_.CalculateSize(_repeated_rollDegree_codec); size += distanceMeters_.CalculateSize(_repeated_distanceMeters_codec); size += heightPercent_.CalculateSize(_repeated_heightPercent_codec); size += vertCtrRatio_.CalculateSize(_repeated_vertCtrRatio_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CameraSettings other) { if (other == null) { return; } if (other.NextCamera.Length != 0) { NextCamera = other.NextCamera; } interpolation_.Add(other.interpolation_); targetType_.Add(other.targetType_); easeInSpeed_.Add(other.easeInSpeed_); eastOutSpeed_.Add(other.eastOutSpeed_); durationSeconds_.Add(other.durationSeconds_); waitSeconds_.Add(other.waitSeconds_); transitionSeconds_.Add(other.transitionSeconds_); angleDegree_.Add(other.angleDegree_); angleOffsetDegree_.Add(other.angleOffsetDegree_); pitchDegree_.Add(other.pitchDegree_); pitchOffsetDegree_.Add(other.pitchOffsetDegree_); rollDegree_.Add(other.rollDegree_); distanceMeters_.Add(other.distanceMeters_); heightPercent_.Add(other.heightPercent_); vertCtrRatio_.Add(other.vertCtrRatio_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { NextCamera = input.ReadString(); break; } case 18: case 16: { interpolation_.AddEntriesFrom(input, _repeated_interpolation_codec); break; } case 26: case 24: { targetType_.AddEntriesFrom(input, _repeated_targetType_codec); break; } case 34: case 37: { easeInSpeed_.AddEntriesFrom(input, _repeated_easeInSpeed_codec); break; } case 42: case 45: { eastOutSpeed_.AddEntriesFrom(input, _repeated_eastOutSpeed_codec); break; } case 50: case 53: { durationSeconds_.AddEntriesFrom(input, _repeated_durationSeconds_codec); break; } case 58: case 61: { waitSeconds_.AddEntriesFrom(input, _repeated_waitSeconds_codec); break; } case 66: case 69: { transitionSeconds_.AddEntriesFrom(input, _repeated_transitionSeconds_codec); break; } case 74: case 77: { angleDegree_.AddEntriesFrom(input, _repeated_angleDegree_codec); break; } case 82: case 85: { angleOffsetDegree_.AddEntriesFrom(input, _repeated_angleOffsetDegree_codec); break; } case 90: case 93: { pitchDegree_.AddEntriesFrom(input, _repeated_pitchDegree_codec); break; } case 98: case 101: { pitchOffsetDegree_.AddEntriesFrom(input, _repeated_pitchOffsetDegree_codec); break; } case 106: case 109: { rollDegree_.AddEntriesFrom(input, _repeated_rollDegree_codec); break; } case 114: case 117: { distanceMeters_.AddEntriesFrom(input, _repeated_distanceMeters_codec); break; } case 122: case 125: { heightPercent_.AddEntriesFrom(input, _repeated_heightPercent_codec); break; } case 130: case 133: { vertCtrRatio_.AddEntriesFrom(input, _repeated_vertCtrRatio_codec); break; } } } } } #endregion } #endregion Designer generated code
// // Mono.Unix/StdioFileStream.cs // // Authors: // Jonathan Pryor (jonpryor@vt.edu) // // (C) 2005 Jonathan Pryor // // 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.Runtime.InteropServices; using System.Text; using Mono.Unix; namespace Mono.Unix { public class StdioFileStream : Stream { public static readonly IntPtr InvalidFileStream = IntPtr.Zero; public static readonly IntPtr StandardInput = Stdlib.stdin; public static readonly IntPtr StandardOutput = Stdlib.stdout; public static readonly IntPtr StandardError = Stdlib.stderr; public StdioFileStream (IntPtr fileStream) : this (fileStream, true) {} public StdioFileStream (IntPtr fileStream, bool ownsHandle) { InitStream (fileStream, ownsHandle); } public StdioFileStream (IntPtr fileStream, FileAccess access) : this (fileStream, access, true) {} public StdioFileStream (IntPtr fileStream, FileAccess access, bool ownsHandle) { InitStream (fileStream, ownsHandle); InitCanReadWrite (access); } public StdioFileStream (string path) { InitStream (Fopen (path, "r"), true); } public StdioFileStream (string path, string mode) { InitStream (Fopen (path, mode), true); } public StdioFileStream (string path, FileMode mode) { InitStream (Fopen (path, ToFopenMode (path, mode)), true); } public StdioFileStream (string path, FileAccess access) { InitStream (Fopen (path, ToFopenMode (path, access)), true); InitCanReadWrite (access); } public StdioFileStream (string path, FileMode mode, FileAccess access) { InitStream (Fopen (path, ToFopenMode (path, mode, access)), true); InitCanReadWrite (access); } private static IntPtr Fopen (string path, string mode) { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("path"); if (mode == null) throw new ArgumentNullException ("path"); IntPtr f = Stdlib.fopen (path, mode); if (f == IntPtr.Zero) throw new DirectoryNotFoundException ("path", UnixMarshal.CreateExceptionForLastError ()); return f; } private void InitStream (IntPtr fileStream, bool ownsHandle) { if (InvalidFileStream == fileStream) throw new ArgumentException (Locale.GetText ("Invalid file stream"), "fileStream"); this.file = fileStream; this.owner = ownsHandle; try { long offset = Stdlib.fseek (file, 0, SeekFlags.SEEK_CUR); if (offset != -1) canSeek = true; Stdlib.fread (IntPtr.Zero, 0, 0, file); if (Stdlib.ferror (file) == 0) canRead = true; Stdlib.fwrite (IntPtr.Zero, 0, 0, file); if (Stdlib.ferror (file) == 0) canWrite = true; Stdlib.clearerr (file); } catch (Exception e) { throw new ArgumentException (Locale.GetText ("Invalid file stream"), "fileStream"); } } private void InitCanReadWrite (FileAccess access) { canRead = canRead && (access == FileAccess.Read || access == FileAccess.ReadWrite); canWrite = canWrite && (access == FileAccess.Write || access == FileAccess.ReadWrite); } private static string ToFopenMode (string file, FileMode mode) { string cmode = UnixConvert.ToFopenMode (mode); AssertFileMode (file, mode); return cmode; } private static string ToFopenMode (string file, FileAccess access) { return UnixConvert.ToFopenMode (access); } private static string ToFopenMode (string file, FileMode mode, FileAccess access) { string cmode = UnixConvert.ToFopenMode (mode, access); bool exists = AssertFileMode (file, mode); // HACK: for open-or-create & read, mode is "rb", which doesn't create // files. If the file doesn't exist, we need to use "w+b" to ensure // file creation. if (mode == FileMode.OpenOrCreate && access == FileAccess.Read && !exists) cmode = "w+b"; return cmode; } private static bool AssertFileMode (string file, FileMode mode) { bool exists = FileExists (file); if (mode == FileMode.CreateNew && exists) throw new IOException ("File exists and FileMode.CreateNew specified"); if ((mode == FileMode.Open || mode == FileMode.Truncate) && !exists) throw new FileNotFoundException ("File doesn't exist and FileMode.Open specified", file); return exists; } private static bool FileExists (string file) { bool found = false; IntPtr f = Stdlib.fopen (file, "r"); found = f != IntPtr.Zero; if (f != IntPtr.Zero) Stdlib.fclose (f); return found; } private void AssertNotDisposed () { if (file == InvalidFileStream) throw new ObjectDisposedException ("Invalid File Stream"); } public IntPtr Handle { get {AssertNotDisposed (); return file;} } public override bool CanRead { get {return canRead;} } public override bool CanSeek { get {return canSeek;} } public override bool CanWrite { get {return canWrite;} } public override long Length { get { AssertNotDisposed (); if (!CanSeek) throw new NotSupportedException ("File Stream doesn't support seeking"); long curPos = Stdlib.ftell (file); if (curPos == -1) throw new NotSupportedException ("Unable to obtain current file position"); int r = Stdlib.fseek (file, 0, SeekFlags.SEEK_END); UnixMarshal.ThrowExceptionForLastErrorIf (r); long endPos = Stdlib.ftell (file); if (endPos == -1) UnixMarshal.ThrowExceptionForLastError (); r = Stdlib.fseek (file, curPos, SeekFlags.SEEK_SET); UnixMarshal.ThrowExceptionForLastErrorIf (r); return endPos; } } public override long Position { get { AssertNotDisposed (); if (!CanSeek) throw new NotSupportedException ("The stream does not support seeking"); long pos = Stdlib.ftell (file); if (pos == -1) UnixMarshal.ThrowExceptionForLastError (); return (long) pos; } set { AssertNotDisposed (); Seek (value, SeekOrigin.Begin); } } public void SaveFilePosition (FilePosition pos) { AssertNotDisposed (); int r = Stdlib.fgetpos (file, pos); UnixMarshal.ThrowExceptionForLastErrorIf (r); } public void RestoreFilePosition (FilePosition pos) { AssertNotDisposed (); if (pos == null) throw new ArgumentNullException ("value"); int r = Stdlib.fsetpos (file, pos); UnixMarshal.ThrowExceptionForLastErrorIf (r); } public override void Flush () { AssertNotDisposed (); int r = Stdlib.fflush (file); if (r != 0) UnixMarshal.ThrowExceptionForLastError (); } public override unsafe int Read ([In, Out] byte[] buffer, int offset, int count) { AssertNotDisposed (); AssertValidBuffer (buffer, offset, count); if (!CanRead) throw new NotSupportedException ("Stream does not support reading"); ulong r = 0; fixed (byte* buf = &buffer[offset]) { r = Stdlib.fread (buf, 1, (ulong) count, file); } if (r != (ulong) count) { if (Stdlib.ferror (file) != 0) throw new IOException (); } return (int) r; } private void AssertValidBuffer (byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); if (offset > buffer.Length) throw new ArgumentException ("destination offset is beyond array size"); if (offset > (buffer.Length - count)) throw new ArgumentException ("would overrun buffer"); } public void Rewind () { AssertNotDisposed (); Stdlib.rewind (file); } public override long Seek (long offset, SeekOrigin origin) { AssertNotDisposed (); if (!CanSeek) throw new NotSupportedException ("The File Stream does not support seeking"); SeekFlags sf = SeekFlags.SEEK_CUR; switch (origin) { case SeekOrigin.Begin: sf = SeekFlags.SEEK_SET; break; case SeekOrigin.Current: sf = SeekFlags.SEEK_CUR; break; case SeekOrigin.End: sf = SeekFlags.SEEK_END; break; default: throw new ArgumentException ("origin"); } int r = Stdlib.fseek (file, offset, sf); if (r != 0) throw new IOException ("Unable to seek", UnixMarshal.CreateExceptionForLastError ()); long pos = Stdlib.ftell (file); if (pos == -1) throw new IOException ("Unable to get current file position", UnixMarshal.CreateExceptionForLastError ()); return pos; } public override void SetLength (long value) { throw new NotSupportedException ("ANSI C doesn't provide a way to truncate a file"); } public override unsafe void Write (byte[] buffer, int offset, int count) { AssertNotDisposed (); AssertValidBuffer (buffer, offset, count); if (!CanWrite) throw new NotSupportedException ("File Stream does not support writing"); ulong r = 0; fixed (byte* buf = &buffer[offset]) { r = Stdlib.fwrite (buf, (ulong) 1, (ulong) count, file); } if (r != (ulong) count) UnixMarshal.ThrowExceptionForLastError (); } ~StdioFileStream () { Close (); } public override void Close () { if (file == InvalidFileStream) return; Flush (); if (owner) { int r = Stdlib.fclose (file); if (r != 0) UnixMarshal.ThrowExceptionForLastError (); } file = InvalidFileStream; canRead = false; canSeek = false; canWrite = false; GC.SuppressFinalize (this); } private bool canSeek = false; private bool canRead = false; private bool canWrite = false; private bool owner = true; private IntPtr file = InvalidFileStream; } } // vim: noexpandtab
// 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.Runtime.CompilerServices; //////////////////////////////////////////////////////////////////////////////// // Tests //////////////////////////////////////////////////////////////////////////////// namespace NativeVarargTest { public class ManagedNativeVarargTests { //////////////////////////////////////////////////////////////////////// // Test passing fixed args to functions marked varargs // // Does not use ArgIterator, only tests fixed args not varargs. // // Note that all methods will take an empty arglist, which will mark // the method as vararg. //////////////////////////////////////////////////////////////////////// [MethodImpl(MethodImplOptions.NoInlining)] public static int TestPassingIntsNoVarargs(int one, int two, int three, int four, int five, int six, int seven, int eight, int nine, __arglist) { return one + two + three + four + five + six + seven + eight + nine; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestPassingLongsNoVarargs(long one, long two, long three, long four, long five, long six, long seven, long eight, long nine, __arglist) { return one + two + three + four + five + six + seven + eight + nine; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingFloatsNoVarargs(float one, float two, float three, float four, float five, float six, float seven, float eight, float nine, __arglist) { return one + two + three + four + five + six + seven + eight + nine; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingDoublesNoVarargs(double one, double two, double three, double four, double five, double six, double seven, double eight, double nine, __arglist) { return one + two + three + four + five + six + seven + eight + nine; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingIntAndFloatsNoVarargs(int one, int two, int three, int four, int five, int six, int seven, int eight, int nine, float ten, float eleven, float twelve, float thirteen, float fourteen, float fifteen, float sixteen, float seventeen, float eighteen, __arglist) { float sum = one + two + three + four + five + six + seven + eight + nine; sum += ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen + eighteen; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingFloatsAndIntNoVarargs(float one, float two, float three, float four, float five, float six, float seven, float eight, float nine, int ten, int eleven, int twelve, int thirteen, int fourteen, int fifteen, int sixteen, int seventeen, int eighteen, __arglist) { float sum = one + two + three + four + five + six + seven + eight + nine; sum += ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen + eighteen; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingIntAndDoublesNoVarargs(int one, int two, int three, int four, int five, int six, int seven, int eight, int nine, double ten, double eleven, double twelve, double thirteen, double fourteen, double fifteen, double sixteen, double seventeen, double eighteen, __arglist) { double sum = one + two + three + four + five + six + seven + eight + nine; sum += ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen + eighteen; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingDoublesAndIntNoVarargs(double one, double two, double three, double four, double five, double six, double seven, double eight, double nine, int ten, int eleven, int twelve, int thirteen, int fourteen, int fifteen, int sixteen, int seventeen, int eighteen, __arglist) { double sum = one + two + three + four + five + six + seven + eight + nine; sum += ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen + eighteen; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingLongAndFloatsNoVarargs(long one, long two, long three, long four, long five, long six, long seven, long eight, long nine, float ten, float eleven, float twelve, float thirteen, float fourteen, float fifteen, float sixteen, float seventeen, float eighteen, __arglist) { float sum = one + two + three + four + five + six + seven + eight + nine; sum += ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen + eighteen; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingFloatsAndlongNoVarargs(float one, float two, float three, float four, float five, float six, float seven, float eight, float nine, long ten, long eleven, long twelve, long thirteen, long fourteen, long fifteen, long sixteen, long seventeen, long eighteen, __arglist) { float sum = one + two + three + four + five + six + seven + eight + nine; sum += ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen + eighteen; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassinglongAndDoublesNoVarargs(long one, long two, long three, long four, long five, long six, long seven, long eight, long nine, double ten, double eleven, double twelve, double thirteen, double fourteen, double fifteen, double sixteen, double seventeen, double eighteen, __arglist) { double sum = one + two + three + four + five + six + seven + eight + nine; sum += ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen + eighteen; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingDoublesAndlongNoVarargs(double one, double two, double three, double four, double five, double six, double seven, double eight, double nine, long ten, long eleven, long twelve, long thirteen, long fourteen, long fifteen, long sixteen, long seventeen, long eighteen, __arglist) { double sum = one + two + three + four + five + six + seven + eight + nine; sum += ten + eleven + twelve + thirteen + fourteen + fifteen + sixteen + seventeen + eighteen; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static int TestPassingTwoIntStructsNoVarargs(TwoIntStruct one, TwoIntStruct two, TwoIntStruct three, TwoIntStruct four, TwoIntStruct five, TwoIntStruct six, TwoIntStruct seven, TwoIntStruct eight, TwoIntStruct nine, TwoIntStruct ten, __arglist) { int sum = one.a + one.b; sum += two.a + two.b; sum += three.a + three.b; sum += four.a + four.b; sum += five.a + five.b; sum += six.a + six.b; sum += seven.a + seven.b; sum += eight.a + eight.b; sum += nine.a + nine.b; sum += ten.a + ten.b; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static int TestPassingFourIntStructsNoVarargs(FourIntStruct one, FourIntStruct two, FourIntStruct three, FourIntStruct four, FourIntStruct five, FourIntStruct six, FourIntStruct seven, FourIntStruct eight, FourIntStruct nine, FourIntStruct ten, __arglist) { int sum = one.a + one.b + one.c + one.d; sum += two.a + two.b + two.c + two.d; sum += three.a + three.b + three.c + three.d; sum += four.a + four.b + four.c + four.d; sum += five.a + five.b + five.c + five.d; sum += six.a + six.b + six.c + six.d; sum += seven.a + seven.b + seven.c + seven.d; sum += eight.a + eight.b + eight.c + eight.d; sum += nine.a + nine.b + nine.c + nine.d; sum += ten.a + ten.b + ten.c + ten.d; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static bool TestPassingTwoLongStructsNoVarargs(int count, long expected, TwoLongStruct one, TwoLongStruct two, TwoLongStruct three, TwoLongStruct four, TwoLongStruct five, TwoLongStruct six, TwoLongStruct seven, TwoLongStruct eight, TwoLongStruct nine, TwoLongStruct ten, __arglist) { long sum = one.a + one.b; sum += two.a + two.b; sum += three.a + three.b; sum += four.a + four.b; sum += five.a + five.b; sum += six.a + six.b; sum += seven.a + seven.b; sum += eight.a + eight.b; sum += nine.a + nine.b; sum += ten.a + ten.b; return sum == expected; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestPassingTwoLongStructsNoVarargs(TwoLongStruct one, TwoLongStruct two, TwoLongStruct three, TwoLongStruct four, TwoLongStruct five, TwoLongStruct six, TwoLongStruct seven, TwoLongStruct eight, TwoLongStruct nine, TwoLongStruct ten, __arglist) { long sum = one.a + one.b; sum += two.a + two.b; sum += three.a + three.b; sum += four.a + four.b; sum += five.a + five.b; sum += six.a + six.b; sum += seven.a + seven.b; sum += eight.a + eight.b; sum += nine.a + nine.b; sum += ten.a + ten.b; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestPassingTwoLongStructsAndIntNoVarargs(int a, TwoLongStruct one, TwoLongStruct two, TwoLongStruct three, TwoLongStruct four, TwoLongStruct five, TwoLongStruct six, TwoLongStruct seven, TwoLongStruct eight, TwoLongStruct nine, TwoLongStruct ten, __arglist) { long sum = one.a + one.b; sum += two.a + two.b; sum += three.a + three.b; sum += four.a + four.b; sum += five.a + five.b; sum += six.a + six.b; sum += seven.a + seven.b; sum += eight.a + eight.b; sum += nine.a + nine.b; sum += ten.a + ten.b; sum += a; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestPassingFourLongStructsNoVarargs(FourLongStruct one, FourLongStruct two, FourLongStruct three, FourLongStruct four, FourLongStruct five, FourLongStruct six, FourLongStruct seven, FourLongStruct eight, FourLongStruct nine, FourLongStruct ten, __arglist) { long sum = one.a + one.b + one.c + one.d; sum += two.a + two.b + two.c + two.d; sum += three.a + three.b + three.c + three.d; sum += four.a + four.b + four.c + four.d; sum += five.a + five.b + five.c + five.d; sum += six.a + six.b + six.c + six.d; sum += seven.a + seven.b + seven.c + seven.d; sum += eight.a + eight.b + eight.c + eight.d; sum += nine.a + nine.b + nine.c + nine.d; sum += ten.a + ten.b + ten.c + ten.d; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingTwoFloatStructsNoVarargs(TwoFloatStruct one, TwoFloatStruct two, TwoFloatStruct three, TwoFloatStruct four, TwoFloatStruct five, TwoFloatStruct six, TwoFloatStruct seven, TwoFloatStruct eight, TwoFloatStruct nine, TwoFloatStruct ten, __arglist) { float sum = one.a + one.b; sum += two.a + two.b; sum += three.a + three.b; sum += four.a + four.b; sum += five.a + five.b; sum += six.a + six.b; sum += seven.a + seven.b; sum += eight.a + eight.b; sum += nine.a + nine.b; sum += ten.a + ten.b; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingFourFloatStructsNoVarargs(FourFloatStruct one, FourFloatStruct two, FourFloatStruct three, FourFloatStruct four, FourFloatStruct five, FourFloatStruct six, FourFloatStruct seven, FourFloatStruct eight, FourFloatStruct nine, FourFloatStruct ten, __arglist) { float sum = one.a + one.b + one.c + one.d; sum += two.a + two.b + two.c + two.d; sum += three.a + three.b + three.c + three.d; sum += four.a + four.b + four.c + four.d; sum += five.a + five.b + five.c + five.d; sum += six.a + six.b + six.c + six.d; sum += seven.a + seven.b + seven.c + seven.d; sum += eight.a + eight.b + eight.c + eight.d; sum += nine.a + nine.b + nine.c + nine.d; sum += ten.a + ten.b + ten.c + ten.d; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingTwoDoubleStructsNoVarargs(TwoDoubleStruct one, TwoDoubleStruct two, TwoDoubleStruct three, TwoDoubleStruct four, TwoDoubleStruct five, TwoDoubleStruct six, TwoDoubleStruct seven, TwoDoubleStruct eight, TwoDoubleStruct nine, TwoDoubleStruct ten, __arglist) { double sum = one.a + one.b; sum += two.a + two.b; sum += three.a + three.b; sum += four.a + four.b; sum += five.a + five.b; sum += six.a + six.b; sum += seven.a + seven.b; sum += eight.a + eight.b; sum += nine.a + nine.b; sum += ten.a + ten.b; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingTwoDoubleStructsAndFloatNoVarargs(float a, TwoDoubleStruct one, TwoDoubleStruct two, TwoDoubleStruct three, TwoDoubleStruct four, TwoDoubleStruct five, TwoDoubleStruct six, TwoDoubleStruct seven, TwoDoubleStruct eight, TwoDoubleStruct nine, TwoDoubleStruct ten, __arglist) { double sum = one.a + one.b; sum += two.a + two.b; sum += three.a + three.b; sum += four.a + four.b; sum += five.a + five.b; sum += six.a + six.b; sum += seven.a + seven.b; sum += eight.a + eight.b; sum += nine.a + nine.b; sum += ten.a + ten.b; sum += a; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingFourDoubleStructsNoVarargs(FourDoubleStruct one, FourDoubleStruct two, FourDoubleStruct three, FourDoubleStruct four, FourDoubleStruct five, FourDoubleStruct six, FourDoubleStruct seven, FourDoubleStruct eight, FourDoubleStruct nine, FourDoubleStruct ten, __arglist) { double sum = one.a + one.b + one.c + one.d; sum += two.a + two.b + two.c + two.d; sum += three.a + three.b + three.c + three.d; sum += four.a + four.b + four.c + four.d; sum += five.a + five.b + five.c + five.d; sum += six.a + six.b + six.c + six.d; sum += seven.a + seven.b + seven.c + seven.d; sum += eight.a + eight.b + eight.c + eight.d; sum += nine.a + nine.b + nine.c + nine.d; sum += ten.a + ten.b + ten.c + ten.d; return sum; } //////////////////////////////////////////////////////////////////////// // Test returns //////////////////////////////////////////////////////////////////////// public static byte TestEchoByteManagedNoVararg(byte arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static char TestEchoCharManagedNoVararg(char arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static short TestEchoShortManagedNoVararg(short arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static int TestEchoIntManagedNoVararg(int arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestEchoLongManagedNoVararg(long arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestEchoFloatManagedNoVararg(float arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestEchoDoubleManagedNoVararg(double arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static OneIntStruct TestEchoOneIntStructManagedNoVararg(OneIntStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static TwoIntStruct TestEchoTwoIntStructManagedNoVararg(TwoIntStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static OneLongStruct TestEchoOneLongStructManagedNoVararg(OneLongStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static TwoLongStruct TestEchoTwoLongStructManagedNoVararg(TwoLongStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static EightByteStruct TestEchoEightByteStructStructManagedNoVararg(EightByteStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static FourIntStruct TestEchoFourIntStructManagedNoVararg(FourIntStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static SixteenByteStruct TestEchoSixteenByteStructManagedNoVararg(SixteenByteStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static FourLongStruct TestEchoFourLongStructManagedNoVararg(FourLongStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static OneFloatStruct TestEchoOneFloatStructManagedNoVararg(OneFloatStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static TwoFloatStruct TestEchoTwoFloatStructManagedNoVararg(TwoFloatStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static OneDoubleStruct TestEchoOneDoubleStructManagedNoVararg(OneDoubleStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static TwoDoubleStruct TestEchoTwoDoubleStructManagedNoVararg(TwoDoubleStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static ThreeDoubleStruct TestEchoThreeDoubleStructManagedNoVararg(ThreeDoubleStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static FourFloatStruct TestEchoFourFloatStructManagedNoVararg(FourFloatStruct arg, __arglist) { return arg; } [MethodImpl(MethodImplOptions.NoInlining)] public static FourDoubleStruct TestEchoFourDoubleStructManagedNoVararg(FourDoubleStruct arg, __arglist) { return arg; } //////////////////////////////////////////////////////////////////////// // Test passing variable amount of args // // Uses ArgIterator //////////////////////////////////////////////////////////////////////// [MethodImpl(MethodImplOptions.NoInlining)] public static int TestPassingInts(int count, __arglist) { int calculatedCount = 0; ArgIterator it = new ArgIterator(__arglist); int sum = 0; while (it.GetRemainingCount() != 0) { int arg = __refvalue(it.GetNextArg(), int); sum += arg; ++calculatedCount; } if (calculatedCount != count) return -1; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestPassingLongs(int count, __arglist) { ArgIterator it = new ArgIterator(__arglist); int calculatedCount = 0; long sum = 0; while (it.GetRemainingCount() != 0) { long arg = __refvalue(it.GetNextArg(), long); sum += arg; ++calculatedCount; } if (calculatedCount != count) return -1; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingFloats(int count, __arglist) { ArgIterator it = new ArgIterator(__arglist); int calculatedCount = 0; float sum = 0; while (it.GetRemainingCount() != 0) { float arg = __refvalue(it.GetNextArg(), float); sum += arg; ++calculatedCount; } if (calculatedCount != count) return -1; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingDoubles(int count, __arglist) { ArgIterator it = new ArgIterator(__arglist); int calculatedCount = 0; double sum = 0; while (it.GetRemainingCount() != 0) { double arg = __refvalue(it.GetNextArg(), double); sum += arg; ++calculatedCount; } if (calculatedCount != count) return -1; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestPassingIntsAndLongs(int int_count, int long_count, __arglist) { ArgIterator it = new ArgIterator(__arglist); int count = int_count + long_count; long sum = 0; for (int index = 0; index < int_count; ++index) { sum += __refvalue(it.GetNextArg(), int); } for (int index = 0; index < long_count; ++index) { sum += __refvalue(it.GetNextArg(), long); } return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingFloatsAndDoubles(int float_count, int double_count, __arglist) { ArgIterator it = new ArgIterator(__arglist); int count = float_count + double_count; double sum = 0; for (int index = 0; index < float_count; ++index) { sum += __refvalue(it.GetNextArg(), float); } for (int index = 0; index < double_count; ++index) { sum += __refvalue(it.GetNextArg(), double); } return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestPassingIntsAndFloats(float expected_value, __arglist) { ArgIterator it = new ArgIterator(__arglist); float sum = 0; for (int index = 0; index < 6; ++index) { if (index % 2 == 0) { sum += __refvalue(it.GetNextArg(), int); } else { sum += __refvalue(it.GetNextArg(), float); } } if (expected_value != 66.0f) return -1; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestPassingLongsAndDoubles(double expected_value, __arglist) { ArgIterator it = new ArgIterator(__arglist); double sum = 0; for (int index = 0; index < 6; ++index) { if (index % 2 == 0) { sum += __refvalue(it.GetNextArg(), long); } else { sum += __refvalue(it.GetNextArg(), double); } } if (expected_value != 66.0) return -1; return sum; } [MethodImpl(MethodImplOptions.NoInlining)] public static int CheckPassingStruct(int count, __arglist) { ArgIterator it = new ArgIterator(__arglist); int passed = 0; bool is_b = __refvalue(it.GetNextArg(), int) == 1; bool is_floating = __refvalue(it.GetNextArg(), int) == 1; bool is_mixed = __refvalue(it.GetNextArg(), int) == 1; int byte_count = __refvalue(it.GetNextArg(), int); int struct_count = __refvalue(it.GetNextArg(), int); if (!is_floating) { if (byte_count == 8) { // Eight byte structs. if (is_b) { OneLongStruct s = new OneLongStruct(); long sum = 0; long expected_value = __refvalue(it.GetNextArg(), long); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), OneLongStruct); sum += s.a; } if (sum != expected_value) passed = 1; } else { TwoIntStruct s = new TwoIntStruct(); int sum = 0; int expected_value = __refvalue(it.GetNextArg(), int); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), TwoIntStruct); sum += s.a + s.b; } if (sum != expected_value) passed = 1; } } else if (byte_count == 16) { // 16 byte structs. if (is_b) { FourIntStruct s = new FourIntStruct(); int sum = 0; int expected_value = __refvalue(it.GetNextArg(), int); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), FourIntStruct); sum += s.a + s.b + s.c + s.d; } if (sum != expected_value) passed = 1; } else { TwoLongStruct s = new TwoLongStruct(); long sum = 0; long expected_value = __refvalue(it.GetNextArg(), long); sum = 0; while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), TwoLongStruct); sum += s.a + s.b; } if (sum != expected_value) passed = 1; } } else if (byte_count == 32) { FourLongStruct s = new FourLongStruct(); long sum = 0; long expected_value = __refvalue(it.GetNextArg(), long); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), FourLongStruct); sum += s.a + s.b + s.c + s.d; } if (sum != expected_value) passed = 1; } } else { if (byte_count == 8) { // Eight byte structs. if (is_b) { OneDoubleStruct s = new OneDoubleStruct(); double sum = 0; double expected_value = __refvalue(it.GetNextArg(), double); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), OneDoubleStruct); sum += s.a; } if (sum != expected_value) passed = 1; } else { TwoFloatStruct s = new TwoFloatStruct(); float sum = 0f; float expected_value = __refvalue(it.GetNextArg(), float); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), TwoFloatStruct); sum += s.a + s.b; } if (sum != expected_value) passed = 1; } } else if (byte_count == 16) { // 16 byte structs. if (is_b) { FourFloatStruct s = new FourFloatStruct(); float sum = 0; float expected_value = __refvalue(it.GetNextArg(), float); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), FourFloatStruct); sum += s.a + s.b + s.c + s.d; } if (sum != expected_value) passed = 1; } else { TwoDoubleStruct s = new TwoDoubleStruct(); double sum = 0; double expected_value = __refvalue(it.GetNextArg(), double); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), TwoDoubleStruct); sum += s.a + s.b; } if (sum != expected_value) passed = 1; } } else if (byte_count == 32) { FourDoubleStruct s = new FourDoubleStruct(); double sum = 0; double expected_value = __refvalue(it.GetNextArg(), double); while (struct_count-- != 0) { s = __refvalue(it.GetNextArg(), FourDoubleStruct); sum += s.a + s.b + s.c + s.d; } if (sum != expected_value) passed = 1; } } return passed; } [MethodImpl(MethodImplOptions.NoInlining)] public static int CheckPassingFourSixteenByteStructs(int count, __arglist) { ArgIterator it = new ArgIterator(__arglist); int passed = 0; long calculated_value = 0; long expected_value = __refvalue(it.GetNextArg(), long); for (int index = 0; index < 4; ++index) { TwoLongStruct s = __refvalue(it.GetNextArg(), TwoLongStruct); calculated_value += s.a + s.b; } passed = expected_value == calculated_value ? 0 : 1; return passed; } //////////////////////////////////////////////////////////////////////// // Test returns, using passed vararg //////////////////////////////////////////////////////////////////////// public static byte TestEchoByteManaged(byte arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); Debug.Assert(it.GetRemainingCount() > 0); var varArg = __refvalue(it.GetNextArg(), byte); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static char TestEchoCharManaged(char arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), char); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static short TestEchoShortManaged(short arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), short); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static int TestEchoIntManaged(int arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), int); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static long TestEchoLongManaged(long arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), long); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static float TestEchoFloatManaged(float arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), float); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static double TestEchoDoubleManaged(double arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), double); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static OneIntStruct TestEchoOneIntStructManaged(OneIntStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), OneIntStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static TwoIntStruct TestEchoTwoIntStructManaged(TwoIntStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), TwoIntStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static OneLongStruct TestEchoOneLongStructManaged(OneLongStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), OneLongStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static TwoLongStruct TestEchoTwoLongStructManaged(TwoLongStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), TwoLongStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static EightByteStruct TestEchoEightByteStructStructManaged(EightByteStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), EightByteStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static FourIntStruct TestEchoFourIntStructManaged(FourIntStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), FourIntStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static SixteenByteStruct TestEchoSixteenByteStructManaged(SixteenByteStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), SixteenByteStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static FourLongStruct TestEchoFourLongStructManaged(FourLongStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), FourLongStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static OneFloatStruct TestEchoOneFloatStructManaged(OneFloatStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), OneFloatStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static TwoFloatStruct TestEchoTwoFloatStructManaged(TwoFloatStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), TwoFloatStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static OneDoubleStruct TestEchoOneDoubleStructManaged(OneDoubleStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), OneDoubleStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static TwoDoubleStruct TestEchoTwoDoubleStructManaged(TwoDoubleStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), TwoDoubleStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static ThreeDoubleStruct TestEchoThreeDoubleStructManaged(ThreeDoubleStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), ThreeDoubleStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static FourFloatStruct TestEchoFourFloatStructManaged(FourFloatStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), FourFloatStruct); return varArg; } [MethodImpl(MethodImplOptions.NoInlining)] public static FourDoubleStruct TestEchoFourDoubleStructManaged(FourDoubleStruct arg, __arglist) { ArgIterator it = new ArgIterator(__arglist); var varArg = __refvalue(it.GetNextArg(), FourDoubleStruct); return varArg; } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityTest { public interface ITestComponent : IComparable<ITestComponent> { void EnableTest(bool enable); bool IsTestGroup(); GameObject gameObject { get; } string Name { get; } ITestComponent GetTestGroup(); bool IsExceptionExpected(string exceptionType); bool ShouldSucceedOnException(); double GetTimeout(); bool IsIgnored(); bool ShouldSucceedOnAssertions(); bool IsExludedOnThisPlatform(); } public class TestComponent : MonoBehaviour, ITestComponent { public static ITestComponent NullTestComponent = new NullTestComponentImpl(); public float timeout = 5; public bool ignored = false; public bool succeedAfterAllAssertionsAreExecuted = false; public bool expectException = false; public string expectedExceptionList = ""; public bool succeedWhenExceptionIsThrown = false; public IncludedPlatforms includedPlatforms = (IncludedPlatforms) ~0L; public string[] platformsToIgnore = null; public bool dynamic; public string dynamicTypeName; public bool IsExludedOnThisPlatform() { return platformsToIgnore != null && platformsToIgnore.Any(platform => platform == Application.platform.ToString()); } static bool IsAssignableFrom(Type a, Type b) { #if !UNITY_METRO return a.IsAssignableFrom(b); #else return false; #endif } public bool IsExceptionExpected(string exception) { if (!expectException) return false; exception = exception.Trim(); foreach (var expectedException in expectedExceptionList.Split(',').Select(e => e.Trim())) { if (exception == expectedException) return true; var exceptionType = Type.GetType(exception) ?? GetTypeByName(exception); var expectedExceptionType = Type.GetType(expectedException) ?? GetTypeByName(expectedException); if (exceptionType != null && expectedExceptionType != null && IsAssignableFrom(expectedExceptionType, exceptionType)) return true; } return false; } public bool ShouldSucceedOnException() { return succeedWhenExceptionIsThrown; } public double GetTimeout() { return timeout; } public bool IsIgnored() { return ignored; } public bool ShouldSucceedOnAssertions() { return succeedAfterAllAssertionsAreExecuted; } private static Type GetTypeByName(string className) { #if !UNITY_METRO return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).FirstOrDefault(type => type.Name == className); #else return null; #endif } public void OnValidate() { if (timeout < 0.01f) timeout = 0.01f; } // Legacy [Flags] public enum IncludedPlatforms { WindowsEditor = 1 << 0, OSXEditor = 1 << 1, WindowsPlayer = 1 << 2, OSXPlayer = 1 << 3, LinuxPlayer = 1 << 4, MetroPlayerX86 = 1 << 5, MetroPlayerX64 = 1 << 6, MetroPlayerARM = 1 << 7, WindowsWebPlayer = 1 << 8, OSXWebPlayer = 1 << 9, Android = 1 << 10, // ReSharper disable once InconsistentNaming IPhonePlayer = 1 << 11, TizenPlayer = 1 << 12, WP8Player = 1 << 13, BB10Player = 1 << 14, NaCl = 1 << 15, PS3 = 1 << 16, XBOX360 = 1 << 17, WiiPlayer = 1 << 18, PSP2 = 1 << 19, PS4 = 1 << 20, PSMPlayer = 1 << 21, XboxOne = 1 << 22, } #region ITestComponent implementation public void EnableTest(bool enable) { if (enable && dynamic) { Type t = Type.GetType(dynamicTypeName); var s = gameObject.GetComponent(t) as MonoBehaviour; if (s != null) DestroyImmediate(s); gameObject.AddComponent(t); } if (gameObject.activeSelf != enable) gameObject.SetActive(enable); } public int CompareTo(ITestComponent obj) { if (obj == NullTestComponent) return 1; var result = gameObject.name.CompareTo(obj.gameObject.name); if (result == 0) result = gameObject.GetInstanceID().CompareTo(obj.gameObject.GetInstanceID()); return result; } public bool IsTestGroup() { for (int i = 0; i < gameObject.transform.childCount; i++) { var childTc = gameObject.transform.GetChild(i).GetComponent(typeof(TestComponent)); if (childTc != null) return true; } return false; } public string Name { get { return gameObject == null ? "" : gameObject.name; } } public ITestComponent GetTestGroup() { var parent = gameObject.transform.parent; if (parent == null) return NullTestComponent; return parent.GetComponent<TestComponent>(); } public override bool Equals(object o) { if (o is TestComponent) return this == (o as TestComponent); return false; } public override int GetHashCode() { return base.GetHashCode(); } public static bool operator ==(TestComponent a, TestComponent b) { if (ReferenceEquals(a, b)) return true; if (((object)a == null) || ((object)b == null)) return false; if (a.dynamic && b.dynamic) return a.dynamicTypeName == b.dynamicTypeName; if (a.dynamic || b.dynamic) return false; return a.gameObject == b.gameObject; } public static bool operator !=(TestComponent a, TestComponent b) { return !(a == b); } #endregion #region Static helpers public static TestComponent CreateDynamicTest(Type type) { var go = CreateTest(type.Name); go.hideFlags |= HideFlags.DontSave; go.SetActive(false); var tc = go.GetComponent<TestComponent>(); tc.dynamic = true; tc.dynamicTypeName = type.AssemblyQualifiedName; #if !UNITY_METRO foreach (var typeAttribute in type.GetCustomAttributes(false)) { if (typeAttribute is IntegrationTest.TimeoutAttribute) tc.timeout = (typeAttribute as IntegrationTest.TimeoutAttribute).timeout; else if (typeAttribute is IntegrationTest.IgnoreAttribute) tc.ignored = true; else if (typeAttribute is IntegrationTest.SucceedWithAssertions) tc.succeedAfterAllAssertionsAreExecuted = true; else if (typeAttribute is IntegrationTest.ExcludePlatformAttribute) tc.platformsToIgnore = (typeAttribute as IntegrationTest.ExcludePlatformAttribute).platformsToExclude; else if (typeAttribute is IntegrationTest.ExpectExceptions) { var attribute = (typeAttribute as IntegrationTest.ExpectExceptions); tc.expectException = true; tc.expectedExceptionList = string.Join(",", attribute.exceptionTypeNames); tc.succeedWhenExceptionIsThrown = attribute.succeedOnException; } } go.AddComponent(type); #endif // if !UNITY_METRO return tc; } public static GameObject CreateTest() { return CreateTest("New Test"); } private static GameObject CreateTest(string name) { var go = new GameObject(name); go.AddComponent<TestComponent>(); return go; } public static List<TestComponent> FindAllTestsOnScene() { var tests = Resources.FindObjectsOfTypeAll (typeof(TestComponent)).Cast<TestComponent> (); #if UNITY_EDITOR tests = tests.Where( t => {var p = PrefabUtility.GetPrefabType(t); return p != PrefabType.Prefab && p != PrefabType.ModelPrefab;} ); #endif return tests.ToList (); } public static List<TestComponent> FindAllTopTestsOnScene() { return FindAllTestsOnScene().Where(component => component.gameObject.transform.parent == null).ToList(); } public static List<TestComponent> FindAllDynamicTestsOnScene() { return FindAllTestsOnScene().Where(t => t.dynamic).ToList(); } public static void DestroyAllDynamicTests() { foreach (var dynamicTestComponent in FindAllDynamicTestsOnScene()) DestroyImmediate(dynamicTestComponent.gameObject); } public static void DisableAllTests() { foreach (var t in FindAllTestsOnScene()) t.EnableTest(false); } public static bool AnyTestsOnScene() { return FindAllTestsOnScene().Any(); } public static bool AnyDynamicTestForCurrentScene() { #if UNITY_EDITOR return TestComponent.GetTypesWithHelpAttribute(EditorApplication.currentScene).Any(); #else return TestComponent.GetTypesWithHelpAttribute(Application.loadedLevelName).Any(); #endif } #endregion private sealed class NullTestComponentImpl : ITestComponent { public int CompareTo(ITestComponent other) { if (other == this) return 0; return -1; } public void EnableTest(bool enable) { } public bool IsTestGroup() { throw new NotImplementedException(); } public GameObject gameObject { get; private set; } public string Name { get { return ""; } } public ITestComponent GetTestGroup() { return null; } public bool IsExceptionExpected(string exceptionType) { throw new NotImplementedException(); } public bool ShouldSucceedOnException() { throw new NotImplementedException(); } public double GetTimeout() { throw new NotImplementedException(); } public bool IsIgnored() { throw new NotImplementedException(); } public bool ShouldSucceedOnAssertions() { throw new NotImplementedException(); } public bool IsExludedOnThisPlatform() { throw new NotImplementedException(); } } public static IEnumerable<Type> GetTypesWithHelpAttribute(string sceneName) { #if !UNITY_METRO foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { foreach (Type type in assembly.GetTypes()) { var attributes = type.GetCustomAttributes(typeof(IntegrationTest.DynamicTestAttribute), true); if (attributes.Length == 1) { var a = attributes.Single() as IntegrationTest.DynamicTestAttribute; if (a.IncludeOnScene(sceneName)) yield return type; } } } #else // if !UNITY_METRO yield break; #endif // if !UNITY_METRO } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface { internal abstract class AbstractExtractInterfaceService : ILanguageService { internal abstract Task<SyntaxNode> GetTypeDeclarationAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken); internal abstract Solution GetSolutionWithUpdatedOriginalType( Solution solutionWithFormattedInterfaceDocument, INamedTypeSymbol extractedInterfaceSymbol, IEnumerable<ISymbol> includedMembers, Dictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, List<DocumentId> documentIds, SyntaxAnnotation typeNodeAnnotation, DocumentId documentIdWithTypeNode, CancellationToken cancellationToken); internal abstract string GetGeneratedNameTypeParameterSuffix(IList<ITypeParameterSymbol> typeParameters, Workspace workspace); internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions); internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode); public async Task<IEnumerable<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false); return typeAnalysisResult.CanExtractInterface ? SpecializedCollections.SingletonEnumerable(new ExtractInterfaceCodeAction(this, typeAnalysisResult)) : SpecializedCollections.EmptyEnumerable<ExtractInterfaceCodeAction>(); } public ExtractInterfaceResult ExtractInterface( Document documentWithTypeToExtractFrom, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken) { var typeAnalysisResult = AnalyzeTypeAtPositionAsync(documentWithTypeToExtractFrom, position, TypeDiscoveryRule.TypeDeclaration, cancellationToken).WaitAndGetResult(cancellationToken); if (!typeAnalysisResult.CanExtractInterface) { errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error); return new ExtractInterfaceResult(succeeded: false); } return ExtractInterfaceFromAnalyzedType(typeAnalysisResult, cancellationToken); } public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken) { var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false); if (typeNode == null) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken); if (type == null || type.Kind != SymbolKind.NamedType) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var typeToExtractFrom = type as INamedTypeSymbol; var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember); if (!extractableMembers.Any()) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } return new ExtractInterfaceTypeAnalysisResult(this, document, typeNode, typeToExtractFrom, extractableMembers); } public ExtractInterfaceResult ExtractInterfaceFromAnalyzedType(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken) { var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace ? string.Empty : refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString(); var extractInterfaceOptions = GetExtractInterfaceOptions( refactoringResult.DocumentToExtractFrom, refactoringResult.TypeToExtractFrom, refactoringResult.ExtractableMembers, containingNamespaceDisplay, cancellationToken); if (extractInterfaceOptions.IsCancelled) { return new ExtractInterfaceResult(succeeded: false); } return ExtractInterfaceFromAnalyzedType(refactoringResult, extractInterfaceOptions, cancellationToken); } public ExtractInterfaceResult ExtractInterfaceFromAnalyzedType(ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var solution = refactoringResult.DocumentToExtractFrom.Project.Solution; List<DocumentId> documentIds; SyntaxAnnotation typeNodeSyntaxAnnotation; var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions); var symbolToDeclarationAnnotationMap = CreateSymbolToDeclarationAnnotationMap( extractInterfaceOptions.IncludedMembers, ref solution, out documentIds, refactoringResult.TypeNode, out typeNodeSyntaxAnnotation, cancellationToken); var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: null, accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), typeKind: TypeKind.Interface, name: extractInterfaceOptions.InterfaceName, typeParameters: GetTypeParameters(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers), members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers)); var interfaceDocumentId = DocumentId.CreateNewId(refactoringResult.DocumentToExtractFrom.Project.Id, debugName: extractInterfaceOptions.FileName); var unformattedInterfaceDocument = GetUnformattedInterfaceDocument( solution, containingNamespaceDisplay, extractInterfaceOptions.FileName, refactoringResult.DocumentToExtractFrom.Folders, extractedInterfaceSymbol, interfaceDocumentId, cancellationToken); var solutionWithFormattedInterfaceDocument = GetSolutionWithFormattedInterfaceDocument(unformattedInterfaceDocument, cancellationToken); var completedSolution = GetSolutionWithOriginalTypeUpdated( solutionWithFormattedInterfaceDocument, documentIds, refactoringResult.DocumentToExtractFrom.Id, typeNodeSyntaxAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolToDeclarationAnnotationMap, cancellationToken); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: interfaceDocumentId); } private Dictionary<ISymbol, SyntaxAnnotation> CreateSymbolToDeclarationAnnotationMap( IEnumerable<ISymbol> includedMembers, ref Solution solution, out List<DocumentId> documentIds, SyntaxNode typeNode, out SyntaxAnnotation typeNodeAnnotation, CancellationToken cancellationToken) { var symbolToDeclarationAnnotationMap = new Dictionary<ISymbol, SyntaxAnnotation>(); var currentRoots = new Dictionary<SyntaxTree, SyntaxNode>(); documentIds = new List<DocumentId>(); var typeNodeRoot = typeNode.SyntaxTree.GetRoot(CancellationToken.None); typeNodeAnnotation = new SyntaxAnnotation(); currentRoots[typeNode.SyntaxTree] = typeNodeRoot.ReplaceNode(typeNode, typeNode.WithAdditionalAnnotations(typeNodeAnnotation)); documentIds.Add(solution.GetDocument(typeNode.SyntaxTree).Id); foreach (var includedMember in includedMembers) { var location = includedMember.Locations.Single(); var tree = location.SourceTree; SyntaxNode root; if (!currentRoots.TryGetValue(tree, out root)) { root = tree.GetRoot(cancellationToken); documentIds.Add(solution.GetDocument(tree).Id); } var token = root.FindToken(location.SourceSpan.Start); var annotation = new SyntaxAnnotation(); symbolToDeclarationAnnotationMap.Add(includedMember, annotation); currentRoots[tree] = root.ReplaceToken(token, token.WithAdditionalAnnotations(annotation)); } foreach (var root in currentRoots) { var document = solution.GetDocument(root.Key); solution = solution.WithDocumentSyntaxRoot(document.Id, root.Value, PreservationMode.PreserveIdentity); } return symbolToDeclarationAnnotationMap; } internal ExtractInterfaceOptionsResult GetExtractInterfaceOptions( Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers, string containingNamespace, CancellationToken cancellationToken) { var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name; var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name)); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); var generatedNameTypeParameterSuffix = GetGeneratedNameTypeParameterSuffix(GetTypeParameters(type, extractableMembers), document.Project.Solution.Workspace); var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); return service.GetExtractInterfaceOptions( syntaxFactsService, notificationService, extractableMembers.ToList(), defaultInterfaceName, conflictingTypeNames.ToList(), containingNamespace, generatedNameTypeParameterSuffix, document.Project.Language); } private Document GetUnformattedInterfaceDocument( Solution solution, string containingNamespaceDisplay, string name, IEnumerable<string> folders, INamedTypeSymbol extractedInterfaceSymbol, DocumentId interfaceDocumentId, CancellationToken cancellationToken) { var solutionWithInterfaceDocument = solution.AddDocument(interfaceDocumentId, name, text: "", folders: folders); var interfaceDocument = solutionWithInterfaceDocument.GetDocument(interfaceDocumentId); var interfaceDocumentSemanticModel = interfaceDocument.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var namespaceParts = containingNamespaceDisplay.Split('.').Where(s => !string.IsNullOrEmpty(s)); var unformattedInterfaceDocument = CodeGenerator.AddNamespaceOrTypeDeclarationAsync( interfaceDocument.Project.Solution, interfaceDocumentSemanticModel.GetEnclosingNamespace(0, cancellationToken), extractedInterfaceSymbol.GenerateRootNamespaceOrType(namespaceParts.ToArray()), options: new CodeGenerationOptions(interfaceDocumentSemanticModel.SyntaxTree.GetLocation(new TextSpan())), cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); return unformattedInterfaceDocument; } private static Solution GetSolutionWithFormattedInterfaceDocument(Document unformattedInterfaceDocument, CancellationToken cancellationToken) { Solution solutionWithInterfaceDocument; var formattedRoot = Formatter.Format(unformattedInterfaceDocument.GetSyntaxRootSynchronously(cancellationToken), unformattedInterfaceDocument.Project.Solution.Workspace, cancellationToken: cancellationToken); var rootToSimplify = formattedRoot.WithAdditionalAnnotations(Simplifier.Annotation); var finalInterfaceDocument = Simplifier.ReduceAsync(unformattedInterfaceDocument.WithSyntaxRoot(rootToSimplify), cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); solutionWithInterfaceDocument = finalInterfaceDocument.Project.Solution; return solutionWithInterfaceDocument; } private Solution GetSolutionWithOriginalTypeUpdated( Solution solutionWithFormattedInterfaceDocument, List<DocumentId> documentIds, DocumentId invocationLocationDocumentId, SyntaxAnnotation typeNodeAnnotation, INamedTypeSymbol typeToExtractFrom, INamedTypeSymbol extractedInterfaceSymbol, IEnumerable<ISymbol> includedMembers, Dictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken) { // If an interface "INewInterface" is extracted from an interface "IExistingInterface", // then "INewInterface" is not marked as implementing "IExistingInterface" and its // extracted members are also not updated. if (typeToExtractFrom.TypeKind == TypeKind.Interface) { return solutionWithFormattedInterfaceDocument; } var formattedSolution = GetSolutionWithUpdatedOriginalType( solutionWithFormattedInterfaceDocument, extractedInterfaceSymbol, includedMembers, symbolToDeclarationAnnotationMap, documentIds, typeNodeAnnotation, invocationLocationDocumentId, cancellationToken); foreach (var docId in documentIds) { var formattedDoc = Formatter.FormatAsync( formattedSolution.GetDocument(docId), Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); formattedSolution = formattedDoc.Project.Solution; } return formattedSolution; } private IList<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers) { var interfaceMembers = new List<ISymbol>(); foreach (var member in includedMembers) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol( attributes: SpecializedCollections.EmptyList<AttributeData>(), accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true), type: @event.Type, explicitInterfaceSymbol: null, name: @event.Name)); break; case SymbolKind.Method: var method = member as IMethodSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: SpecializedCollections.EmptyList<AttributeData>(), accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.IsUnsafe()), returnType: method.ReturnType, explicitInterfaceSymbol: null, name: method.Name, typeParameters: method.TypeParameters, parameters: method.Parameters)); break; case SymbolKind.Property: var property = member as IPropertySymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: SpecializedCollections.EmptyList<AttributeData>(), accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.IsUnsafe()), type: property.Type, explicitInterfaceSymbol: null, name: property.Name, parameters: property.Parameters, getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null), setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null), isIndexer: property.IsIndexer)); break; default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); break; } } return interfaceMembers; } internal virtual bool IsExtractableMember(ISymbol m) { if (m.IsStatic || m.DeclaredAccessibility != Accessibility.Public) { return false; } if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod()) { return true; } if (m.Kind == SymbolKind.Property) { var prop = m as IPropertySymbol; return (prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) || (prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public); } return false; } private IList<ITypeParameterSymbol> GetTypeParameters(INamedTypeSymbol type, IEnumerable<ISymbol> includedMembers) { var potentialTypeParameters = GetPotentialTypeParameters(type); var directlyReferencedTypeParameters = GetDirectlyReferencedTypeParameters(potentialTypeParameters, includedMembers); // The directly referenced TypeParameters may have constraints that reference other // type parameters. var allReferencedTypeParameters = new HashSet<ITypeParameterSymbol>(directlyReferencedTypeParameters); var unanalyzedTypeParameters = new Queue<ITypeParameterSymbol>(directlyReferencedTypeParameters); while (!unanalyzedTypeParameters.IsEmpty()) { var typeParameter = unanalyzedTypeParameters.Dequeue(); foreach (var constraint in typeParameter.ConstraintTypes) { foreach (var originalTypeParameter in potentialTypeParameters) { if (!allReferencedTypeParameters.Contains(originalTypeParameter) && DoesTypeReferenceTypeParameter(constraint, originalTypeParameter, new HashSet<ITypeSymbol>())) { allReferencedTypeParameters.Add(originalTypeParameter); unanalyzedTypeParameters.Enqueue(originalTypeParameter); } } } } return potentialTypeParameters.Where(p => allReferencedTypeParameters.Contains(p)).ToList(); } private List<ITypeParameterSymbol> GetPotentialTypeParameters(INamedTypeSymbol type) { var typeParameters = new List<ITypeParameterSymbol>(); var typesToVisit = new Stack<INamedTypeSymbol>(); var currentType = type; while (currentType != null) { typesToVisit.Push(currentType); currentType = currentType.ContainingType; } while (typesToVisit.Any()) { typeParameters.AddRange(typesToVisit.Pop().TypeParameters); } return typeParameters; } private IList<ITypeParameterSymbol> GetDirectlyReferencedTypeParameters(IEnumerable<ITypeParameterSymbol> potentialTypeParameters, IEnumerable<ISymbol> includedMembers) { var directlyReferencedTypeParameters = new List<ITypeParameterSymbol>(); foreach (var typeParameter in potentialTypeParameters) { if (includedMembers.Any(m => DoesMemberReferenceTypeParameter(m, typeParameter, new HashSet<ITypeSymbol>()))) { directlyReferencedTypeParameters.Add(typeParameter); } } return directlyReferencedTypeParameters; } private bool DoesMemberReferenceTypeParameter(ISymbol member, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; return DoesTypeReferenceTypeParameter(@event.Type, typeParameter, checkedTypes); case SymbolKind.Method: var method = member as IMethodSymbol; return method.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) || method.TypeParameters.Any(t => t.ConstraintTypes.Any(c => DoesTypeReferenceTypeParameter(c, typeParameter, checkedTypes))) || DoesTypeReferenceTypeParameter(method.ReturnType, typeParameter, checkedTypes); case SymbolKind.Property: var property = member as IPropertySymbol; return property.Parameters.Any(t => DoesTypeReferenceTypeParameter(t.Type, typeParameter, checkedTypes)) || DoesTypeReferenceTypeParameter(property.Type, typeParameter, checkedTypes); default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); return false; } } private bool DoesTypeReferenceTypeParameter(ITypeSymbol type, ITypeParameterSymbol typeParameter, HashSet<ITypeSymbol> checkedTypes) { if (!checkedTypes.Add(type)) { return false; } if (type == typeParameter || type.GetTypeArguments().Any(t => DoesTypeReferenceTypeParameter(t, typeParameter, checkedTypes))) { return true; } if (type.ContainingType != null && type.Kind != SymbolKind.TypeParameter && DoesTypeReferenceTypeParameter(type.ContainingType, typeParameter, checkedTypes)) { return true; } return false; } } }
/* ==================================================================== Copyright 2002-2004 Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.HSSF.UserModel { using System; using NPOI.HSSF.UserModel; using NPOI.HSSF.Model; using NUnit.Framework; using NPOI.SS.UserModel; [TestFixture] public class TestHSSFOptimiser { [Test] public void TestDoesNoHarmIfNothingToDo() { HSSFWorkbook wb = new HSSFWorkbook(); // New files start with 4 built in fonts, and 21 built in styles Assert.AreEqual(4, wb.NumberOfFonts); Assert.AreEqual(21, wb.NumCellStyles); // Create a test font and style, and use them IFont f = wb.CreateFont(); f.FontName = ("Testing"); NPOI.SS.UserModel.ICellStyle s = wb.CreateCellStyle(); s.SetFont(f); HSSFSheet sheet = (HSSFSheet)wb.CreateSheet(); HSSFRow row = (HSSFRow)sheet.CreateRow(0); row.CreateCell(0).CellStyle = (s); // Should have one more than the default of each Assert.AreEqual(5, wb.NumberOfFonts); Assert.AreEqual(22, wb.NumCellStyles); // Optimise fonts HSSFOptimiser.OptimiseFonts(wb); Assert.AreEqual(5, wb.NumberOfFonts); Assert.AreEqual(22, wb.NumCellStyles); Assert.AreEqual(f, s.GetFont(wb)); // Optimise styles HSSFOptimiser.OptimiseCellStyles(wb); Assert.AreEqual(5, wb.NumberOfFonts); Assert.AreEqual(22, wb.NumCellStyles); Assert.AreEqual(f, s.GetFont(wb)); } [Test] public void TestOptimiseFonts() { HSSFWorkbook wb = new HSSFWorkbook(); // Add 6 fonts, some duplicates IFont f1 = wb.CreateFont(); f1.FontHeight = ((short)11); f1.FontName = ("Testing"); IFont f2 = wb.CreateFont(); f2.FontHeight = ((short)22); f2.FontName = ("Also Testing"); IFont f3 = wb.CreateFont(); f3.FontHeight = ((short)33); f3.FontName = ("Unique"); IFont f4 = wb.CreateFont(); f4.FontHeight = ((short)11); f4.FontName = ("Testing"); IFont f5 = wb.CreateFont(); f5.FontHeight = ((short)22); f5.FontName = ("Also Testing"); IFont f6 = wb.CreateFont(); f6.FontHeight = ((short)66); f6.FontName = ("Also Unique"); // Use all three of the four in cell styles Assert.AreEqual(21, wb.NumCellStyles); NPOI.SS.UserModel.ICellStyle cs1 = wb.CreateCellStyle(); cs1.SetFont(f1); Assert.AreEqual(5, cs1.FontIndex); NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle(); cs2.SetFont(f4); Assert.AreEqual(8, cs2.FontIndex); NPOI.SS.UserModel.ICellStyle cs3 = wb.CreateCellStyle(); cs3.SetFont(f5); Assert.AreEqual(9, cs3.FontIndex); NPOI.SS.UserModel.ICellStyle cs4 = wb.CreateCellStyle(); cs4.SetFont(f6); Assert.AreEqual(10, cs4.FontIndex); Assert.AreEqual(25, wb.NumCellStyles); // And three in rich text NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); IRow r = s.CreateRow(0); HSSFRichTextString rtr1 = new HSSFRichTextString("Test"); rtr1.ApplyFont(0, 2, f1); rtr1.ApplyFont(3, 4, f2); r.CreateCell(0).SetCellValue(rtr1); HSSFRichTextString rtr2 = new HSSFRichTextString("AlsoTest"); rtr2.ApplyFont(0, 2, f3); rtr2.ApplyFont(3, 5, f5); rtr2.ApplyFont(6, 8, f6); r.CreateCell(1).SetCellValue(rtr2); // Check what we have now Assert.AreEqual(10, wb.NumberOfFonts); Assert.AreEqual(25, wb.NumCellStyles); // Optimise HSSFOptimiser.OptimiseFonts(wb); // Check font count Assert.AreEqual(8, wb.NumberOfFonts); Assert.AreEqual(25, wb.NumCellStyles); // Check font use in cell styles Assert.AreEqual(5, cs1.FontIndex); Assert.AreEqual(5, cs2.FontIndex); // duplicate of 1 Assert.AreEqual(6, cs3.FontIndex); // duplicate of 2 Assert.AreEqual(8, cs4.FontIndex); // two have gone // And in rich text // RTR 1 had f1 and f2, unchanged Assert.AreEqual(5, (r.GetCell(0).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(0)); Assert.AreEqual(5, (r.GetCell(0).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(1)); Assert.AreEqual(6, (r.GetCell(0).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(3)); Assert.AreEqual(6, (r.GetCell(0).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(4)); // RTR 2 had f3 (unchanged), f5 (=f2) and f6 (moved down) Assert.AreEqual(7, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(0)); Assert.AreEqual(7, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(1)); Assert.AreEqual(6, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(3)); Assert.AreEqual(6, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(4)); Assert.AreEqual(8, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(6)); Assert.AreEqual(8, (r.GetCell(1).RichStringCellValue as HSSFRichTextString).GetFontAtIndex(7)); } [Test] public void TestOptimiseStyles() { HSSFWorkbook wb = new HSSFWorkbook(); // Two fonts Assert.AreEqual(4, wb.NumberOfFonts); IFont f1 = wb.CreateFont(); f1.FontHeight = ((short)11); f1.FontName = ("Testing"); IFont f2 = wb.CreateFont(); f2.FontHeight = ((short)22); f2.FontName = ("Also Testing"); Assert.AreEqual(6, wb.NumberOfFonts); // Several styles Assert.AreEqual(21, wb.NumCellStyles); NPOI.SS.UserModel.ICellStyle cs1 = wb.CreateCellStyle(); cs1.SetFont(f1); NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle(); cs2.SetFont(f2); NPOI.SS.UserModel.ICellStyle cs3 = wb.CreateCellStyle(); cs3.SetFont(f1); NPOI.SS.UserModel.ICellStyle cs4 = wb.CreateCellStyle(); cs4.SetFont(f1); cs4.Alignment = HorizontalAlignment.CenterSelection;// ((short)22); NPOI.SS.UserModel.ICellStyle cs5 = wb.CreateCellStyle(); cs5.SetFont(f2); cs5.Alignment = HorizontalAlignment.Fill; //((short)111); NPOI.SS.UserModel.ICellStyle cs6 = wb.CreateCellStyle(); cs6.SetFont(f2); Assert.AreEqual(27, wb.NumCellStyles); // Use them NPOI.SS.UserModel.ISheet s = wb.CreateSheet(); IRow r = s.CreateRow(0); r.CreateCell(0).CellStyle = (cs1); r.CreateCell(1).CellStyle = (cs2); r.CreateCell(2).CellStyle = (cs3); r.CreateCell(3).CellStyle = (cs4); r.CreateCell(4).CellStyle = (cs5); r.CreateCell(5).CellStyle = (cs6); r.CreateCell(6).CellStyle = (cs1); r.CreateCell(7).CellStyle = (cs2); Assert.AreEqual(21, ((HSSFCell)r.GetCell(0)).CellValueRecord.XFIndex); Assert.AreEqual(26, ((HSSFCell)r.GetCell(5)).CellValueRecord.XFIndex); Assert.AreEqual(21, ((HSSFCell)r.GetCell(6)).CellValueRecord.XFIndex); // Optimise HSSFOptimiser.OptimiseCellStyles(wb); // Check Assert.AreEqual(6, wb.NumberOfFonts); Assert.AreEqual(25, wb.NumCellStyles); // cs1 -> 21 Assert.AreEqual(21, ((HSSFCell)r.GetCell(0)).CellValueRecord.XFIndex); // cs2 -> 22 Assert.AreEqual(22, ((HSSFCell)r.GetCell(1)).CellValueRecord.XFIndex); Assert.AreEqual(22, r.GetCell(1).CellStyle.GetFont(wb).FontHeight); // cs3 = cs1 -> 21 Assert.AreEqual(21, ((HSSFCell)r.GetCell(2)).CellValueRecord.XFIndex); // cs4 --> 24 -> 23 Assert.AreEqual(23, ((HSSFCell)r.GetCell(3)).CellValueRecord.XFIndex); // cs5 --> 25 -> 24 Assert.AreEqual(24, ((HSSFCell)r.GetCell(4)).CellValueRecord.XFIndex); // cs6 = cs2 -> 22 Assert.AreEqual(22, ((HSSFCell)r.GetCell(5)).CellValueRecord.XFIndex); // cs1 -> 21 Assert.AreEqual(21, ((HSSFCell)r.GetCell(6)).CellValueRecord.XFIndex); // cs2 -> 22 Assert.AreEqual(22, ((HSSFCell)r.GetCell(7)).CellValueRecord.XFIndex); // Add a new duplicate, and two that aren't used HSSFCellStyle csD = (HSSFCellStyle)wb.CreateCellStyle(); csD.SetFont(f1); r.CreateCell(8).CellStyle=(csD); HSSFFont f3 = (HSSFFont)wb.CreateFont(); f3.FontHeight=((short)23); f3.FontName=("Testing 3"); HSSFFont f4 = (HSSFFont)wb.CreateFont(); f4.FontHeight=((short)24); f4.FontName=("Testing 4"); HSSFCellStyle csU1 = (HSSFCellStyle)wb.CreateCellStyle(); csU1.SetFont(f3); HSSFCellStyle csU2 = (HSSFCellStyle)wb.CreateCellStyle(); csU2.SetFont(f4); // Check before the optimise Assert.AreEqual(8, wb.NumberOfFonts); Assert.AreEqual(28, wb.NumCellStyles); // Optimise, should remove the two un-used ones and the one duplicate HSSFOptimiser.OptimiseCellStyles(wb); // Check Assert.AreEqual(8, wb.NumberOfFonts); Assert.AreEqual(25, wb.NumCellStyles); // csD -> cs1 -> 21 Assert.AreEqual(21, ((HSSFCell)r.GetCell(8)).CellValueRecord.XFIndex); } [Test] public void TestOptimiseStylesCheckActualStyles() { HSSFWorkbook wb = new HSSFWorkbook(); // Several styles Assert.AreEqual(21, wb.NumCellStyles); HSSFCellStyle cs1 = (HSSFCellStyle)wb.CreateCellStyle(); cs1.BorderBottom=(BorderStyle.Thick); HSSFCellStyle cs2 = (HSSFCellStyle)wb.CreateCellStyle(); cs2.BorderBottom=(BorderStyle.DashDot); HSSFCellStyle cs3 = (HSSFCellStyle)wb.CreateCellStyle(); // = cs1 cs3.BorderBottom=(BorderStyle.Thick); Assert.AreEqual(24, wb.NumCellStyles); // Use them HSSFSheet s = (HSSFSheet)wb.CreateSheet(); HSSFRow r = (HSSFRow)s.CreateRow(0); r.CreateCell(0).CellStyle=(cs1); r.CreateCell(1).CellStyle=(cs2); r.CreateCell(2).CellStyle=(cs3); Assert.AreEqual(21, ((HSSFCell)r.GetCell(0)).CellValueRecord.XFIndex); Assert.AreEqual(22, ((HSSFCell)r.GetCell(1)).CellValueRecord.XFIndex); Assert.AreEqual(23, ((HSSFCell)r.GetCell(2)).CellValueRecord.XFIndex); // Optimise HSSFOptimiser.OptimiseCellStyles(wb); // Check Assert.AreEqual(23, wb.NumCellStyles); Assert.AreEqual(BorderStyle.Thick, r.GetCell(0).CellStyle.BorderBottom); Assert.AreEqual(BorderStyle.DashDot, r.GetCell(1).CellStyle.BorderBottom); Assert.AreEqual(BorderStyle.Thick, r.GetCell(2).CellStyle.BorderBottom); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; using Xunit; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; using System.Threading; namespace BasicEventSourceTests { /// <summary> /// Tests the user experience for common user errors. /// </summary> public class TestsUserErrors { /// <summary> /// Try to pass a user defined class (even with EventData) /// to a manifest based eventSource /// </summary> [Fact] public void Test_BadTypes_Manifest_UserClass() { var badEventSource = new BadEventSource_Bad_Type_UserClass(); Test_BadTypes_Manifest(badEventSource); } private void Test_BadTypes_Manifest(EventSource source) { try { using (var listener = new EventListenerListener()) { var events = new List<Event>(); Debug.WriteLine("Adding delegate to onevent"); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(source.Name, EventCommand.Enable); listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(events.Count, 1); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); // Check the exception text if not ProjectN. if (!PlatformDetection.IsNetNative) { string message = _event.PayloadString(0, "message"); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. " Assert.True(Regex.IsMatch(message, "Unsupported type")); } } } finally { source.Dispose(); } } /// <summary> /// Test the /// </summary> [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Depends on inspecting IL at runtime.")] public void Test_BadEventSource_MismatchedIds() { #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. // We expect only one session to be on when running the test but if a ETW session was left // hanging, it will confuse the EventListener tests. EtwListener.EnsureStopped(); #endif // USE_ETW TestUtilities.CheckNoEventSourcesRunning("Start"); var onStartups = new bool[] { false, true }; var listenerGenerators = new Func<Listener>[] { () => new EventListenerListener(), #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. () => new EtwListener() #endif // USE_ETW }; var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat }; // For every interesting combination, run the test and see that we get a nice failure message. foreach (bool onStartup in onStartups) { foreach (Func<Listener> listenerGenerator in listenerGenerators) { foreach (EventSourceSettings setting in settings) { Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting); } } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } /// <summary> /// A helper that can run the test under a variety of conditions /// * Whether the eventSource is enabled at startup /// * Whether the listener is ETW or an EventListern /// * Whether the ETW output is self describing or not. /// </summary> private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings) { var eventSourceName = typeof(BadEventSource_MismatchedIds).Name; Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")"); // Activate the source before the source exists (if told to). if (onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; using (var source = new BadEventSource_MismatchedIds(settings)) { Assert.Equal(eventSourceName, source.Name); // activate the source after the source exists (if told to). if (!onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); source.Event1(1); // Try to send something. } listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(events.Count, 1); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); Debug.WriteLine(String.Format("Message=\"{0}\"", message)); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 is given event ID 2 but 1 was passed to WriteEvent. " Assert.True(Regex.IsMatch(message, "Event Event2 is givien event ID 2 but 1 was passed to WriteEvent")); } [Fact] public void Test_Bad_WriteRelatedID_ParameterName() { #if true Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet."); #else BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null; EventListenerListener listener = null; try { Guid oldGuid; Guid newGuid = Guid.NewGuid(); Guid newGuid2 = Guid.NewGuid(); EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid); bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter(); using (var listener = new EventListenerListener()) { var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(bes.Name, EventCommand.Enable); bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB"); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(events.Count, 1); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId." Assert.True(Regex.IsMatch(message, "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId.")); } } finally { if (bes != null) { bes.Dispose(); } if (listener != null) { listener.Dispose(); } } #endif } } /// <summary> /// This EventSource has a common user error, and we want to make sure EventSource /// gives a reasonable experience in that case. /// </summary> internal class BadEventSource_MismatchedIds : EventSource { public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { } public void Event1(int arg) { WriteEvent(1, arg); } // Error Used the same event ID for this event. public void Event2(int arg) { WriteEvent(1, arg); } } /// <summary> /// A manifest based provider with a bad type byte[] /// </summary> internal class BadEventSource_Bad_Type_ByteArray : EventSource { public void Event1(byte[] myArray) { WriteEvent(1, myArray); } } public sealed class BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter : EventSource { public void E2() { this.Write("sampleevent", new { a = "a string" }); } [Event(7, Keywords = Keywords.Debug, Message = "Hello Message 7", Channel = EventChannel.Admin, Opcode = EventOpcode.Send)] public void RelatedActivity(Guid guid, string message, int value, string componentName, string instanceId) { WriteEventWithRelatedActivityId(7, guid, message, value, componentName, instanceId); } public class Keywords { public const EventKeywords Debug = (EventKeywords)0x0002; } } [EventData] public class UserClass { public int i; }; /// <summary> /// A manifest based provider with a bad type (only supported in self describing) /// </summary> internal class BadEventSource_Bad_Type_UserClass : EventSource { public void Event1(UserClass myClass) { WriteEvent(1, myClass); } } }
using UnityEngine; using System.Collections; namespace WingroveAudio { public class ActiveCue : MonoBehaviour { public enum CueState { Initial, PlayingFadeIn, Playing, PlayingFadeOut } private GameObject m_originatorSource; private BaseWingroveAudioSource m_audioClipSource; private GameObject m_targetGameObject; private bool m_hasTarget; private double m_dspStartTime = 0.0f; private bool m_hasDSPStartTime = false; public void Initialise(GameObject originator, GameObject target) { m_originatorSource = originator; m_targetGameObject = target; m_hasTarget = (target != null); m_audioClipSource = m_originatorSource.GetComponent<BaseWingroveAudioSource>(); m_pitch = m_audioClipSource.GetNewPitch(); m_audioClipSource.AddUsage(); transform.parent = m_originatorSource.transform; Update(); } void OnDestroy() { if (m_currentAudioSource != null) { WingroveRoot.Instance.UnlinkSource(m_currentAudioSource); m_currentAudioSource = null; } m_audioClipSource.RemoveUsage(); } public GameObject GetOriginatorSource() { return m_originatorSource; } public GameObject GetTargetObject() { return m_targetGameObject; } public int GetImportance() { return m_audioClipSource.GetImportance(); } public float m_fadeT; public float m_fadeSpeed; CueState m_currentState; bool m_isPaused; int m_currentPosition; float m_pitch; public WingroveRoot.AudioSourcePoolItem m_currentAudioSource; float[] m_bufferDataL = new float[512]; float[] m_bufferDataR = new float[512]; private float m_rms; private bool m_rmsRequested; private bool m_hasStartedEver = false; void Update() { bool queueEnableAndPlay = false; if (m_currentAudioSource == null) { // don't bother stealing if we're going to be silent anyway... if (GetTheoreticalVolume() > 0) { m_currentAudioSource = WingroveRoot.Instance.TryClaimPoolSource(this); } if (m_currentAudioSource != null) { m_currentAudioSource.m_audioSource.clip = m_audioClipSource.GetAudioClip(); if (!m_isPaused) { m_currentAudioSource.m_audioSource.loop = m_audioClipSource.GetLooping(); queueEnableAndPlay = true; } } else { if (!m_isPaused) { if (m_hasStartedEver) { m_currentPosition += (int)(WingroveRoot.GetDeltaTime() * m_audioClipSource.GetAudioClip().frequency * GetMixPitch()); } if (m_currentPosition > m_audioClipSource.GetAudioClip().samples) { if (m_audioClipSource.GetLooping()) { m_currentPosition -= m_audioClipSource.GetAudioClip().samples; } else { StopInternal(); } } } } } else { if (!m_isPaused) { m_currentPosition = m_currentAudioSource.m_audioSource.timeSamples; } } if (!m_isPaused) { switch (m_currentState) { case CueState.Initial: break; case CueState.Playing: m_fadeT = 1; break; case CueState.PlayingFadeIn: m_fadeT += m_fadeSpeed * WingroveRoot.GetDeltaTime(); if (m_fadeT >= 1) { m_fadeT = 1.0f; m_currentState = CueState.Playing; } break; case CueState.PlayingFadeOut: m_fadeT -= m_fadeSpeed * WingroveRoot.GetDeltaTime(); if (m_fadeT <= 0) { m_fadeT = 0.0f; StopInternal(); // early return!!!! return; } break; } if (!m_audioClipSource.GetLooping()) { if (m_currentPosition > m_audioClipSource.GetAudioClip().samples - 1000) { StopInternal(); return; } } } SetMix(); if (queueEnableAndPlay) { if (m_currentAudioSource != null) { m_currentAudioSource.m_audioSource.enabled = true; m_currentAudioSource.m_audioSource.timeSamples = m_currentPosition; Audio3DSetting settings = m_audioClipSource.Get3DSettings(); if (settings == null) { WingroveRoot.Instance.SetDefault3DSettings(m_currentAudioSource.m_audioSource); } else { AudioRolloffMode rolloffMode = settings.GetRolloffMode(); if ( rolloffMode != AudioRolloffMode.Custom ) { m_currentAudioSource.m_audioSource.rolloffMode = rolloffMode; m_currentAudioSource.m_audioSource.minDistance = settings.GetMinDistance(); m_currentAudioSource.m_audioSource.maxDistance = settings.GetMaxDistance(); } else { m_currentAudioSource.m_audioSource.rolloffMode = AudioRolloffMode.Linear; m_currentAudioSource.m_audioSource.minDistance = float.MaxValue; m_currentAudioSource.m_audioSource.maxDistance = float.MaxValue; } } if ((m_hasDSPStartTime) && (m_dspStartTime > AudioSettings.dspTime)) { m_currentAudioSource.m_audioSource.timeSamples = m_currentPosition = 0; m_currentAudioSource.m_audioSource.PlayScheduled(m_dspStartTime); } else { m_currentAudioSource.m_audioSource.Play(); } } } m_hasStartedEver = true; } public float GetTheoreticalVolume() { if (m_isPaused) { return 0; } else { float v3D = 1.0f; return m_fadeT * m_audioClipSource.GetMixBusLevel() * v3D; } } public float GetMixPitch() { return m_pitch * m_audioClipSource.GetPitchModifier(m_targetGameObject); } public float ApplyCustom3DCurve(float distance) { Audio3DSetting settings = m_audioClipSource.Get3DSettings(); if (settings != null) { if (settings.GetRolloffMode() == AudioRolloffMode.Custom) { return settings.EvaluateCustom(distance); } } return 1.0f; } public void SetMix() { if (m_currentAudioSource != null) { if (m_audioClipSource.GetPositioningType() == BaseWingroveAudioSource.PositioningType.UnityDefault3d2d) { if (m_targetGameObject != null) { m_currentAudioSource.m_audioSource.transform.position = WingroveRoot.Instance.GetRelativeListeningPosition(m_targetGameObject.transform.position); } else { // don't snap back to origin when object destroyed if (!m_hasTarget) { m_currentAudioSource.m_audioSource.transform.position = Vector3.zero; } } } else { m_currentAudioSource.m_audioSource.transform.position = Vector3.zero; } // apply the full mix, including custom rolloff m_currentAudioSource.m_audioSource.volume = m_fadeT * m_audioClipSource.GetMixBusLevel() * m_audioClipSource.GetVolumeModifier(m_targetGameObject) * ApplyCustom3DCurve( m_currentAudioSource.m_audioSource.transform.position.magnitude); m_currentAudioSource.m_audioSource.pitch = GetMixPitch(); if (WingroveRoot.Instance.ShouldCalculateMS(m_currentAudioSource.m_index)) { if (m_rmsRequested) { float rms = 0; if (m_audioClipSource.GetAudioClip().channels == 2) { m_currentAudioSource.m_audioSource.GetOutputData(m_bufferDataL, 0); m_currentAudioSource.m_audioSource.GetOutputData(m_bufferDataR, 1); for (int index = 0; index < 512; ++index) { rms += (Mathf.Abs(m_bufferDataR[index]) + Mathf.Abs(m_bufferDataL[index])) * (Mathf.Abs(m_bufferDataR[index]) + Mathf.Abs(m_bufferDataL[index])); } } else { m_currentAudioSource.m_audioSource.GetOutputData(m_bufferDataL, 0); for (int index = 0; index < 512; ++index) { rms += (m_bufferDataL[index] * m_bufferDataL[index]); } } rms = Mathf.Sqrt(Mathf.Clamp01(rms / 512.0f)); m_rms = Mathf.Max(rms * m_fadeT * m_audioClipSource.GetMixBusLevel(), m_rms * 0.9f);// ((m_rms * 2 + rms) / 3.0f) * m_fadeT * m_audioClipSource.GetMixBusLevel(); } m_rmsRequested = false; } } else { m_rms = 0; } } public float GetRMS() { m_rmsRequested = true; return m_rms; } public void Play(float fade) { m_currentPosition = 0; if (m_currentAudioSource != null) { m_currentAudioSource.m_audioSource.timeSamples = 0; } if (fade == 0.0f) { m_currentState = CueState.Playing; } else { m_currentState = CueState.PlayingFadeIn; m_fadeSpeed = 1.0f / fade; } } public void Play(float fade, double dspStartTime) { m_currentPosition = 0; m_hasDSPStartTime = true; m_dspStartTime = dspStartTime; if (m_currentAudioSource != null) { m_currentAudioSource.m_audioSource.timeSamples = 0; } if (fade == 0.0f) { m_currentState = CueState.Playing; } else { m_currentState = CueState.PlayingFadeIn; m_fadeSpeed = 1.0f / fade; } } public float GetTime() { float currentTime = (m_currentPosition) / (float)(m_audioClipSource.GetAudioClip().frequency * GetMixPitch()); return currentTime; } public float GetTimeUntilFinished(WingroveGroupInformation.HandleRepeatingAudio handleRepeat) { float timeRemaining = (m_audioClipSource.GetAudioClip().samples - m_currentPosition) / (float)(m_audioClipSource.GetAudioClip().frequency * GetMixPitch()); if (m_audioClipSource.GetLooping()) { switch(handleRepeat) { case WingroveGroupInformation.HandleRepeatingAudio.IgnoreRepeatingAudio: timeRemaining = 0.0f; break; case WingroveGroupInformation.HandleRepeatingAudio.ReturnFloatMax: case WingroveGroupInformation.HandleRepeatingAudio.ReturnNegativeOne: timeRemaining = float.MaxValue; break; case WingroveGroupInformation.HandleRepeatingAudio.GiveTimeUntilLoop: default: break; } } if (m_currentState == CueState.PlayingFadeOut) { if (m_fadeSpeed != 0) { timeRemaining = Mathf.Min(m_fadeT / m_fadeSpeed, timeRemaining); } } return timeRemaining; } public void Stop(float fade) { if (fade == 0.0f) { StopInternal(); } else { m_currentState = CueState.PlayingFadeOut; m_fadeSpeed = 1.0f / fade; } } void StopInternal() { Unlink(); } public void Unlink() { if (m_currentAudioSource != null) { WingroveRoot.Instance.UnlinkSource(m_currentAudioSource); m_currentAudioSource = null; } GameObject.Destroy(gameObject); } public void Virtualise() { if (m_currentAudioSource != null) { WingroveRoot.Instance.UnlinkSource(m_currentAudioSource); m_currentAudioSource = null; } } public void Pause() { if (!m_isPaused) { if (m_currentAudioSource != null) { m_currentAudioSource.m_audioSource.Pause(); } } m_isPaused = true; } public void Unpause() { if (m_isPaused) { if (m_currentAudioSource != null) { m_currentAudioSource.m_audioSource.Play(); } } m_isPaused = false; } public CueState GetState() { return m_currentState; } } }
using De.Osthus.Ambeth.Util; using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace De.Osthus.Ambeth.Collections { public abstract class AbstractTuple2KeyHashMap<Key1, Key2, V> : IPrintable, Iterable<Tuple2KeyEntry<Key1, Key2, V>> { public static readonly int DEFAULT_INITIAL_CAPACITY = 16; public static readonly int MAXIMUM_CAPACITY = 1 << 30; public static readonly float DEFAULT_LOAD_FACTOR = 0.75f; protected readonly float loadFactor; protected int threshold; protected Tuple2KeyEntry<Key1, Key2, V>[] table; public AbstractTuple2KeyHashMap(int initialCapacity, float loadFactor) { this.loadFactor = loadFactor; if (initialCapacity < 0) { throw new ArgumentException("Illegal initial capacity: " + initialCapacity); } if (initialCapacity > MAXIMUM_CAPACITY) { initialCapacity = MAXIMUM_CAPACITY; } if (loadFactor <= 0 || Single.IsNaN(loadFactor)) { throw new ArgumentException("Illegal load factor: " + loadFactor); } // Find a power of 2 >= initialCapacity int capacity = 1; while (capacity < initialCapacity) { capacity <<= 1; } threshold = (int)(capacity * loadFactor); table = CreateTable(capacity); Init(); } protected Tuple2KeyEntry<Key1, Key2, V>[] CreateTable(int capacity) { return new Tuple2KeyEntry<Key1, Key2, V>[capacity]; } protected virtual void Init() { } protected virtual int ExtractHash(Key1 key1, Key2 key2) { return (key1 != null ? key1.GetHashCode() : 3) ^ (key2 != null ? key2.GetHashCode() : 5); } protected static int Hash(int hash) { uint uhash = (uint)hash; uhash += ~(uhash << 9); uhash ^= uhash >> 14; uhash += uhash << 4; uhash ^= uhash >> 10; return (int)uhash; } protected void AddEntry(int hash, Key1 key1, Key2 key2, V value, int bucketIndex) { Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; Tuple2KeyEntry<Key1, Key2, V> e = table[bucketIndex]; e = CreateEntry(hash, key1, key2, value, e); table[bucketIndex] = e; EntryAdded(e); if (Count >= threshold) { Resize(2 * table.Length); } } protected virtual void EntryAdded(Tuple2KeyEntry<Key1, Key2, V> entry) { // Intended blank } protected virtual void EntryRemoved(Tuple2KeyEntry<Key1, Key2, V> entry) { // Intended blank } /** * Rehashes the contents of this map into a new array with a larger capacity. This method is called automatically when the number of keys in this map * reaches its threshold. If current capacity is MAXIMUM_CAPACITY, this method does not resize the map, but sets threshold to Integer.MAX_VALUE. This has * the effect of preventing future calls. * * @param newCapacity * the new capacity, MUST be a power of two; must be greater than current capacity unless current capacity is MAXIMUM_CAPACITY (in which case * value is irrelevant). */ protected virtual void Resize(int newCapacity) { Tuple2KeyEntry<Key1, Key2, V>[] oldTable = table; int oldCapacity = oldTable.Length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Int32.MaxValue; return; } Tuple2KeyEntry<Key1, Key2, V>[] newTable = CreateTable(newCapacity); Transfer(newTable); table = newTable; threshold = (int)(newCapacity * loadFactor); } protected virtual void Transfer(Tuple2KeyEntry<Key1, Key2, V>[] newTable) { int newCapacityMinus1 = newTable.Length - 1; Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; for (int a = table.Length; a-- > 0; ) { Tuple2KeyEntry<Key1, Key2, V> entry = table[a], next; while (entry != null) { next = entry.GetNextEntry(); int i = entry.GetHash() & newCapacityMinus1; entry.SetNextEntry(newTable[i]); newTable[i] = entry; entry = next; } } } public V[] ToArray(V[] targetArray) { int index = 0; Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; for (int a = table.Length; a-- > 0; ) { Tuple2KeyEntry<Key1, Key2, V> entry = table[a]; while (entry != null) { targetArray[index++] = entry.GetValue(); entry = entry.GetNextEntry(); } } return targetArray; } public void Clear() { if (IsEmpty) { return; } Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; for (int a = table.Length; a-- > 0; ) { Tuple2KeyEntry<Key1, Key2, V> entry = table[a]; if (entry != null) { table[a] = null; while (entry != null) { Tuple2KeyEntry<Key1, Key2, V> nextEntry = entry.GetNextEntry(); EntryRemoved(entry); entry = nextEntry; } } } } public bool ContainsKey(Key1 key1, Key2 key2) { int hash = Hash(ExtractHash(key1, key2)); Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; int i = hash & (table.Length - 1); Tuple2KeyEntry<Key1, Key2, V> entry = table[i]; while (entry != null) { if (EqualKeys(key1, key2, entry)) { return true; } entry = entry.GetNextEntry(); } return false; } /** * @see java.util.Map#containsValue(java.lang.Object) */ public bool ContainsValue(V value) { Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; if (value == null) { for (int a = table.Length; a-- > 0; ) { Tuple2KeyEntry<Key1, Key2, V> entry = table[a]; while (entry != null) { Object entryValue = entry.GetValue(); if (entryValue == null) { return true; } entry = entry.GetNextEntry(); } } } else { for (int a = table.Length; a-- > 0; ) { Tuple2KeyEntry<Key1, Key2, V> entry = table[a]; while (entry != null) { Object entryValue = entry.GetValue(); if (value.Equals(entryValue)) { return true; } entry = entry.GetNextEntry(); } } } return false; } protected virtual bool EqualKeys(Key1 key1, Key2 key2, Tuple2KeyEntry<Key1, Key2, V> entry) { return Object.Equals(key1, entry.GetKey1()) && Object.Equals(key2, entry.GetKey2()); } public V Put(Key1 key1, Key2 key2, V value) { int hash = Hash(ExtractHash(key1, key2)); Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; int i = hash & (table.Length - 1); Tuple2KeyEntry<Key1, Key2, V> entry = table[i]; while (entry != null) { if (EqualKeys(key1, key2, entry)) { if (IsSetValueForEntryAllowed()) { return SetValueForEntry(entry, value); } V oldValue = entry.GetValue(); RemoveEntryForKey(key1, key2); AddEntry(hash, key1, key2, value, i); return oldValue; } entry = entry.GetNextEntry(); } AddEntry(hash, key1, key2, value, i); return default(V); } public bool PutIfNotExists(Key1 key1, Key2 key2, V value) { int hash = Hash(ExtractHash(key1, key2)); Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; int i = hash & (table.Length - 1); Tuple2KeyEntry<Key1, Key2, V> entry = table[i]; while (entry != null) { if (EqualKeys(key1, key2, entry)) { return false; } entry = entry.GetNextEntry(); } AddEntry(hash, key1, key2, value, i); return true; } public bool RemoveIfValue(Key1 key1, Key2 key2, V value) { int hash = Hash(ExtractHash(key1, key2)); Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; int i = hash & (table.Length - 1); Tuple2KeyEntry<Key1, Key2, V> entry = table[i]; if (entry != null) { if (EqualKeys(key1, key2, entry)) { table[i] = entry.GetNextEntry(); V existingValue = entry.GetValue(); if (!Object.ReferenceEquals(existingValue, value)) // Test if reference identical { return false; } EntryRemoved(entry); return true; } Tuple2KeyEntry<Key1, Key2, V> prevEntry = entry; entry = entry.GetNextEntry(); while (entry != null) { if (EqualKeys(key1, key2, entry)) { prevEntry.SetNextEntry(entry.GetNextEntry()); V existingValue = entry.GetValue(); if (!Object.ReferenceEquals(existingValue, value)) // Test if reference identical { return false; } EntryRemoved(entry); return true; } prevEntry = entry; entry = entry.GetNextEntry(); } } return false; } public V Remove(Key1 key1, Key2 key2) { return RemoveEntryForKey(key1, key2); } protected V RemoveEntryForKey(Key1 key1, Key2 key2) { int hash = Hash(ExtractHash(key1, key2)); Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; int i = hash & (table.Length - 1); Tuple2KeyEntry<Key1, Key2, V> entry = table[i]; if (entry != null) { if (EqualKeys(key1, key2, entry)) { table[i] = entry.GetNextEntry(); V value = entry.GetValue(); EntryRemoved(entry); return value; } Tuple2KeyEntry<Key1, Key2, V> prevEntry = entry; entry = entry.GetNextEntry(); while (entry != null) { if (EqualKeys(key1, key2, entry)) { prevEntry.SetNextEntry(entry.GetNextEntry()); V value = entry.GetValue(); EntryRemoved(entry); return value; } prevEntry = entry; entry = entry.GetNextEntry(); } } return default(V); } public V Get(Key1 key1, Key2 key2) { int hash = Hash(ExtractHash(key1, key2)); Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; int i = hash & (table.Length - 1); Tuple2KeyEntry<Key1, Key2, V> entry = table[i]; while (entry != null) { if (EqualKeys(key1, key2, entry)) { return entry.GetValue(); } entry = entry.GetNextEntry(); } return default(V); } protected virtual bool IsSetValueForEntryAllowed() { return true; } protected V SetValueForEntry(Tuple2KeyEntry<Key1, Key2, V> entry, V value) { V oldValue = entry.GetValue(); entry.SetValue(value); return oldValue; } protected abstract Tuple2KeyEntry<Key1, Key2, V> CreateEntry(int hash, Key1 key1, Key2 key2, V value, Tuple2KeyEntry<Key1, Key2, V> nextEntry); public abstract int Count { get; } public bool IsEmpty { get { return Count == 0; } } public Iterator<Tuple2KeyEntry<Key1, Key2, V>> Iterator() { return new Tuple2KeyIterator<Key1, Key2, V>(this, table, true); } public Iterator<Tuple2KeyEntry<Key1, Key2, V>> Iterator(bool removeAllowed) { return new Tuple2KeyIterator<Key1, Key2, V>(this, table, removeAllowed); } public IList<V> Values() { Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; List<V> valueList = new List<V>(Count); for (int a = table.Length; a-- > 0; ) { Tuple2KeyEntry<Key1, Key2, V> entry = table[a]; while (entry != null) { valueList.Add(entry.GetValue()); entry = entry.GetNextEntry(); } } return valueList; } public override String ToString() { StringBuilder sb = new StringBuilder(); ToString(sb); return sb.ToString(); } public void ToString(StringBuilder sb) { sb.Append(Count).Append(" items: ["); bool first = true; Tuple2KeyEntry<Key1, Key2, V>[] table = this.table; for (int a = table.Length; a-- > 0; ) { Tuple2KeyEntry<Key1, Key2, V> entry = table[a]; while (entry != null) { if (first) { first = false; } else { sb.Append(','); } StringBuilderUtil.AppendPrintable(sb, entry); entry = entry.GetNextEntry(); } } sb.Append(']'); } public IEnumerator<Tuple2KeyEntry<Key1, Key2, V>> GetEnumerator() { return Iterator(); } IEnumerator IEnumerable.GetEnumerator() { return Iterator(); } Iterator Iterable.Iterator() { return Iterator(); } Iterator Iterable.Iterator(bool removeAllowed) { return Iterator(removeAllowed); } } }
// 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; namespace System.Data.SqlTypes { /// <devdoc> /// <para> /// Represents a globally unique identifier to be stored in /// or retrieved from a database. /// </para> /// </devdoc> public struct SqlGuid : INullable, IComparable { private static readonly int s_sizeOfGuid = 16; // Comparison orders. private static readonly int[] s_rgiGuidOrder = new int[16] {10, 11, 12, 13, 14, 15, 8, 9, 6, 7, 4, 5, 0, 1, 2, 3}; private byte[] _value; // the SqlGuid is null if m_value is null // constructor // construct a SqlGuid.Null private SqlGuid(bool fNull) { _value = null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SqlGuid(byte[] value) { if (value == null || value.Length != s_sizeOfGuid) throw new ArgumentException(SQLResource.InvalidArraySizeMessage); _value = new byte[s_sizeOfGuid]; value.CopyTo(_value, 0); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal SqlGuid(byte[] value, bool ignored) { if (value == null || value.Length != s_sizeOfGuid) throw new ArgumentException(SQLResource.InvalidArraySizeMessage); _value = value; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SqlGuid(String s) { _value = (new Guid(s)).ToByteArray(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SqlGuid(Guid g) { _value = g.ToByteArray(); } public SqlGuid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) : this(new Guid(a, b, c, d, e, f, g, h, i, j, k)) { } // INullable /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsNull { get { return (_value == null); } } // property: Value /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Guid Value { get { if (IsNull) throw new SqlNullValueException(); else return new Guid(_value); } } // Implicit conversion from Guid to SqlGuid /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static implicit operator SqlGuid(Guid x) { return new SqlGuid(x); } // Explicit conversion from SqlGuid to Guid. Throw exception if x is Null. /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator Guid(SqlGuid x) { return x.Value; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public byte[] ToByteArray() { byte[] ret = new byte[s_sizeOfGuid]; _value.CopyTo(ret, 0); return ret; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override String ToString() { if (IsNull) return SQLResource.NullString; Guid g = new Guid(_value); return g.ToString(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlGuid Parse(String s) { if (s == SQLResource.NullString) return SqlGuid.Null; else return new SqlGuid(s); } // Comparison operators private static EComparison Compare(SqlGuid x, SqlGuid y) { //Swap to the correct order to be compared for (int i = 0; i < s_sizeOfGuid; i++) { byte b1, b2; b1 = x._value[s_rgiGuidOrder[i]]; b2 = y._value[s_rgiGuidOrder[i]]; if (b1 != b2) return (b1 < b2) ? EComparison.LT : EComparison.GT; } return EComparison.EQ; } // Implicit conversions // Explicit conversions // Explicit conversion from SqlString to SqlGuid /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlGuid(SqlString x) { return x.IsNull ? Null : new SqlGuid(x.Value); } // Explicit conversion from SqlBinary to SqlGuid /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static explicit operator SqlGuid(SqlBinary x) { return x.IsNull ? Null : new SqlGuid(x.Value); } // Overloading comparison operators /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator ==(SqlGuid x, SqlGuid y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.EQ); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator !=(SqlGuid x, SqlGuid y) { return !(x == y); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator <(SqlGuid x, SqlGuid y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.LT); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator >(SqlGuid x, SqlGuid y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(Compare(x, y) == EComparison.GT); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator <=(SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; EComparison cmp = Compare(x, y); return new SqlBoolean(cmp == EComparison.LT || cmp == EComparison.EQ); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static SqlBoolean operator >=(SqlGuid x, SqlGuid y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; EComparison cmp = Compare(x, y); return new SqlBoolean(cmp == EComparison.GT || cmp == EComparison.EQ); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator == public static SqlBoolean Equals(SqlGuid x, SqlGuid y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlGuid x, SqlGuid y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlGuid x, SqlGuid y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlGuid x, SqlGuid y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlGuid x, SqlGuid y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlGuid x, SqlGuid y) { return (x >= y); } // Alternative method for conversions. public SqlString ToSqlString() { return (SqlString)this; } public SqlBinary ToSqlBinary() { return (SqlBinary)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 SqlGuid) { SqlGuid i = (SqlGuid)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlGuid)); } public int CompareTo(SqlGuid 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 < value) return -1; if (this > value) 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 SqlGuid)) { return false; } SqlGuid i = (SqlGuid)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>[To be supplied.]</para> /// </devdoc> public static readonly SqlGuid Null = new SqlGuid(true); } // SqlGuid } // namespace System.Data.SqlTypes
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using OpenMetaverse; using OpenMetaverse.Packets; namespace OpenSim.Framework { #region Client API Delegate definitions public delegate void ViewerEffectEventHandler(IClientAPI sender, List<ViewerEffectEventHandlerArg> args); public delegate void ChatMessage(Object sender, OSChatMessage e); public delegate void GenericMessage(Object sender, string method, List<String> args); public delegate void TextureRequest(Object sender, TextureRequestArgs e); public delegate void AvatarNowWearing(Object sender, AvatarWearingArgs e); public delegate void ImprovedInstantMessage(IClientAPI remoteclient, GridInstantMessage im); public delegate void RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID); public delegate UUID RezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt); public delegate void RezMultipleAttachmentsFromInv(IClientAPI remoteClient, RezMultipleAttachmentsFromInvPacket.HeaderDataBlock header, RezMultipleAttachmentsFromInvPacket.ObjectDataBlock[] objects); public delegate void ObjectAttach( IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent); public delegate void ModifyTerrain(UUID user, float height, float seconds, byte size, byte action, float north, float west, float south, float east, UUID agentId); public delegate void NetworkStats(int inPackets, int outPackets, int unAckedBytes); public delegate void SetAppearance(byte[] texture, List<byte> visualParamList); public delegate void StartAnim(IClientAPI remoteClient, UUID animID); public delegate void StopAnim(IClientAPI remoteClient, UUID animID); public delegate void LinkObjects(IClientAPI remoteClient, uint parent, List<uint> children); public delegate void DelinkObjects(List<uint> primIds); public delegate void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag); public delegate void RequestMapName(IClientAPI remoteClient, string mapName); public delegate void TeleportLocationRequest( IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags); public delegate void TeleportLandmarkRequest( IClientAPI remoteClient, UUID regionID, Vector3 position); public delegate void DisconnectUser(); public delegate void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID); public delegate void UpdateAvatarProperties(IClientAPI remoteClient, UserProfileData ProfileData); public delegate void SetAlwaysRun(IClientAPI remoteClient, bool SetAlwaysRun); public delegate void GenericCall2(); // really don't want to be passing packets in these events, so this is very temporary. public delegate void GenericCall4(Packet packet, IClientAPI remoteClient); public delegate void DeRezObject( IClientAPI remoteClient, List<uint> localIDs, UUID groupID, DeRezAction action, UUID destinationID); public delegate void GenericCall5(IClientAPI remoteClient, bool status); public delegate void GenericCall7(IClientAPI remoteClient, uint localID, string message); public delegate void UpdateShape(UUID agentID, uint localID, UpdateShapeArgs shapeBlock); public delegate void ObjectExtraParams(UUID agentID, uint localID, ushort type, bool inUse, byte[] data); public delegate void ObjectSelect(uint localID, IClientAPI remoteClient); public delegate void ObjectRequest(uint localID, IClientAPI remoteClient); public delegate void RequestObjectPropertiesFamily( IClientAPI remoteClient, UUID AgentID, uint RequestFlags, UUID TaskID); public delegate void ObjectDeselect(uint localID, IClientAPI remoteClient); public delegate void ObjectDrop(uint localID, IClientAPI remoteClient); public delegate void UpdatePrimFlags( uint localID, bool UsePhysics, bool IsTemporary, bool IsPhantom, IClientAPI remoteClient); public delegate void UpdatePrimTexture(uint localID, byte[] texture, IClientAPI remoteClient); public delegate void UpdateVector(uint localID, Vector3 pos, IClientAPI remoteClient); public delegate void UpdatePrimRotation(uint localID, Quaternion rot, IClientAPI remoteClient); public delegate void UpdatePrimSingleRotation(uint localID, Quaternion rot, IClientAPI remoteClient); public delegate void UpdatePrimSingleRotationPosition(uint localID, Quaternion rot, Vector3 pos, IClientAPI remoteClient); public delegate void UpdatePrimGroupRotation(uint localID, Vector3 pos, Quaternion rot, IClientAPI remoteClient); public delegate void ObjectDuplicate(uint localID, Vector3 offset, uint dupeFlags, UUID AgentID, UUID GroupID); public delegate void ObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID, UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart, bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates); public delegate void StatusChange(bool status); public delegate void NewAvatar(IClientAPI remoteClient, UUID agentID, bool status); public delegate void UpdateAgent(IClientAPI remoteClient, AgentUpdateArgs agentData); public delegate void AgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset); public delegate void AgentSit(IClientAPI remoteClient, UUID agentID); public delegate void AvatarPickerRequest(IClientAPI remoteClient, UUID agentdata, UUID queryID, string UserQuery); public delegate void GrabObject( uint localID, Vector3 pos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs); public delegate void DeGrabObject( uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs); public delegate void MoveObject( UUID objectID, Vector3 offset, Vector3 grapPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs); public delegate void SpinStart(UUID objectID, IClientAPI remoteClient); public delegate void SpinObject(UUID objectID, Quaternion rotation, IClientAPI remoteClient); public delegate void SpinStop(UUID objectID, IClientAPI remoteClient); public delegate void ParcelAccessListRequest( UUID agentID, UUID sessionID, uint flags, int sequenceID, int landLocalID, IClientAPI remote_client); public delegate void ParcelAccessListUpdateRequest( UUID agentID, UUID sessionID, uint flags, int landLocalID, List<ParcelManager.ParcelAccessEntry> entries, IClientAPI remote_client); public delegate void ParcelPropertiesRequest( int start_x, int start_y, int end_x, int end_y, int sequence_id, bool snap_selection, IClientAPI remote_client); public delegate void ParcelDivideRequest(int west, int south, int east, int north, IClientAPI remote_client); public delegate void ParcelJoinRequest(int west, int south, int east, int north, IClientAPI remote_client); public delegate void ParcelPropertiesUpdateRequest(LandUpdateArgs args, int local_id, IClientAPI remote_client); public delegate void ParcelSelectObjects(int land_local_id, int request_type, List<UUID> returnIDs, IClientAPI remote_client); public delegate void ParcelObjectOwnerRequest(int local_id, IClientAPI remote_client); public delegate void ParcelAbandonRequest(int local_id, IClientAPI remote_client); public delegate void ParcelGodForceOwner(int local_id, UUID ownerID, IClientAPI remote_client); public delegate void ParcelReclaim(int local_id, IClientAPI remote_client); public delegate void ParcelReturnObjectsRequest( int local_id, uint return_type, UUID[] agent_ids, UUID[] selected_ids, IClientAPI remote_client); public delegate void ParcelDeedToGroup(int local_id, UUID group_id, IClientAPI remote_client); public delegate void EstateOwnerMessageRequest( UUID AgentID, UUID SessionID, UUID TransactionID, UUID Invoice, byte[] Method, byte[][] Parameters, IClientAPI remote_client); public delegate void RegionInfoRequest(IClientAPI remote_client); public delegate void EstateCovenantRequest(IClientAPI remote_client); public delegate void UUIDNameRequest(UUID id, IClientAPI remote_client); public delegate void AddNewPrim( UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape, byte bypassRaycast, Vector3 RayStart, UUID RayTargetID, byte RayEndIsIntersection); public delegate void RequestGodlikePowers( UUID AgentID, UUID SessionID, UUID token, bool GodLike, IClientAPI remote_client); public delegate void GodKickUser( UUID GodAgentID, UUID GodSessionID, UUID AgentID, uint kickflags, byte[] reason); public delegate void CreateInventoryFolder( IClientAPI remoteClient, UUID folderID, ushort folderType, string folderName, UUID parentID); public delegate void UpdateInventoryFolder( IClientAPI remoteClient, UUID folderID, ushort type, string name, UUID parentID); public delegate void MoveInventoryFolder( IClientAPI remoteClient, UUID folderID, UUID parentID); public delegate void CreateNewInventoryItem( IClientAPI remoteClient, UUID transActionID, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte type, byte wearableType, uint nextOwnerMask, int creationDate); public delegate void FetchInventoryDescendents( IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder); public delegate void PurgeInventoryDescendents( IClientAPI remoteClient, UUID folderID); public delegate void FetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID); public delegate void RequestTaskInventory(IClientAPI remoteClient, uint localID); /* public delegate void UpdateInventoryItem( IClientAPI remoteClient, UUID transactionID, UUID itemID, string name, string description, uint nextOwnerMask);*/ public delegate void UpdateInventoryItem( IClientAPI remoteClient, UUID transactionID, UUID itemID, InventoryItemBase itemUpd); public delegate void CopyInventoryItem( IClientAPI remoteClient, uint callbackID, UUID oldAgentID, UUID oldItemID, UUID newFolderID, string newName); public delegate void MoveInventoryItem( IClientAPI remoteClient, List<InventoryItemBase> items); public delegate void RemoveInventoryItem( IClientAPI remoteClient, List<UUID> itemIDs); public delegate void RemoveInventoryFolder( IClientAPI remoteClient, List<UUID> folderIDs); public delegate void RequestAsset(IClientAPI remoteClient, RequestAssetArgs transferRequest); public delegate void AbortXfer(IClientAPI remoteClient, ulong xferID); public delegate void RezScript(IClientAPI remoteClient, InventoryItemBase item, UUID transactionID, uint localID); public delegate void UpdateTaskInventory( IClientAPI remoteClient, UUID transactionID, TaskInventoryItem item, uint localID); public delegate void MoveTaskInventory(IClientAPI remoteClient, UUID folderID, uint localID, UUID itemID); public delegate void RemoveTaskInventory(IClientAPI remoteClient, UUID itemID, uint localID); public delegate void UDPAssetUploadRequest( IClientAPI remoteClient, UUID assetID, UUID transaction, sbyte type, byte[] data, bool storeLocal, bool tempFile); public delegate void XferReceive(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data); public delegate void RequestXfer(IClientAPI remoteClient, ulong xferID, string fileName); public delegate void ConfirmXfer(IClientAPI remoteClient, ulong xferID, uint packetID); public delegate void FriendActionDelegate( IClientAPI remoteClient, UUID agentID, UUID transactionID, List<UUID> callingCardFolders); public delegate void FriendshipTermination(IClientAPI remoteClient, UUID agentID, UUID ExID); public delegate void MoneyTransferRequest( UUID sourceID, UUID destID, int amount, int transactionType, string description); public delegate void ParcelBuy(UUID agentId, UUID groupId, bool final, bool groupOwned, bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated); // We keep all this information for fraud purposes in the future. public delegate void MoneyBalanceRequest(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID TransactionID); public delegate void ObjectPermissions( IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set); public delegate void EconomyDataRequest(UUID agentID); public delegate void ObjectIncludeInSearch(IClientAPI remoteClient, bool IncludeInSearch, uint localID); public delegate void ScriptAnswer(IClientAPI remoteClient, UUID objectID, UUID itemID, int answer); public delegate void RequestPayPrice(IClientAPI remoteClient, UUID objectID); public delegate void ObjectSaleInfo( IClientAPI remoteClient, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice); public delegate void ObjectBuy( IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID groupID, UUID categoryID, uint localID, byte saleType, int salePrice); public delegate void BuyObjectInventory( IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID objectID, UUID itemID, UUID folderID); public delegate void ForceReleaseControls(IClientAPI remoteClient, UUID agentID); public delegate void GodLandStatRequest( int parcelID, uint reportType, uint requestflags, string filter, IClientAPI remoteClient); //Estate Requests public delegate void DetailedEstateDataRequest(IClientAPI remoteClient, UUID invoice); public delegate void SetEstateFlagsRequest( bool blockTerraform, bool noFly, bool allowDamage, bool blockLandResell, int maxAgents, float objectBonusFactor, int matureLevel, bool restrictPushObject, bool allowParcelChanges); public delegate void SetEstateTerrainBaseTexture(IClientAPI remoteClient, int corner, UUID side); public delegate void SetEstateTerrainDetailTexture(IClientAPI remoteClient, int corner, UUID side); public delegate void SetEstateTerrainTextureHeights(IClientAPI remoteClient, int corner, float lowVal, float highVal ); public delegate void CommitEstateTerrainTextureRequest(IClientAPI remoteClient); public delegate void SetRegionTerrainSettings( float waterHeight, float terrainRaiseLimit, float terrainLowerLimit, bool estateSun, bool fixedSun, float sunHour, bool globalSun, bool estateFixed, float estateSunHour); public delegate void EstateChangeInfo(IClientAPI client, UUID invoice, UUID senderID, UInt32 param1, UInt32 param2); public delegate void RequestTerrain(IClientAPI remoteClient, string clientFileName); public delegate void BakeTerrain(IClientAPI remoteClient); public delegate void EstateRestartSimRequest(IClientAPI remoteClient, int secondsTilReboot); public delegate void EstateChangeCovenantRequest(IClientAPI remoteClient, UUID newCovenantID); public delegate void UpdateEstateAccessDeltaRequest( IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user); public delegate void SimulatorBlueBoxMessageRequest( IClientAPI remoteClient, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message); public delegate void EstateBlueBoxMessageRequest( IClientAPI remoteClient, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message); public delegate void EstateDebugRegionRequest( IClientAPI remoteClient, UUID invoice, UUID senderID, bool scripted, bool collisionEvents, bool physics); public delegate void EstateTeleportOneUserHomeRequest( IClientAPI remoteClient, UUID invoice, UUID senderID, UUID prey); public delegate void EstateTeleportAllUsersHomeRequest(IClientAPI remoteClient, UUID invoice, UUID senderID); public delegate void RegionHandleRequest(IClientAPI remoteClient, UUID regionID); public delegate void ParcelInfoRequest(IClientAPI remoteClient, UUID parcelID); public delegate void ScriptReset(IClientAPI remoteClient, UUID objectID, UUID itemID); public delegate void GetScriptRunning(IClientAPI remoteClient, UUID objectID, UUID itemID); public delegate void SetScriptRunning(IClientAPI remoteClient, UUID objectID, UUID itemID, bool running); public delegate void ActivateGesture(IClientAPI client, UUID gestureid, UUID assetId); public delegate void DeactivateGesture(IClientAPI client, UUID gestureid); public delegate void TerrainUnacked(IClientAPI remoteClient, int patchX, int patchY); public delegate void ObjectOwner(IClientAPI remoteClient, UUID ownerID, UUID groupID, List<uint> localIDs); public delegate void DirPlacesQuery( IClientAPI remoteClient, UUID queryID, string queryText, int queryFlags, int category, string simName, int queryStart); public delegate void DirFindQuery( IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart); public delegate void DirLandQuery( IClientAPI remoteClient, UUID queryID, uint queryFlags, uint searchType, int price, int area, int queryStart); public delegate void DirPopularQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags); public delegate void DirClassifiedQuery( IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, uint category, int queryStart); public delegate void EventInfoRequest(IClientAPI remoteClient, uint eventID); public delegate void ParcelSetOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime); public delegate void MapItemRequest( IClientAPI remoteClient, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle); public delegate void OfferCallingCard(IClientAPI remoteClient, UUID destID, UUID transactionID); public delegate void AcceptCallingCard(IClientAPI remoteClient, UUID transactionID, UUID folderID); public delegate void DeclineCallingCard(IClientAPI remoteClient, UUID transactionID); public delegate void SoundTrigger( UUID soundId, UUID ownerid, UUID objid, UUID parentid, double Gain, Vector3 Position, UInt64 Handle); public delegate void StartLure(byte lureType, string message, UUID targetID, IClientAPI client); public delegate void TeleportLureRequest(UUID lureID, uint teleportFlags, IClientAPI client); public delegate void ClassifiedInfoRequest(UUID classifiedID, IClientAPI client); public delegate void ClassifiedInfoUpdate(UUID classifiedID, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, Vector3 globalPos, byte classifiedFlags, int price, IClientAPI client); public delegate void ClassifiedDelete(UUID classifiedID, IClientAPI client); public delegate void EventNotificationAddRequest(uint EventID, IClientAPI client); public delegate void EventNotificationRemoveRequest(uint EventID, IClientAPI client); public delegate void EventGodDelete(uint eventID, UUID queryID, string queryText, uint queryFlags, int queryStart, IClientAPI client); public delegate void ParcelDwellRequest(int localID, IClientAPI client); public delegate void UserInfoRequest(IClientAPI client); public delegate void UpdateUserInfo(bool imViaEmail, bool visible, IClientAPI client); public delegate void RetrieveInstantMessages(IClientAPI client); public delegate void PickDelete(IClientAPI client, UUID pickID); public delegate void PickGodDelete(IClientAPI client, UUID agentID, UUID pickID, UUID queryID); public delegate void PickInfoUpdate(IClientAPI client, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled); public delegate void AvatarNotesUpdate(IClientAPI client, UUID targetID, string notes); public delegate void MuteListRequest(IClientAPI client, uint muteCRC); public delegate void AvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages); public delegate void PlacesQuery(UUID QueryID, UUID TransactionID, string QueryText, uint QueryFlags, byte Category, string SimName, IClientAPI client); #endregion public struct DirPlacesReplyData { public UUID parcelID; public string name; public bool forSale; public bool auction; public float dwell; public uint Status; } public struct DirPeopleReplyData { public UUID agentID; public string firstName; public string lastName; public string group; public bool online; public int reputation; } public struct DirEventsReplyData { public UUID ownerID; public string name; public uint eventID; public string date; public uint unixTime; public uint eventFlags; public uint Status; } public struct DirGroupsReplyData { public UUID groupID; public string groupName; public int members; public float searchOrder; } public struct DirClassifiedReplyData { public UUID classifiedID; public string name; public byte classifiedFlags; public uint creationDate; public uint expirationDate; public int price; public uint Status; } public struct DirLandReplyData { public UUID parcelID; public string name; public bool auction; public bool forSale; public int salePrice; public int actualArea; } public struct DirPopularReplyData { public UUID parcelID; public string name; public float dwell; } public interface IClientAPI { Vector3 StartPos { get; set; } UUID AgentId { get; } UUID SessionId { get; } UUID SecureSessionId { get; } UUID ActiveGroupId { get; } string ActiveGroupName { get; } ulong ActiveGroupPowers { get; } ulong GetGroupPowers(UUID groupID); bool IsGroupMember(UUID GroupID); string FirstName { get; } string LastName { get; } IScene Scene { get; } // [Obsolete("LLClientView Specific - Replace with ???")] int NextAnimationSequenceNumber { get; } /// <summary> /// Returns the full name of the agent/avatar represented by this client /// </summary> string Name { get; } /// <value> /// Determines whether the client thread is doing anything or not. /// </value> bool IsActive { get; set; } bool SendLogoutPacketWhenClosing { set; } // [Obsolete("LLClientView Specific - Circuits are unique to LLClientView")] uint CircuitCode { get; } event GenericMessage OnGenericMessage; // [Obsolete("LLClientView Specific - Replace with more bare-bones arguments.")] event ImprovedInstantMessage OnInstantMessage; // [Obsolete("LLClientView Specific - Replace with more bare-bones arguments. Rename OnChat.")] event ChatMessage OnChatFromClient; // [Obsolete("LLClientView Specific - Replace with more bare-bones arguments.")] event TextureRequest OnRequestTexture; // [Obsolete("LLClientView Specific - Remove bitbuckets. Adam, can you be more specific here.. as I don't see any bit buckets.")] event RezObject OnRezObject; // [Obsolete("LLClientView Specific - Replace with more suitable arguments.")] event ModifyTerrain OnModifyTerrain; event BakeTerrain OnBakeTerrain; event EstateChangeInfo OnEstateChangeInfo; // [Obsolete("LLClientView Specific.")] event SetAppearance OnSetAppearance; // [Obsolete("LLClientView Specific - Replace and rename OnAvatarUpdate. Difference from SetAppearance?")] event AvatarNowWearing OnAvatarNowWearing; event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; event UUIDNameRequest OnDetachAttachmentIntoInv; event ObjectAttach OnObjectAttach; event ObjectDeselect OnObjectDetach; event ObjectDrop OnObjectDrop; event StartAnim OnStartAnim; event StopAnim OnStopAnim; event LinkObjects OnLinkObjects; event DelinkObjects OnDelinkObjects; event RequestMapBlocks OnRequestMapBlocks; event RequestMapName OnMapNameRequest; event TeleportLocationRequest OnTeleportLocationRequest; event DisconnectUser OnDisconnectUser; event RequestAvatarProperties OnRequestAvatarProperties; event SetAlwaysRun OnSetAlwaysRun; event TeleportLandmarkRequest OnTeleportLandmarkRequest; event DeRezObject OnDeRezObject; event Action<IClientAPI> OnRegionHandShakeReply; event GenericCall2 OnRequestWearables; event GenericCall2 OnCompleteMovementToRegion; event UpdateAgent OnAgentUpdate; event AgentRequestSit OnAgentRequestSit; event AgentSit OnAgentSit; event AvatarPickerRequest OnAvatarPickerRequest; event Action<IClientAPI> OnRequestAvatarsData; event AddNewPrim OnAddPrim; event FetchInventory OnAgentDataUpdateRequest; event TeleportLocationRequest OnSetStartLocationRequest; event RequestGodlikePowers OnRequestGodlikePowers; event GodKickUser OnGodKickUser; event ObjectDuplicate OnObjectDuplicate; event ObjectDuplicateOnRay OnObjectDuplicateOnRay; event GrabObject OnGrabObject; event DeGrabObject OnDeGrabObject; event MoveObject OnGrabUpdate; event SpinStart OnSpinStart; event SpinObject OnSpinUpdate; event SpinStop OnSpinStop; event UpdateShape OnUpdatePrimShape; event ObjectExtraParams OnUpdateExtraParams; event ObjectRequest OnObjectRequest; event ObjectSelect OnObjectSelect; event ObjectDeselect OnObjectDeselect; event GenericCall7 OnObjectDescription; event GenericCall7 OnObjectName; event GenericCall7 OnObjectClickAction; event GenericCall7 OnObjectMaterial; event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; event UpdatePrimFlags OnUpdatePrimFlags; event UpdatePrimTexture OnUpdatePrimTexture; event UpdateVector OnUpdatePrimGroupPosition; event UpdateVector OnUpdatePrimSinglePosition; event UpdatePrimRotation OnUpdatePrimGroupRotation; event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; event UpdateVector OnUpdatePrimScale; event UpdateVector OnUpdatePrimGroupScale; event StatusChange OnChildAgentStatus; event GenericCall2 OnStopMovement; event Action<UUID> OnRemoveAvatar; event ObjectPermissions OnObjectPermissions; event CreateNewInventoryItem OnCreateNewInventoryItem; event CreateInventoryFolder OnCreateNewInventoryFolder; event UpdateInventoryFolder OnUpdateInventoryFolder; event MoveInventoryFolder OnMoveInventoryFolder; event FetchInventoryDescendents OnFetchInventoryDescendents; event PurgeInventoryDescendents OnPurgeInventoryDescendents; event FetchInventory OnFetchInventory; event RequestTaskInventory OnRequestTaskInventory; event UpdateInventoryItem OnUpdateInventoryItem; event CopyInventoryItem OnCopyInventoryItem; event MoveInventoryItem OnMoveInventoryItem; event RemoveInventoryFolder OnRemoveInventoryFolder; event RemoveInventoryItem OnRemoveInventoryItem; event UDPAssetUploadRequest OnAssetUploadRequest; event XferReceive OnXferReceive; event RequestXfer OnRequestXfer; event ConfirmXfer OnConfirmXfer; event AbortXfer OnAbortXfer; event RezScript OnRezScript; event UpdateTaskInventory OnUpdateTaskInventory; event MoveTaskInventory OnMoveTaskItem; event RemoveTaskInventory OnRemoveTaskItem; event RequestAsset OnRequestAsset; event UUIDNameRequest OnNameFromUUIDRequest; event ParcelAccessListRequest OnParcelAccessListRequest; event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; event ParcelPropertiesRequest OnParcelPropertiesRequest; event ParcelDivideRequest OnParcelDivideRequest; event ParcelJoinRequest OnParcelJoinRequest; event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; event ParcelSelectObjects OnParcelSelectObjects; event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; event ParcelAbandonRequest OnParcelAbandonRequest; event ParcelGodForceOwner OnParcelGodForceOwner; event ParcelReclaim OnParcelReclaim; event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; event ParcelDeedToGroup OnParcelDeedToGroup; event RegionInfoRequest OnRegionInfoRequest; event EstateCovenantRequest OnEstateCovenantRequest; event FriendActionDelegate OnApproveFriendRequest; event FriendActionDelegate OnDenyFriendRequest; event FriendshipTermination OnTerminateFriendship; // Financial packets event MoneyTransferRequest OnMoneyTransferRequest; event EconomyDataRequest OnEconomyDataRequest; event MoneyBalanceRequest OnMoneyBalanceRequest; event UpdateAvatarProperties OnUpdateAvatarProperties; event ParcelBuy OnParcelBuy; event RequestPayPrice OnRequestPayPrice; event ObjectSaleInfo OnObjectSaleInfo; event ObjectBuy OnObjectBuy; event BuyObjectInventory OnBuyObjectInventory; event RequestTerrain OnRequestTerrain; event RequestTerrain OnUploadTerrain; event ObjectIncludeInSearch OnObjectIncludeInSearch; event UUIDNameRequest OnTeleportHomeRequest; event ScriptAnswer OnScriptAnswer; event AgentSit OnUndo; event ForceReleaseControls OnForceReleaseControls; event GodLandStatRequest OnLandStatRequest; event DetailedEstateDataRequest OnDetailedEstateDataRequest; event SetEstateFlagsRequest OnSetEstateFlagsRequest; event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; event SetRegionTerrainSettings OnSetRegionTerrainSettings; event EstateRestartSimRequest OnEstateRestartSimRequest; event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; event EstateDebugRegionRequest OnEstateDebugRegionRequest; event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; event UUIDNameRequest OnUUIDGroupNameRequest; event RegionHandleRequest OnRegionHandleRequest; event ParcelInfoRequest OnParcelInfoRequest; event RequestObjectPropertiesFamily OnObjectGroupRequest; event ScriptReset OnScriptReset; event GetScriptRunning OnGetScriptRunning; event SetScriptRunning OnSetScriptRunning; event UpdateVector OnAutoPilotGo; event TerrainUnacked OnUnackedTerrain; event ActivateGesture OnActivateGesture; event DeactivateGesture OnDeactivateGesture; event ObjectOwner OnObjectOwner; event DirPlacesQuery OnDirPlacesQuery; event DirFindQuery OnDirFindQuery; event DirLandQuery OnDirLandQuery; event DirPopularQuery OnDirPopularQuery; event DirClassifiedQuery OnDirClassifiedQuery; event EventInfoRequest OnEventInfoRequest; event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; event MapItemRequest OnMapItemRequest; event OfferCallingCard OnOfferCallingCard; event AcceptCallingCard OnAcceptCallingCard; event DeclineCallingCard OnDeclineCallingCard; event SoundTrigger OnSoundTrigger; event StartLure OnStartLure; event TeleportLureRequest OnTeleportLureRequest; event NetworkStats OnNetworkStatsUpdate; event ClassifiedInfoRequest OnClassifiedInfoRequest; event ClassifiedInfoUpdate OnClassifiedInfoUpdate; event ClassifiedDelete OnClassifiedDelete; event ClassifiedDelete OnClassifiedGodDelete; event EventNotificationAddRequest OnEventNotificationAddRequest; event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; event EventGodDelete OnEventGodDelete; event ParcelDwellRequest OnParcelDwellRequest; event UserInfoRequest OnUserInfoRequest; event UpdateUserInfo OnUpdateUserInfo; event RetrieveInstantMessages OnRetrieveInstantMessages; event PickDelete OnPickDelete; event PickGodDelete OnPickGodDelete; event PickInfoUpdate OnPickInfoUpdate; event AvatarNotesUpdate OnAvatarNotesUpdate; event MuteListRequest OnMuteListRequest; event PlacesQuery OnPlacesQuery; /// <summary> /// Set the debug level at which packet output should be printed to console. /// </summary> void SetDebugPacketLevel(int newDebug); void InPacket(object NewPack); void ProcessInPacket(Packet NewPack); void Close(bool ShutdownCircuit); void Kick(string message); /// <summary> /// Start processing for this client. /// </summary> void Start(); void Stop(); // void ActivateGesture(UUID assetId, UUID gestureId); /// <summary> /// Tell this client what items it should be wearing now /// </summary> void SendWearables(AvatarWearable[] wearables, int serial); /// <summary> /// Send information about the given agent's appearance to another client. /// </summary> /// <param name="agentID">The id of the agent associated with the appearance</param> /// <param name="visualParams"></param> /// <param name="textureEntry"></param> void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry); void SendStartPingCheck(byte seq); /// <summary> /// Tell the client that an object has been deleted /// </summary> /// <param name="regionHandle"></param> /// <param name="localID"></param> void SendKillObject(ulong regionHandle, uint localID); void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs); void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args); void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible); void SendInstantMessage(GridInstantMessage im); void SendGenericMessage(string method, List<string> message); void SendLayerData(float[] map); void SendLayerData(int px, int py, float[] map); void SendWindData(Vector2[] windSpeeds); void SendCloudData(float[] cloudCover); void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look); void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint); /// <summary> /// Return circuit information for this client. /// </summary> /// <returns></returns> AgentCircuitData RequestClientInfo(); void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL); void SendMapBlock(List<MapBlockData> mapBlocks, uint flag); void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags); void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL); void SendTeleportFailed(string reason); void SendTeleportLocationStart(); void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance); void SendPayPrice(UUID objectID, int[] payPrice); void SendAvatarData(ulong regionHandle, string firstName, string lastName, string grouptitle, UUID avatarID, uint avatarLocalID, Vector3 Pos, byte[] textureEntry, uint parentID, Quaternion rotation); void SendAvatarTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position, Vector3 velocity, Quaternion rotation, UUID agentid); void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations); void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID); void SetChildAgentThrottle(byte[] throttle); void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, Vector3 pos, Vector3 vel, Vector3 acc, Quaternion rotation, Vector3 rvel, uint flags, UUID objectID, UUID ownerID, string text, byte[] color, uint parentID, byte[] particleSystem, byte clickAction, byte material, byte[] textureanim, bool attachment, uint AttachPoint, UUID AssetId, UUID SoundId, double SoundVolume, byte SoundFlags, double SoundRadius); void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, Vector3 pos, Vector3 vel, Vector3 acc, Quaternion rotation, Vector3 rvel, uint flags, UUID objectID, UUID ownerID, string text, byte[] color, uint parentID, byte[] particleSystem, byte clickAction, byte material); void SendPrimTerseUpdate(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position, Quaternion rotation, Vector3 velocity, Vector3 rotationalvelocity, byte state, UUID AssetId, UUID owner, int attachPoint); void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems); void FlushPrimUpdates(); void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item); /// <summary> /// Tell the client that we have created the item it requested. /// </summary> /// <param name="Item"></param> void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId); void SendRemoveInventoryItem(UUID itemID); void SendTakeControls(int controls, bool passToAgent, bool TakeControls); void SendTaskInventory(UUID taskID, short serial, byte[] fileName); /// <summary> /// Used by the server to inform the client of new inventory items and folders. /// </summary> /// /// If the node is a folder then the contents will be transferred /// (including all descendent folders) as well as the folder itself. /// /// <param name="node"></param> void SendBulkUpdateInventory(InventoryNodeBase node); void SendXferPacket(ulong xferID, uint packet, byte[] data); void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent); void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data); void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle); void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID); void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags); void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain); void SendAttachedSoundGainChange(UUID objectID, float gain); void SendNameReply(UUID profileId, string firstname, string lastname); void SendAlertMessage(string message); void SendAgentAlertMessage(string message, bool modal); void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url); void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels); bool AddMoney(int debit); /// <summary> /// Update the client as to where the sun is currently located. /// </summary> /// <param name="sunPos"></param> /// <param name="sunVel"></param> /// <param name="CurrentTime">Seconds since Unix Epoch 01/01/1970 00:00:00</param> /// <param name="SecondsPerSunCycle"></param> /// <param name="SecondsPerYear"></param> /// <param name="OrbitalPosition">The orbital position is given in radians, and must be "adjusted" for the linden client, see LLClientView</param> void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition); void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks); void SendViewerTime(int phase); UUID GetDefaultAnimation(string name); void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID); void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question); void SendHealth(float health); void SendEstateManagersList(UUID invoice, UUID[] EstateManagers, uint estateID); void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID); void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args); void SendEstateCovenantInformation(UUID covenant); void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner); void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags); void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID); void SendForceClientSelectObjects(List<uint> objectIDs); void SendCameraConstraint(Vector4 ConstraintPlane); void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount); void SendLandParcelOverlay(byte[] data, int sequence_id); #region Parcel Methods void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time); void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop); #endregion void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID); void SendConfirmXfer(ulong xferID, uint PacketID); void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName); void SendInitiateDownload(string simFileName, string clientFileName); /// <summary> /// Send the first part of a texture. For sufficiently small textures, this may be the only packet. /// </summary> /// <param name="numParts"></param> /// <param name="ImageUUID"></param> /// <param name="ImageSize"></param> /// <param name="ImageData"></param> /// <param name="imageCodec"></param> void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec); /// <summary> /// Send the next packet for a series of packets making up a single texture, /// as established by SendImageFirstPart() /// </summary> /// <param name="partNumber"></param> /// <param name="imageUuid"></param> /// <param name="imageData"></param> void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData); /// <summary> /// Tell the client that the requested texture cannot be found /// </summary> void SendImageNotFound(UUID imageid); void SendShutdownConnectionNotice(); /// <summary> /// Send statistical information about the sim to the client. /// </summary> /// <param name="stats"></param> void SendSimStats(SimStats stats); void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description); void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice); void SendAgentOffline(UUID[] agentIDs); void SendAgentOnline(UUID[] agentIDs); void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook); void SendAdminResponse(UUID Token, uint AdminLevel); void SendGroupMembership(GroupMembershipData[] GroupMembership); void SendGroupNameReply(UUID groupLLUID, string GroupName); void SendJoinGroupReply(UUID groupID, bool success); void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success); void SendLeaveGroupReply(UUID groupID, bool success); void SendCreateGroupReply(UUID groupID, bool success, string message); void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia); void SendScriptRunningReply(UUID objectID, UUID itemID, bool running); void SendAsset(AssetRequestToClient req); void SendTexture(AssetBase TextureAsset); byte[] GetThrottlesPacked(float multiplier); event ViewerEffectEventHandler OnViewerEffect; event Action<IClientAPI> OnLogout; event Action<IClientAPI> OnConnectionClosed; void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message); void SendLogoutPacket(); EndPoint GetClientEP(); // WARNING WARNING WARNING // // The two following methods are EXCLUSIVELY for the load balancer. // they cause a MASSIVE performance hit! // ClientInfo GetClientInfo(); void SetClientInfo(ClientInfo info); void SetClientOption(string option, string value); string GetClientOption(string option); void Terminate(); void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters); void SendClearFollowCamProperties(UUID objectID); void SendRegionHandle(UUID regoinID, ulong handle); void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y); void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt); void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data); void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data); void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data); void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data); void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data); void SendDirLandReply(UUID queryID, DirLandReplyData[] data); void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data); void SendEventInfoReply(EventData info); void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags); void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data); void SendOfferCallingCard(UUID srcID, UUID transactionID); void SendAcceptCallingCard(UUID transactionID); void SendDeclineCallingCard(UUID transactionID); void SendTerminateFriend(UUID exFriendID); void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name); void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price); void SendAgentDropGroup(UUID groupID); void RefreshGroupMembership(); void SendAvatarNotesReply(UUID targetID, string text); void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks); void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled); void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds); void SendParcelDwellReply(int localID, UUID parcelID, float dwell); void SendUserInfoReply(bool imViaEmail, bool visible, string email); void SendUseCachedMuteList(); void SendMuteListUpdate(string filename); void KillEndDone(); bool AddGenericPacketHandler(string MethodName, GenericMessage handler); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; namespace fyiReporting.RDL { ///<summary> /// Renders a report to HTML. This handles some page formating but does not do true page formatting. ///</summary> internal class RenderExcel2003 : RenderExcel { public RenderExcel2003(Report rep, IStreamGen sg) : base(rep, sg) { } public override void End() { base.End(); Byte[] byteArray = ((MemoryStream)base.StreamGen.GetStream()).ToArray(); MemoryStream xlsFile = this.ConvertXSLXToXLS(byteArray); ((MemoryStreamGen)base.StreamGen).SetStream(xlsFile); return; } // Mostly Grok'd from https://stackoverflow.com/questions/29542249/convert-xlsx-file-to-xls-using-npoi-in-c-sharp /// <summary> /// Converts Excel XML format (2007+) to BIFF format (Excel 1997-2003) /// </summary> //public MemoryStreamGen ConvertXSLXToXLS(MemoryStreamGen input) private MemoryStream ConvertXSLXToXLS(Byte[] byteArray) { MemoryStream file = new MemoryStream(); XSSFWorkbook xlsxWb = new XSSFWorkbook(new MemoryStream(byteArray)); HSSFWorkbook xlsWb = ConvertWorkbookXSSFToHSSF(xlsxWb); xlsWb.Write(file); return file; } private static HSSFWorkbook ConvertWorkbookXSSFToHSSF(XSSFWorkbook source) { //Install-Package NPOI -Version 2.0.6 HSSFWorkbook retVal = new HSSFWorkbook(); for (int i = 0; i < source.NumberOfSheets; i++) { HSSFSheet hssfSheet = (HSSFSheet)retVal.CreateSheet(source.GetSheetAt(i).SheetName); XSSFSheet xssfsheet = (XSSFSheet)source.GetSheetAt(i); CopySheets(xssfsheet, hssfSheet, retVal); } return retVal; } private static void CopySheets(XSSFSheet source, HSSFSheet destination, HSSFWorkbook retVal) { int maxColumnNum = 0; Dictionary<int, XSSFCellStyle> styleMap = new Dictionary<int, XSSFCellStyle>(); for (int i = source.FirstRowNum; i <= source.LastRowNum; i++) { XSSFRow srcRow = (XSSFRow)source.GetRow(i); HSSFRow destRow = (HSSFRow)destination.CreateRow(i); if (srcRow != null) { CopyRow(source, destination, srcRow, destRow, styleMap, retVal); if (srcRow.LastCellNum > maxColumnNum) { maxColumnNum = srcRow.LastCellNum; } } } for (int i = 0; i <= maxColumnNum; i++) { destination.SetColumnWidth(i, source.GetColumnWidth(i)); } } private static void CopyRow(XSSFSheet srcSheet, HSSFSheet destSheet, XSSFRow srcRow, HSSFRow destRow, Dictionary<int, XSSFCellStyle> styleMap, HSSFWorkbook retVal) { // manage a list of merged zone in order to not insert two times a // merged zone List<CellRangeAddress> mergedRegions = new List<CellRangeAddress>(); destRow.Height = srcRow.Height; // pour chaque row for (int j = srcRow.FirstCellNum; j <= srcRow.LastCellNum; j++) { XSSFCell oldCell = (XSSFCell)srcRow.GetCell(j); // ancienne cell HSSFCell newCell = (HSSFCell)destRow.GetCell(j); // new cell if (oldCell != null) { if (newCell == null) { newCell = (HSSFCell)destRow.CreateCell(j); } // copy chaque cell CopyCell(oldCell, newCell, styleMap, retVal); // copy les informations de fusion entre les cellules CellRangeAddress mergedRegion = GetMergedRegion(srcSheet, srcRow.RowNum, (short)oldCell.ColumnIndex); if (mergedRegion != null) { CellRangeAddress newMergedRegion = new CellRangeAddress(mergedRegion.FirstRow, mergedRegion.LastRow, mergedRegion.FirstColumn, mergedRegion.LastColumn); if (IsNewMergedRegion(newMergedRegion, mergedRegions)) { mergedRegions.Add(newMergedRegion); destSheet.AddMergedRegion(newMergedRegion); } if (newMergedRegion.FirstColumn == 0 && newMergedRegion.LastColumn == 6 && newMergedRegion.FirstRow == newMergedRegion.LastRow) { HSSFCellStyle style2 = (HSSFCellStyle)retVal.CreateCellStyle(); style2.VerticalAlignment = VerticalAlignment.Center; style2.Alignment = HorizontalAlignment.Left; style2.FillForegroundColor = HSSFColor.Teal.Index; style2.FillPattern = FillPattern.SolidForeground; for (int i = destRow.FirstCellNum; i <= destRow.LastCellNum; i++) { if (destRow.GetCell(i) != null) destRow.GetCell(i).CellStyle = style2; } } } } } } private static void CopyCell(XSSFCell oldCell, HSSFCell newCell, Dictionary<int, XSSFCellStyle> styleMap, HSSFWorkbook retVal) { if (styleMap != null) { int stHashCode = oldCell.CellStyle.Index; XSSFCellStyle sourceCellStyle = null; if (styleMap.TryGetValue(stHashCode, out sourceCellStyle)) { } HSSFCellStyle destnCellStyle = (HSSFCellStyle)newCell.CellStyle; if (sourceCellStyle == null) { sourceCellStyle = (XSSFCellStyle)oldCell.Sheet.Workbook.CreateCellStyle(); } // destnCellStyle.CloneStyleFrom(oldCell.CellStyle); if (!styleMap.Any(p => p.Key == stHashCode)) { styleMap.Add(stHashCode, sourceCellStyle); } destnCellStyle.VerticalAlignment = VerticalAlignment.Top; newCell.CellStyle = (HSSFCellStyle)destnCellStyle; } switch (oldCell.CellType) { case CellType.String: newCell.SetCellValue(oldCell.StringCellValue); break; case CellType.Numeric: newCell.SetCellValue(oldCell.NumericCellValue); break; case CellType.Blank: newCell.SetCellType(CellType.Blank); break; case CellType.Boolean: newCell.SetCellValue(oldCell.BooleanCellValue); break; case CellType.Error: newCell.SetCellErrorValue(oldCell.ErrorCellValue); break; case CellType.Formula: newCell.SetCellFormula(oldCell.CellFormula); break; default: break; } } private static CellRangeAddress GetMergedRegion(XSSFSheet sheet, int rowNum, short cellNum) { for (int i = 0; i < sheet.NumMergedRegions; i++) { CellRangeAddress merged = sheet.GetMergedRegion(i); if (merged.IsInRange(rowNum, cellNum)) { return merged; } } return null; } private static bool IsNewMergedRegion(CellRangeAddress newMergedRegion, List<CellRangeAddress> mergedRegions) { return !mergedRegions.Contains(newMergedRegion); } } }
#region License // Copyright 2013-2014 Matthew Ducker // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion // Controls whether, when debugging, the length of an item's DTO object is reported when authenticating it. #define PRINT_DTO_LENGTH using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Obscur.Core.Cryptography; using Obscur.Core.Cryptography.Authentication; using Obscur.Core.Cryptography.Ciphers; using Obscur.Core.DTO; using Obscur.Core.Packaging.Multiplexing.Entropy; using PerfCopy; namespace Obscur.Core.Packaging.Multiplexing.Primitives { /// <summary> /// Payload multiplexer implementing stream selection order by CSPRNG. /// </summary> public class SimplePayloadMux : PayloadMux { /// <summary> /// Size of the internal buffer to use for multiplexing/demultiplexing I/O. /// </summary> protected const int BufferSize = 4096; /// <summary> /// Used for <see cref="PayloadMuxEntropyScheme.Preallocation" /> scheme. Size in bytes. /// </summary> protected internal const int ItemFieldMaximumSize = sizeof(UInt16); /// <summary> /// Internal buffer to use for multiplexing/demultiplexing I/O. /// </summary> protected readonly byte[] Buffer = new byte[BufferSize]; /// <summary> /// Entropy source for stream selection and other tasks (depending on implementation). /// </summary> protected MuxEntropySourceFacade EntropySource; /// <summary> /// Initializes a new instance of a payload multiplexer. /// </summary> /// <param name="writing">If set to <c>true</c>, writing a multiplexed stream (payload); otherwise, reading.</param> /// <param name="multiplexedStream"> /// Stream being written to (destination; multiplexing) or read from (source; /// demultiplexing). /// </param> /// <param name="payloadItems">Payload items to write.</param> /// <param name="itemPreKeys">Pre-keys for items (indexed by item identifiers).</param> /// <param name="config">Configuration of stream selection.</param> public SimplePayloadMux(bool writing, Stream multiplexedStream, IReadOnlyList<PayloadItem> payloadItems, IReadOnlyDictionary<Guid, byte[]> itemPreKeys, PayloadConfiguration config) : base(writing, multiplexedStream, payloadItems, itemPreKeys) { if (config == null) { throw new ArgumentNullException("config"); } EntropySource = new MuxEntropySourceFacade(writing, config); } /// <summary> /// How many bytes written/read not constituting /// item data emitted/consumed by their decorators. /// </summary> public int Overhead { get; protected set; } protected override void ExecuteOperation() { PayloadItem item = PayloadItems[Index]; bool skip = ItemSkipRegister != null && ItemSkipRegister.Contains(item.Identifier); if (skip == false) { CipherStream itemEncryptor; MacStream itemAuthenticator; CreateEtMDecorator(item, out itemEncryptor, out itemAuthenticator); if (Writing) { EmitHeader(itemAuthenticator); } else { ConsumeHeader(itemAuthenticator); } if (Writing) { int iterIn; do { iterIn = item.StreamBinding.Read(Buffer, 0, BufferSize); itemEncryptor.Write(Buffer, 0, iterIn); } while (iterIn > 0); } else { itemEncryptor.ReadExactly(item.StreamBinding, item.InternalLength, true); } FinishItem(item, itemEncryptor, itemAuthenticator); } else { // Skipping long skipLength = GetHeaderLength() + item.InternalLength + GetTrailerLength(); PayloadStream.Seek(skipLength, SeekOrigin.Current); // Mark the item as completed in the register ItemCompletionRegister[Index] = true; ItemsCompleted++; Debug.Print(DebugUtility.CreateReportString("SimplePayloadMux", "ExecuteOperation", "[*** SKIPPED ITEM", String.Format("{0} ({1}) ***]", Index, item.Identifier))); } } /// <summary> /// Close the item decorator, check lengths, authenticate the item (emit or verify), /// and if writing, commit the authentication value to the payload item DTO. /// </summary> /// <param name="item">Payload item to finish.</param> /// <param name="encryptor">Item encryptor/cipher.</param> /// <param name="authenticator">Item authenticator/MAC.</param> protected override void FinishItem(PayloadItem item, CipherStream encryptor, MacStream authenticator) { try { encryptor.Close(); } catch (Exception e) { throw new Exception("Unknown error when finalising/closing cipher.", e); } try { if (Writing) { EmitTrailer(authenticator); } else { ConsumeTrailer(authenticator); } } catch (Exception e) { throw new Exception(String.Format("Unknown error when {0} item trailer.", Writing ? "emitting" : "consuming"), e); } // Length checks & commits if (Writing) { // Check if pre-stated length matches what was actually written if (item.ExternalLength > 0 && encryptor.BytesIn != item.ExternalLength) { throw new InvalidDataException( "Mismatch between stated item external length and actual input length."); } // Commit the determined internal length to item in payload manifest item.InternalLength = encryptor.BytesOut; } else { if (encryptor.BytesIn != item.InternalLength) { throw new InvalidOperationException("Probable decorator stack malfunction."); } if (encryptor.BytesOut != item.ExternalLength) { throw new InvalidDataException( "Mismatch between stated item external length and actual output length."); } } // Final stages of Encrypt-then-MAC authentication scheme PayloadItem itemDto = item.CreateAuthenticatibleClone(); byte[] itemDtoAuthBytes = itemDto.SerialiseDto(); #if PRINT_DTO_LENGTH Debug.Print(DebugUtility.CreateReportString("SimplePayloadMux", "FinishItem", "Payload item DTO length", itemDtoAuthBytes.Length)); #endif authenticator.Update(itemDtoAuthBytes, 0, itemDtoAuthBytes.Length); authenticator.Close(); // Authentication if (Writing) { // Commit the MAC to item in payload manifest item.AuthenticationVerifiedOutput = authenticator.Mac.DeepCopy(); } else { // Verify the authenticity of the item ciphertext and configuration if (authenticator.Mac.SequenceEqual_ConstantTime(item.AuthenticationVerifiedOutput) == false) { // Verification failed! throw new CiphertextAuthenticationException("Payload item not authenticated."); } } // Close the source/destination item.StreamBinding.Close(); // Mark the item as completed in the register ItemCompletionRegister[Index] = true; ItemsCompleted++; Debug.Print(DebugUtility.CreateReportString("SimplePayloadMux", "ExecuteOperation", "[*** END OF ITEM", String.Format("{0} ({1}) ***]", Index, item.Identifier))); } /// <summary> /// Advances and returns the index of the next stream to use in an I/O operation (whether to completion or just a /// buffer-full). /// </summary> /// <remarks>May be overriden in a derived class to provide for advanced stream selection logic.</remarks> /// <returns>The next stream index.</returns> protected override sealed void NextSource() { Index = EntropySource.NextPositive(0, PayloadItems.Count - 1); Debug.Print(DebugUtility.CreateReportString("SimplePayloadMux", "NextSource", "Generated index", Index)); } #region Extensible methods /// <summary> /// Get the length of a header of the current item. /// </summary> /// <returns>Length of the header.</returns> protected virtual int GetHeaderLength() { // Unused in this version return 0; } /// <summary> /// Generate and write an item header into the payload stream. /// </summary> /// <param name="authenticator"> /// Authenticator for the item, if header is to be authenticated. /// </param> protected virtual void EmitHeader(MacStream authenticator) { // Unused in this version } /// <summary> /// Read an item header from the payload stream. /// </summary> /// <param name="authenticator"> /// Authenticator for the item, if header is to be authenticated. /// </param> protected virtual void ConsumeHeader(MacStream authenticator) { // Unused in this version // Could throw an exception in an implementation where a header must be present } /// <summary> /// Get the length of a trailer of the current item. /// </summary> /// <returns>Length of the trailer.</returns> protected virtual int GetTrailerLength() { // Unused in this version return 0; } /// <summary> /// Generate and write an item trailer into the payload stream. /// </summary> /// <param name="authenticator"> /// Authenticator for the item, if trailer is to be authenticated. /// </param> protected virtual void EmitTrailer(MacStream authenticator) { // Unused in this version } /// <summary> /// Read an item trailer from the payload stream. /// </summary> /// <param name="authenticator"> /// Authenticator for the item, if trailer is to be authenticated. /// </param> protected virtual void ConsumeTrailer(MacStream authenticator) { // Unused in this version // Could throw an exception in an implementation where a trailer must be present } #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic{ /// <summary> /// Strongly-typed collection for the VwAspnetUser class. /// </summary> [Serializable] public partial class VwAspnetUserCollection : ReadOnlyList<VwAspnetUser, VwAspnetUserCollection> { public VwAspnetUserCollection() {} } /// <summary> /// This is Read-only wrapper class for the vw_aspnet_Users view. /// </summary> [Serializable] public partial class VwAspnetUser : ReadOnlyRecord<VwAspnetUser>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("vw_aspnet_Users", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarApplicationId = new TableSchema.TableColumn(schema); colvarApplicationId.ColumnName = "ApplicationId"; colvarApplicationId.DataType = DbType.Guid; colvarApplicationId.MaxLength = 0; colvarApplicationId.AutoIncrement = false; colvarApplicationId.IsNullable = false; colvarApplicationId.IsPrimaryKey = false; colvarApplicationId.IsForeignKey = false; colvarApplicationId.IsReadOnly = false; schema.Columns.Add(colvarApplicationId); TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = false; colvarUserId.IsPrimaryKey = false; colvarUserId.IsForeignKey = false; colvarUserId.IsReadOnly = false; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarUserName = new TableSchema.TableColumn(schema); colvarUserName.ColumnName = "UserName"; colvarUserName.DataType = DbType.String; colvarUserName.MaxLength = 256; colvarUserName.AutoIncrement = false; colvarUserName.IsNullable = false; colvarUserName.IsPrimaryKey = false; colvarUserName.IsForeignKey = false; colvarUserName.IsReadOnly = false; schema.Columns.Add(colvarUserName); TableSchema.TableColumn colvarLoweredUserName = new TableSchema.TableColumn(schema); colvarLoweredUserName.ColumnName = "LoweredUserName"; colvarLoweredUserName.DataType = DbType.String; colvarLoweredUserName.MaxLength = 256; colvarLoweredUserName.AutoIncrement = false; colvarLoweredUserName.IsNullable = false; colvarLoweredUserName.IsPrimaryKey = false; colvarLoweredUserName.IsForeignKey = false; colvarLoweredUserName.IsReadOnly = false; schema.Columns.Add(colvarLoweredUserName); TableSchema.TableColumn colvarMobileAlias = new TableSchema.TableColumn(schema); colvarMobileAlias.ColumnName = "MobileAlias"; colvarMobileAlias.DataType = DbType.String; colvarMobileAlias.MaxLength = 16; colvarMobileAlias.AutoIncrement = false; colvarMobileAlias.IsNullable = true; colvarMobileAlias.IsPrimaryKey = false; colvarMobileAlias.IsForeignKey = false; colvarMobileAlias.IsReadOnly = false; schema.Columns.Add(colvarMobileAlias); TableSchema.TableColumn colvarIsAnonymous = new TableSchema.TableColumn(schema); colvarIsAnonymous.ColumnName = "IsAnonymous"; colvarIsAnonymous.DataType = DbType.Boolean; colvarIsAnonymous.MaxLength = 0; colvarIsAnonymous.AutoIncrement = false; colvarIsAnonymous.IsNullable = false; colvarIsAnonymous.IsPrimaryKey = false; colvarIsAnonymous.IsForeignKey = false; colvarIsAnonymous.IsReadOnly = false; schema.Columns.Add(colvarIsAnonymous); TableSchema.TableColumn colvarLastActivityDate = new TableSchema.TableColumn(schema); colvarLastActivityDate.ColumnName = "LastActivityDate"; colvarLastActivityDate.DataType = DbType.DateTime; colvarLastActivityDate.MaxLength = 0; colvarLastActivityDate.AutoIncrement = false; colvarLastActivityDate.IsNullable = false; colvarLastActivityDate.IsPrimaryKey = false; colvarLastActivityDate.IsForeignKey = false; colvarLastActivityDate.IsReadOnly = false; schema.Columns.Add(colvarLastActivityDate); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("vw_aspnet_Users",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public VwAspnetUser() { SetSQLProps(); SetDefaults(); MarkNew(); } public VwAspnetUser(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public VwAspnetUser(object keyID) { SetSQLProps(); LoadByKey(keyID); } public VwAspnetUser(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("ApplicationId")] [Bindable(true)] public Guid ApplicationId { get { return GetColumnValue<Guid>("ApplicationId"); } set { SetColumnValue("ApplicationId", value); } } [XmlAttribute("UserId")] [Bindable(true)] public Guid UserId { get { return GetColumnValue<Guid>("UserId"); } set { SetColumnValue("UserId", value); } } [XmlAttribute("UserName")] [Bindable(true)] public string UserName { get { return GetColumnValue<string>("UserName"); } set { SetColumnValue("UserName", value); } } [XmlAttribute("LoweredUserName")] [Bindable(true)] public string LoweredUserName { get { return GetColumnValue<string>("LoweredUserName"); } set { SetColumnValue("LoweredUserName", value); } } [XmlAttribute("MobileAlias")] [Bindable(true)] public string MobileAlias { get { return GetColumnValue<string>("MobileAlias"); } set { SetColumnValue("MobileAlias", value); } } [XmlAttribute("IsAnonymous")] [Bindable(true)] public bool IsAnonymous { get { return GetColumnValue<bool>("IsAnonymous"); } set { SetColumnValue("IsAnonymous", value); } } [XmlAttribute("LastActivityDate")] [Bindable(true)] public DateTime LastActivityDate { get { return GetColumnValue<DateTime>("LastActivityDate"); } set { SetColumnValue("LastActivityDate", value); } } #endregion #region Columns Struct public struct Columns { public static string ApplicationId = @"ApplicationId"; public static string UserId = @"UserId"; public static string UserName = @"UserName"; public static string LoweredUserName = @"LoweredUserName"; public static string MobileAlias = @"MobileAlias"; public static string IsAnonymous = @"IsAnonymous"; public static string LastActivityDate = @"LastActivityDate"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookChartSeriesRequest. /// </summary> public partial class WorkbookChartSeriesRequest : BaseRequest, IWorkbookChartSeriesRequest { /// <summary> /// Constructs a new WorkbookChartSeriesRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookChartSeriesRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookChartSeries using POST. /// </summary> /// <param name="workbookChartSeriesToCreate">The WorkbookChartSeries to create.</param> /// <returns>The created WorkbookChartSeries.</returns> public System.Threading.Tasks.Task<WorkbookChartSeries> CreateAsync(WorkbookChartSeries workbookChartSeriesToCreate) { return this.CreateAsync(workbookChartSeriesToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookChartSeries using POST. /// </summary> /// <param name="workbookChartSeriesToCreate">The WorkbookChartSeries to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookChartSeries.</returns> public async System.Threading.Tasks.Task<WorkbookChartSeries> CreateAsync(WorkbookChartSeries workbookChartSeriesToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookChartSeries>(workbookChartSeriesToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookChartSeries. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookChartSeries. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookChartSeries>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookChartSeries. /// </summary> /// <returns>The WorkbookChartSeries.</returns> public System.Threading.Tasks.Task<WorkbookChartSeries> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookChartSeries. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookChartSeries.</returns> public async System.Threading.Tasks.Task<WorkbookChartSeries> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookChartSeries>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookChartSeries using PATCH. /// </summary> /// <param name="workbookChartSeriesToUpdate">The WorkbookChartSeries to update.</param> /// <returns>The updated WorkbookChartSeries.</returns> public System.Threading.Tasks.Task<WorkbookChartSeries> UpdateAsync(WorkbookChartSeries workbookChartSeriesToUpdate) { return this.UpdateAsync(workbookChartSeriesToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookChartSeries using PATCH. /// </summary> /// <param name="workbookChartSeriesToUpdate">The WorkbookChartSeries to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookChartSeries.</returns> public async System.Threading.Tasks.Task<WorkbookChartSeries> UpdateAsync(WorkbookChartSeries workbookChartSeriesToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookChartSeries>(workbookChartSeriesToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartSeriesRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartSeriesRequest Expand(Expression<Func<WorkbookChartSeries, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartSeriesRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartSeriesRequest Select(Expression<Func<WorkbookChartSeries, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookChartSeriesToInitialize">The <see cref="WorkbookChartSeries"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookChartSeries workbookChartSeriesToInitialize) { if (workbookChartSeriesToInitialize != null && workbookChartSeriesToInitialize.AdditionalData != null) { if (workbookChartSeriesToInitialize.Points != null && workbookChartSeriesToInitialize.Points.CurrentPage != null) { workbookChartSeriesToInitialize.Points.AdditionalData = workbookChartSeriesToInitialize.AdditionalData; object nextPageLink; workbookChartSeriesToInitialize.AdditionalData.TryGetValue("points@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { workbookChartSeriesToInitialize.Points.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
// 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.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for OriginsOperations. /// </summary> public static partial class OriginsOperationsExtensions { /// <summary> /// Lists all of the existing origins within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> public static IPage<Origin> ListByEndpoint(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName) { return operations.ListByEndpointAsync(resourceGroupName, profileName, endpointName).GetAwaiter().GetResult(); } /// <summary> /// Lists all of the existing origins within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Origin>> ListByEndpointAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEndpointWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets an existing origin within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> public static Origin Get(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName) { return operations.GetAsync(resourceGroupName, profileName, endpointName, originName).GetAwaiter().GetResult(); } /// <summary> /// Gets an existing origin within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Origin> GetAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates an existing origin within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> /// <param name='originUpdateProperties'> /// Origin properties /// </param> public static Origin Update(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties) { return operations.UpdateAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties).GetAwaiter().GetResult(); } /// <summary> /// Updates an existing origin within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> /// <param name='originUpdateProperties'> /// Origin properties /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Origin> UpdateAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates an existing origin within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> /// <param name='originUpdateProperties'> /// Origin properties /// </param> public static Origin BeginUpdate(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties) { return operations.BeginUpdateAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties).GetAwaiter().GetResult(); } /// <summary> /// Updates an existing origin within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='profileName'> /// Name of the CDN profile which is unique within the resource group. /// </param> /// <param name='endpointName'> /// Name of the endpoint under the profile which is unique globally. /// </param> /// <param name='originName'> /// Name of the origin which is unique within the endpoint. /// </param> /// <param name='originUpdateProperties'> /// Origin properties /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Origin> BeginUpdateAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the existing origins within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Origin> ListByEndpointNext(this IOriginsOperations operations, string nextPageLink) { return operations.ListByEndpointNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists all of the existing origins within an endpoint. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Origin>> ListByEndpointNextAsync(this IOriginsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEndpointNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* Genuine Channels product. * * Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved. * * This source code comes under and must be used and distributed according to the Genuine Channels license agreement. */ using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Web; using Belikov.Common.ThreadProcessing; using Belikov.GenuineChannels.BufferPooling; using Belikov.GenuineChannels.Connection; using Belikov.GenuineChannels.DotNetRemotingLayer; using Belikov.GenuineChannels.Logbook; using Belikov.GenuineChannels.Messaging; using Belikov.GenuineChannels.Parameters; using Belikov.GenuineChannels.Receiving; using Belikov.GenuineChannels.Security; using Belikov.GenuineChannels.TransportContext; using Belikov.GenuineChannels.Utilities; using Zyan.SafeDeserializationHelpers; namespace Belikov.GenuineChannels.GenuineHttp { /// <summary> /// Intercepts incoming requests come to the registered web handler and processes them. /// </summary> internal class HttpServerConnectionManager : ConnectionManager, ITimerConsumer { /// <summary> /// Constructs an instance of the HttpServerConnectionManager class. /// </summary> /// <param name="iTransportContext">The transport context.</param> public HttpServerConnectionManager(ITransportContext iTransportContext) : base(iTransportContext) { this.Local = new HostInformation("_ghttp://" + iTransportContext.HostIdentifier, iTransportContext); this._releaseConnections_InspectPersistentConnections = new PersistentConnectionStorage.ProcessConnectionEventHandler(this.ReleaseConnections_InspectPersistentConnections); this._internal_TimerCallback_InspectPersistentConnections = new PersistentConnectionStorage.ProcessConnectionEventHandler(this.Internal_TimerCallback_InspectPersistentConnections); // calculate host renewing timespan // this._hostRenewingSpan = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]) + GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect]); this._internal_TimerCallback = new WaitCallback(Internal_TimerCallback); this._closeInvocationConnectionAfterInactivity = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.CloseInvocationConnectionAfterInactivity]); TimerProvider.Attach(this); } /// <summary> /// Sends the message to the remote host. /// </summary> /// <param name="message">The message to be sent.</param> protected override void InternalSend(Message message) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; switch (message.SecuritySessionParameters.GenuineConnectionType) { case GenuineConnectionType.Persistent: if (message.ConnectionName == null) message.ConnectionName = message.SecuritySessionParameters.ConnectionName; HttpServerConnection httpServerConnection = this._persistent.Get(message.Recipient.Uri, message.ConnectionName) as HttpServerConnection; if (httpServerConnection == null) throw GenuineExceptions.Get_Send_DestinationIsUnreachable(message.Recipient.Uri); bool messageWasSent = false; lock (httpServerConnection.Listener_Lock) { if (httpServerConnection.Listener != null) { try { // the listener request is available - send the message through it if (httpServerConnection.Listener.HttpContext.Response.IsClientConnected) { messageWasSent = true; // some data is available, gather the stream and send it GenuineChunkedStream responseStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.Usual, httpServerConnection.Listener_SequenceNo, message.Recipient); MessageCoder.FillInLabelledStream(message, httpServerConnection.Listener_MessageContainer, httpServerConnection.Listener_MessagesBeingSent, responseStream, httpServerConnection.Listener_IntermediateBuffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 ) { for ( int i = 0; i < httpServerConnection.Listener_MessagesBeingSent.Count; i++) { Message nextMessage = (Message) httpServerConnection.Listener_MessagesBeingSent[i]; binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "HttpServerConnectionManager.InternalSend", LogMessageType.MessageIsSentAsynchronously, null, nextMessage, httpServerConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.Listener_SecuritySession, null, httpServerConnection.DbgConnectionId, httpServerConnection.Listener_SequenceNo, 0, 0, null, null, null, null, "The message will be sent in the LISTENER stream N: {0}.", httpServerConnection.Listener_SequenceNo); } } httpServerConnection.Listener_SentStream = responseStream; this.LowLevel_SendStream(httpServerConnection.Listener.HttpContext, true, httpServerConnection, true, ref httpServerConnection.Listener_SentStream, httpServerConnection); } } catch(Exception ex) { // a client is expected to re-request this data // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.InternalSend", LogMessageType.ConnectionEstablishing, ex, null, httpServerConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Asynchronous sending failed. Listener seq no: {0}.", httpServerConnection.Listener_SequenceNo); } } finally { httpServerConnection.Listener.Complete(false); httpServerConnection.Listener = null; } } if (! messageWasSent) { try { // there is no listener requests available, so put the message into the queue httpServerConnection.Listener_MessageContainer.AddMessage(message, false); } catch(Exception ex) { // too many messages in the queue httpServerConnection.Dispose(ex); this.ITransportContext.KnownHosts.ReleaseHostResources(message.Recipient, ex); } } } break; case GenuineConnectionType.Named: // named connections are not supported throw new NotSupportedException("The named pattern is not supported by the GHTTP server channel."); case GenuineConnectionType.Invocation: // I/connectionId lock (this._invocation.SyncRoot) { if (this._invocation.ContainsKey(message.SecuritySessionParameters.ConnectionName)) { // the response has been already registered if (this._invocation[message.SecuritySessionParameters.ConnectionName] != null) throw GenuineExceptions.Get_Processing_LogicError("The response has been already registered."); this._invocation[message.SecuritySessionParameters.ConnectionName] = message; break; } } // there is no invocation connection awaiting for this response throw GenuineExceptions.Get_Send_DestinationIsUnreachable(message.SecuritySessionParameters.ConnectionName); } } #region -- Handling incoming requests ------------------------------------------------------ private int _closeInvocationConnectionAfterInactivity; /// <summary> /// Handles the incoming HTTP request. /// </summary> /// <param name="httpServerRequestResultAsObject">The HTTP request.</param> public void HandleIncomingRequest(object httpServerRequestResultAsObject) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; HttpServerRequestResult httpServerRequestResult = (HttpServerRequestResult) httpServerRequestResultAsObject; HttpServerConnection httpServerConnection = null; bool postponeResponse = false; try { // get the stream HttpRequest httpRequest = httpServerRequestResult.HttpContext.Request; Stream incomingStream = httpRequest.InputStream; if (incomingStream.Length <= 0) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest", LogMessageType.LowLevelTransport_AsyncReceivingCompleted, null, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Empty content has been received. It will be ignored."); } return ; } // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { bool writeContent = binaryLogWriter[LogCategory.LowLevelTransport] > 1; GenuineChunkedStream content = null; if (writeContent) { content = new GenuineChunkedStream(false); GenuineUtility.CopyStreamToStream(incomingStream, content); } binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpServerConnectionManager.HandleIncomingRequest", LogMessageType.LowLevelTransport_AsyncReceivingCompleted, null, null, null, writeContent ? content : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, -1, (int) httpServerRequestResult.HttpContext.Request.ContentLength, httpServerRequestResult.HttpContext.Request.UserHostAddress, null, null, "HTTP request has been received."); if (writeContent) incomingStream = content; } BinaryReader binaryReader = new BinaryReader(incomingStream); // read the header byte protocolVersion; GenuineConnectionType genuineConnectionType; Guid hostId; HttpPacketType httpPacketType; int sequenceNo; string connectionName; int remoteHostUniqueIdentifier; HttpMessageCoder.ReadRequestHeader(binaryReader, out protocolVersion, out genuineConnectionType, out hostId, out httpPacketType, out sequenceNo, out connectionName, out remoteHostUniqueIdentifier); HostInformation remote = this.ITransportContext.KnownHosts["_ghttp://" + hostId.ToString("N")]; remote.ProtocolVersion = protocolVersion; // remote.Renew(this._hostRenewingSpan, false); remote.PhysicalAddress = httpRequest.UserHostAddress; // raise an event if we were not recognized remote.UpdateUri(remote.Uri, remoteHostUniqueIdentifier); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest", LogMessageType.ReceivingFinished, null, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "HTTP request is being processed. Packet type: {0}. Sequence no: {1}. Content length: {2}. Host address: {3}.", Enum.Format(typeof(HttpPacketType), httpPacketType, "g"), sequenceNo, httpRequest.ContentLength, httpRequest.UserHostAddress); } // prepare the output stream GenuineChunkedStream outputStream = new GenuineChunkedStream(false); BinaryWriter binaryWriter = new BinaryWriter(outputStream); HttpMessageCoder.WriteResponseHeader(binaryWriter, protocolVersion, this.ITransportContext.ConnectionManager.Local.Uri, sequenceNo, httpPacketType, remote.LocalHostUniqueIdentifier); // analyze the received packet switch(genuineConnectionType) { case GenuineConnectionType.Persistent: { // get the server connection lock (remote.PersistentConnectionEstablishingLock) { httpServerConnection = this._persistent.Get(remote.Uri, connectionName) as HttpServerConnection; if (httpServerConnection != null && httpServerConnection._disposed) httpServerConnection = null; // initialize CLSS from the very beginning, if necessary if (httpPacketType == HttpPacketType.Establishing_ResetConnection) { if (httpServerConnection != null) httpServerConnection.Dispose(GenuineExceptions.Get_Receive_ConnectionClosed("Client sends Establishing_ResetCLSS flag.")); httpServerConnection = null; } if (httpServerConnection == null) { // create the new connection httpServerConnection = new HttpServerConnection(this.ITransportContext, hostId, remote, connectionName, GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]) + GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.MaxTimeSpanToReconnect])); if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteConnectionParameterEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest", LogMessageType.ConnectionParameters, null, remote, this.ITransportContext.IParameterProvider, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.DbgConnectionId, "HTTP connection is being established."); } this._persistent.Set(remote.Uri, connectionName, httpServerConnection); // and CLSS string securitySessionName = this.ITransportContext.IParameterProvider[GenuineParameter.SecuritySessionForPersistentConnections] as string; if (securitySessionName != null) { httpServerConnection.Sender_SecuritySession = this.ITransportContext.IKeyStore.GetKey(securitySessionName).CreateSecuritySession(securitySessionName, null); httpServerConnection.Listener_SecuritySession = this.ITransportContext.IKeyStore.GetKey(securitySessionName).CreateSecuritySession(securitySessionName, null); } // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest", LogMessageType.ConnectionEstablished, null, null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.Sender_SecuritySession, securitySessionName, httpServerConnection.DbgConnectionId, (int) GenuineConnectionType.Persistent, 0, 0, this.GetType().Name, null, null, null, "The connection is being established."); } // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 ) { binaryLogWriter.WriteHostInformationEvent("HttpServerConnectionManager.HandleIncomingRequest", LogMessageType.HostInformationCreated, null, remote, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.Sender_SecuritySession, securitySessionName, httpServerConnection.DbgConnectionId, "HostInformation is ready for actions."); } this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.GHttpConnectionAccepted, null, remote, httpRequest.UserHostAddress)); } } httpServerConnection.Renew(); httpServerConnection.SignalState(GenuineEventType.GeneralConnectionEstablished, null, null); switch(httpPacketType) { case HttpPacketType.Establishing_ResetConnection: case HttpPacketType.Establishing: Stream clsseStream = Stream.Null; // establish the CLSS // P/Sender int length = binaryReader.ReadInt32(); if (httpServerConnection.Sender_SecuritySession != null) { using (Stream senderClssReading = new DelimiterStream(incomingStream, length)) { clsseStream = httpServerConnection.Sender_SecuritySession.EstablishSession( senderClssReading, true); } } if (clsseStream == null) clsseStream = Stream.Null; using (new GenuineChunkedStreamSizeLabel(outputStream)) GenuineUtility.CopyStreamToStream(clsseStream, outputStream); // P/Listener length = binaryReader.ReadInt32(); clsseStream = Stream.Null; if (httpServerConnection.Listener_SecuritySession != null) clsseStream = httpServerConnection.Listener_SecuritySession.EstablishSession( new DelimiterStream(incomingStream, length), true); if (clsseStream == null) clsseStream = Stream.Null; using (new GenuineChunkedStreamSizeLabel(outputStream)) GenuineUtility.CopyStreamToStream(clsseStream, outputStream); // write the answer Stream finalStream = outputStream; this.LowLevel_SendStream(httpServerRequestResult.HttpContext, false, null, false, ref finalStream, httpServerConnection); break; case HttpPacketType.Listening: postponeResponse = this.LowLevel_ProcessListenerRequest(httpServerRequestResult, httpServerConnection, sequenceNo); break; case HttpPacketType.Usual: this.LowLevel_ProcessSenderRequest(genuineConnectionType, incomingStream, httpServerRequestResult, httpServerConnection, sequenceNo, remote); break; default: // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest", LogMessageType.Error, GenuineExceptions.Get_Debugging_GeneralWarning("Unexpected type of the packet."), null, remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpServerConnection == null ? -1 : httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Unexpected type of the packet. Packet type: {0}. Sequence no: {1}. Content length: {2}. Host address: {3}.", Enum.Format(typeof(HttpPacketType), httpPacketType, "g"), sequenceNo, httpRequest.ContentLength, httpRequest.UserHostAddress); } break; } } break; case GenuineConnectionType.Named: throw new NotSupportedException("Named connections are not supported."); case GenuineConnectionType.Invocation: // renew the host remote.Renew(this._closeInvocationConnectionAfterInactivity, false); this.LowLevel_ProcessSenderRequest(genuineConnectionType, incomingStream, httpServerRequestResult, null, sequenceNo, remote); break; } } catch(Exception ex) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.HandleIncomingRequest", LogMessageType.ReceivingFinished, ex, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Error occurred while processing incoming HTTP request."); } } finally { if (! postponeResponse) httpServerRequestResult.Complete(true); } } #endregion #region -- Low-level members --------------------------------------------------------------- /// <summary> /// Handles the listener request. /// </summary> /// <param name="httpServerRequestResult">The request.</param> /// <param name="httpServerConnection">The connection.</param> /// <param name="requestedSequenceNo">The sequence number.</param> /// <returns>True if the response should be delayed.</returns> public bool LowLevel_ProcessListenerRequest(HttpServerRequestResult httpServerRequestResult, HttpServerConnection httpServerConnection, int requestedSequenceNo) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; GenuineChunkedStream responseStream = null; lock (httpServerConnection.Listener_Lock) { // if there is an already registered listener request, release it if (httpServerConnection.Listener != null) { try { this.LowLevel_ReportServerError(httpServerConnection.Listener.HttpContext); } finally { httpServerConnection.Listener.Complete(false); httpServerConnection.Listener = null; } } try { Debug.Assert(httpServerConnection.Listener == null); // if the previous content requested - send it if (requestedSequenceNo == httpServerConnection.Listener_SequenceNo && httpServerConnection.Listener_SentStream != null) { httpServerConnection.Listener_SentStream.Position = 0; this.LowLevel_SendStream(httpServerRequestResult.HttpContext, true, httpServerConnection, false, ref httpServerConnection.Listener_SentStream, httpServerConnection); return false; } // if too old content version requested - send an error if (requestedSequenceNo < httpServerConnection.Listener_SequenceNo || requestedSequenceNo > httpServerConnection.Listener_SequenceNo + 1) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { string errorMessage = string.Format("Desynchronization error. Current sequence number: {0}. Requested sequence number: {1}.", httpServerConnection.Listener_SequenceNo, requestedSequenceNo); binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ProcessListenerRequest", LogMessageType.Error, GenuineExceptions.Get_Debugging_GeneralWarning(errorMessage), null, httpServerConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, errorMessage); } // send the error Stream errorResponseStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.Desynchronization, requestedSequenceNo, httpServerConnection.Remote); MessageCoder.FillInLabelledStream(null, null, null, (GenuineChunkedStream) errorResponseStream, httpServerConnection.Listener_IntermediateBuffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]); this.LowLevel_SendStream(httpServerRequestResult.HttpContext, true, httpServerConnection, true, ref errorResponseStream, httpServerConnection); return false; } // the next sequence is requested if (httpServerConnection.Listener_SentStream != null) { // release the content httpServerConnection.Listener_MessagesBeingSent.Clear(); httpServerConnection.Listener_SentStream.Close(); httpServerConnection.Listener_SentStream = null; } Message message = httpServerConnection.Listener_MessageContainer.GetMessage(); if (message == null) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ProcessListenerRequest", LogMessageType.ReceivingFinished, null, null, httpServerConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Listener request is postponed."); } // no data is available, postpone the request httpServerConnection.Listener_Opened = GenuineUtility.TickCount; httpServerConnection.Listener = httpServerRequestResult; httpServerConnection.Listener_SequenceNo = requestedSequenceNo; return true; } // some data is available, gather the stream and send it responseStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.Usual, requestedSequenceNo, httpServerConnection.Remote); MessageCoder.FillInLabelledStream(message, httpServerConnection.Listener_MessageContainer, httpServerConnection.Listener_MessagesBeingSent, responseStream, httpServerConnection.Listener_IntermediateBuffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]); // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0 ) { for ( int i = 0; i < httpServerConnection.Listener_MessagesBeingSent.Count; i++) { Message nextMessage = (Message) httpServerConnection.Listener_MessagesBeingSent[i]; binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "HttpServerConnectionManager.LowLevel_ProcessListenerRequest", LogMessageType.MessageIsSentAsynchronously, null, nextMessage, httpServerConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnection.Listener_SecuritySession, null, httpServerConnection.DbgConnectionId, httpServerConnection.Listener_SequenceNo, 0, 0, null, null, null, null, "The message is sent in the LISTENER stream N: {0}.", httpServerConnection.Listener_SequenceNo); } } httpServerConnection.Listener_SentStream = responseStream; httpServerConnection.Listener_SequenceNo = requestedSequenceNo; this.LowLevel_SendStream(httpServerRequestResult.HttpContext, true, httpServerConnection, true, ref httpServerConnection.Listener_SentStream, httpServerConnection); } catch(Exception ex) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ProcessListenerRequest", LogMessageType.Error, ex, null, httpServerConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Error occurred while processing the listener request N: {0}.", httpServerConnection.Listener_SequenceNo); } } } return false; } /// <summary> /// Processes the sender's request. /// </summary> /// <param name="genuineConnectionType">The type of the connection.</param> /// <param name="input">The incoming data.</param> /// <param name="httpServerRequestResult">The request.</param> /// <param name="httpServerConnection">The connection.</param> /// <param name="sequenceNo">The sequence number.</param> /// <param name="remote">The information about remote host.</param> public void LowLevel_ProcessSenderRequest(GenuineConnectionType genuineConnectionType, Stream input, HttpServerRequestResult httpServerRequestResult, HttpServerConnection httpServerConnection, int sequenceNo, HostInformation remote) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; GenuineChunkedStream outputStream = null; // parse the incoming stream bool directExecution = genuineConnectionType != GenuineConnectionType.Persistent; BinaryReader binaryReader = new BinaryReader(input); using (BufferKeeper bufferKeeper = new BufferKeeper(0)) { switch(genuineConnectionType) { case GenuineConnectionType.Persistent: Exception gotException = null; try { if (httpServerConnection.Sender_SecuritySession != null) { input = httpServerConnection.Sender_SecuritySession.Decrypt(input); binaryReader = new BinaryReader(input); } while (binaryReader.ReadByte() == 0) using(LabelledStream labelledStream = new LabelledStream(this.ITransportContext, input, bufferKeeper.Buffer)) { GenuineChunkedStream receivedContent = new GenuineChunkedStream(true); GenuineUtility.CopyStreamToStream(labelledStream, receivedContent); this.ITransportContext.IIncomingStreamHandler.HandleMessage(receivedContent, httpServerConnection.Remote, genuineConnectionType, httpServerConnection.ConnectionName, httpServerConnection.DbgConnectionId, false, this._iMessageRegistrator, httpServerConnection.Sender_SecuritySession, httpServerRequestResult); } } catch(Exception ex) { gotException = ex; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ProcessSenderRequest", LogMessageType.Error, ex, null, httpServerConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "Error occurred while processing the sender request N: {0}.", httpServerConnection.Sender_SequenceNo); } } if (gotException != null) { gotException = OperationException.WrapException(gotException); outputStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.SenderError, sequenceNo, remote); var binaryFormatter = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Other)).Safe(); binaryFormatter.Serialize(outputStream, gotException); } else { // serialize and send the empty response outputStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.SenderResponse, sequenceNo, remote); MessageCoder.FillInLabelledStream(null, null, null, outputStream, bufferKeeper.Buffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]); } break; case GenuineConnectionType.Invocation: // register the http context as an invocation waiters string connectionGuid = Guid.NewGuid().ToString("N"); try { if (binaryReader.ReadByte() != 0) { // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteImplementationWarningEvent("HttpServerConnectionManager.LowLevel_ProcessSenderRequest", LogMessageType.Error, GenuineExceptions.Get_Debugging_GeneralWarning("The invocation request doesn't contain any messages."), GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, "The invocation request doesn't contain any messages."); } } using(LabelledStream labelledStream = new LabelledStream(this.ITransportContext, input, bufferKeeper.Buffer)) { // process the response this._invocation[connectionGuid] = null; this.ITransportContext.IIncomingStreamHandler.HandleMessage(labelledStream, remote, genuineConnectionType, connectionGuid, -1, true, null, null, httpServerRequestResult); } if (binaryReader.ReadByte() != 1) { // LOG: if ( binaryLogWriter != null ) { binaryLogWriter.WriteImplementationWarningEvent("HttpServerConnectionManager.LowLevel_ProcessSenderRequest", LogMessageType.Error, GenuineExceptions.Get_Debugging_GeneralWarning("The invocation request must not contain more than one message."), GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, "The invocation request must not contain more than one message."); } } // if there is a response, serialize it outputStream = this.LowLevel_CreateStreamWithHeader(HttpPacketType.Usual, sequenceNo, remote); Message message = this._invocation[connectionGuid] as Message; MessageCoder.FillInLabelledStream(message, null, null, outputStream, bufferKeeper.Buffer, (int) this.ITransportContext.IParameterProvider[GenuineParameter.HttpRecommendedPacketSize]); } finally { this._invocation.Remove(connectionGuid); } break; } } // report back to the client Stream finalStream = outputStream; this.LowLevel_SendStream(httpServerRequestResult.HttpContext, false, null, true, ref finalStream, httpServerConnection); } /// <summary> /// Creates and returns the stream with a written response header. /// </summary> /// <param name="httpPacketType">The type of the packet.</param> /// <param name="sequenceNo">The sequence number.</param> /// <param name="remote">The HostInformation of the remote host.</param> /// <returns>The stream with a written response header.</returns> public GenuineChunkedStream LowLevel_CreateStreamWithHeader(HttpPacketType httpPacketType, int sequenceNo, HostInformation remote) { GenuineChunkedStream output = new GenuineChunkedStream(false); BinaryWriter binaryWriter = new BinaryWriter(output); HttpMessageCoder.WriteResponseHeader(binaryWriter, remote.ProtocolVersion, this.ITransportContext.ConnectionManager.Local.Uri, sequenceNo, httpPacketType, remote.LocalHostUniqueIdentifier); return output; } /// <summary> /// Sends the response to the remote host. /// </summary> /// <param name="httpContext">The http context.</param> /// <param name="listener">True if it's a listener.</param> /// <param name="httpServerConnection">The connection containing CLSS.</param> /// <param name="applyClss">Indicates whether it is necessary to apply Connection Level Security Session.</param> /// <param name="content">The content being sent to the remote host.</param> /// <param name="httpServerConnectionForDebugging">The connection that will be mentioned in the debug records.</param> public void LowLevel_SendStream(HttpContext httpContext, bool listener, HttpServerConnection httpServerConnection, bool applyClss, ref Stream content, HttpServerConnection httpServerConnectionForDebugging) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; try { if (applyClss) { // detect clss SecuritySession clss = null; if (httpServerConnection != null && listener && httpServerConnection.Listener_SecuritySession != null && httpServerConnection.Listener_SecuritySession.IsEstablished) clss = httpServerConnection.Listener_SecuritySession; if (httpServerConnection != null && ! listener && httpServerConnection.Sender_SecuritySession != null && httpServerConnection.Sender_SecuritySession.IsEstablished) clss = httpServerConnection.Sender_SecuritySession; // apply clss if (clss != null) { GenuineChunkedStream encryptedContent = new GenuineChunkedStream(false); clss.Encrypt(content, encryptedContent); content = encryptedContent; } } #if DEBUG Debug.Assert(content.CanSeek); Debug.Assert(content.Length >= 0); #endif // prepare the response HttpResponse response = httpContext.Response; response.ContentType = "application/octet-stream"; response.StatusCode = 200; response.StatusDescription = "OK"; int contentLength = (int) content.Length; response.AppendHeader("Content-Length", contentLength.ToString() ); // write the response Stream responseStream = response.OutputStream; GenuineUtility.CopyStreamToStream(content, responseStream, contentLength); this.ITransportContext.ConnectionManager.IncreaseBytesSent(contentLength); #if DEBUG // the content must end up here Debug.Assert(content.ReadByte() == -1); #endif // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { bool writeContent = binaryLogWriter[LogCategory.LowLevelTransport] > 1; GenuineChunkedStream copiedContent = null; if (writeContent) { copiedContent = new GenuineChunkedStream(false); GenuineUtility.CopyStreamToStream(content, copiedContent); } binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "HttpServerConnectionManager.LowLevel_SendStream", LogMessageType.LowLevelTransport_AsyncSendingInitiating, null, null, httpServerConnectionForDebugging.Remote, copiedContent, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, httpServerConnectionForDebugging.DbgConnectionId, (int) content.Length, null, null, null, "Response is sent back to the client. Buffer: {0}; BufferOutput: {1}; Charset: {2}; ContentEncoding: {3}; ContentType: {4}; IsClientConnected: {5}; StatusCode: {6}; StatusDescription: {7}; SuppressContent: {8}; Content-Length: {9}. Connection: {10}.", response.Buffer, response.BufferOutput, response.Charset, response.ContentEncoding, response.ContentType, response.IsClientConnected, response.StatusCode, response.StatusDescription, response.SuppressContent, contentLength, listener ? "LISTENER" : "SENDER"); } } catch(Exception ex) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_SendStream", LogMessageType.MessageIsSentAsynchronously, ex, null, httpServerConnectionForDebugging.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, httpServerConnectionForDebugging.DbgConnectionId, 0, 0, 0, null, null, null, null, "Error occurred while sending a response."); } throw; } } /// <summary> /// Sends the response to the remote host. /// </summary> /// <param name="httpContext">The http context.</param> public void LowLevel_ReportServerError(HttpContext httpContext) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; try { // prepare the response HttpResponse response = httpContext.Response; response.ContentType = "application/octet-stream"; response.StatusCode = 409; response.StatusDescription = "Conflict"; response.AppendHeader ( "Content-Length", "0" ); } catch (Exception ex) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.LowLevel_ReportServerError", LogMessageType.Error, ex, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Error occurred while sending 409/conflict error."); } } } #endregion #region -- Pool management ----------------------------------------------------------------- /// <summary> /// The message registrator. /// </summary> private IMessageRegistrator _iMessageRegistrator = new MessageRegistratorWithLimitedTime(); /// <summary> /// The set of persistent connections (with CLSS and message queues): Uri -> connection. /// </summary> private PersistentConnectionStorage _persistent = new PersistentConnectionStorage(); /// <summary> /// The set of response to messages received via invocation connections (connection Id => Message or a null reference). /// </summary> private Hashtable _invocation = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Sends the packet with empty content and specified type of packet to the remote host /// through the listening connection. /// </summary> /// <param name="httpServerConnection">The connection.</param> /// <param name="httpPacketType">The type of packet.</param> private void Pool_SendThroughListener(HttpServerConnection httpServerConnection, HttpPacketType httpPacketType) { lock (httpServerConnection.Listener_Lock) { if ( httpServerConnection.Listener == null ) return ; try { Stream outputStream = this.LowLevel_CreateStreamWithHeader(httpPacketType, httpServerConnection.Listener_SequenceNo, httpServerConnection.Remote); this.LowLevel_SendStream(httpServerConnection.Listener.HttpContext, true, httpServerConnection, true, ref outputStream, httpServerConnection); } finally { httpServerConnection.Listener.Complete(false); httpServerConnection.Listener = null; } } } #endregion #region -- Resource releasing -------------------------------------------------------------- private PersistentConnectionStorage.ProcessConnectionEventHandler _releaseConnections_InspectPersistentConnections; private class ReleaseConnections_Parameters { public ArrayList FailedConnections; public HostInformation HostInformation; } /// <summary> /// Finds connections to be released. /// </summary> /// <param name="httpServerConnectionAsObject">The connection.</param> /// <param name="releaseConnections_ParametersAsObject">Stuff to make decisions and to save the results.</param> private void ReleaseConnections_InspectPersistentConnections(object httpServerConnectionAsObject, object releaseConnections_ParametersAsObject) { HttpServerConnection httpServerConnection = (HttpServerConnection) httpServerConnectionAsObject; ReleaseConnections_Parameters releaseConnections_Parameters = (ReleaseConnections_Parameters) releaseConnections_ParametersAsObject; if (releaseConnections_Parameters.HostInformation != null && httpServerConnection.Remote != releaseConnections_Parameters.HostInformation) return ; releaseConnections_Parameters.FailedConnections.Add(httpServerConnection); } /// <summary> /// Closes the specified connections to the remote host and releases acquired resources. /// </summary> /// <param name="hostInformation">Host information.</param> /// <param name="genuineConnectionType">What kind of connections will be affected by this operation.</param> /// <param name="reason">The reason of resource releasing.</param> public override void ReleaseConnections(HostInformation hostInformation, GenuineConnectionType genuineConnectionType, Exception reason) { BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; ArrayList connectionsToClose = new ArrayList(); using (new WriterAutoLocker(this._disposeLock)) { if (this._disposed) return ; // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpServerConnectionManager.ReleaseConnections", LogMessageType.ReleaseConnections, reason, null, hostInformation, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, Enum.Format(typeof(GenuineConnectionType), genuineConnectionType, "g"), null, null, null, "Connections \"{0}\" will be terminated.", Enum.Format(typeof(GenuineConnectionType), genuineConnectionType, "g"), null); } // persistent if ( (genuineConnectionType & GenuineConnectionType.Persistent) != 0 ) { // persistent ReleaseConnections_Parameters releaseConnections_Parameters = new ReleaseConnections_Parameters(); releaseConnections_Parameters.FailedConnections = connectionsToClose; releaseConnections_Parameters.HostInformation = hostInformation; this._persistent.InspectAllConnections(this._releaseConnections_InspectPersistentConnections, releaseConnections_Parameters); } // close connections foreach (HttpServerConnection nextHttpServerConnection in connectionsToClose) { lock (nextHttpServerConnection.Listener_Lock) { // LOG: if ( binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0 ) { binaryLogWriter.WriteEvent(LogCategory.Connection, "HttpClientConnectionManager.ReleaseConnections", LogMessageType.ConnectionShuttingDown, reason, null, nextHttpServerConnection.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, nextHttpServerConnection.DbgConnectionId, 0, 0, 0, null, null, null, null, "The connection is being shut down manually."); } nextHttpServerConnection.SignalState(GenuineEventType.GeneralConnectionClosed, reason, null); this._persistent.Remove(nextHttpServerConnection.Remote.Uri, nextHttpServerConnection.ConnectionName); if (nextHttpServerConnection.Listener != null) this.Pool_SendThroughListener(nextHttpServerConnection, HttpPacketType.ClosedManually); } } } } /// <summary> /// Returns names of connections opened to the specified destination. /// Not all Connection Manager support this member. /// </summary> /// <param name="uri">The URI or URL of the remote host.</param> /// <returns>Names of connections opened to the specified destination.</returns> public override string[] GetConnectionNames(string uri) { string ignored; uri = GenuineUtility.Parse(uri, out ignored); return this._persistent.GetAll(uri); } /// <summary> /// Releases all resources. /// </summary> /// <param name="reason">The reason of disposing.</param> public override void InternalDispose(Exception reason) { this.ReleaseConnections(null, GenuineConnectionType.All, reason); } /// <summary> /// Closes expired connections and sends ping via inactive connections. /// </summary> public void TimerCallback() { GenuineThreadPool.QueueUserWorkItem(_internal_TimerCallback, null, false); } private WaitCallback _internal_TimerCallback; private PersistentConnectionStorage.ProcessConnectionEventHandler _internal_TimerCallback_InspectPersistentConnections; private class Internal_TimerCallback_Parameters { public ArrayList SendPingTo = new ArrayList(); public ArrayList ExpiredConnections = new ArrayList(); public int CloseListenerConnectionsAfter; public int Now; } /// <summary> /// Finds connections to be released. /// </summary> /// <param name="httpServerConnectionAsObject">The connection.</param> /// <param name="parametersAsObject">Stuff to make decisions and to save the results.</param> private void Internal_TimerCallback_InspectPersistentConnections(object httpServerConnectionAsObject, object parametersAsObject) { HttpServerConnection httpServerConnection = (HttpServerConnection) httpServerConnectionAsObject; Internal_TimerCallback_Parameters parameters = (Internal_TimerCallback_Parameters) parametersAsObject; lock (httpServerConnection.Remote.PersistentConnectionEstablishingLock) { if (GenuineUtility.IsTimeoutExpired(httpServerConnection.ShutdownTime, parameters.Now)) parameters.ExpiredConnections.Add(httpServerConnection); if (httpServerConnection.Listener != null && GenuineUtility.IsTimeoutExpired(httpServerConnection.Listener_Opened + parameters.CloseListenerConnectionsAfter, parameters.Now)) parameters.SendPingTo.Add(httpServerConnection); } } /// <summary> /// Closes expired connections and sends ping via inactive connections. /// </summary> /// <param name="ignored">Ignored.</param> private void Internal_TimerCallback(object ignored) { Internal_TimerCallback_Parameters internal_TimerCallback_Parameters = new Internal_TimerCallback_Parameters(); internal_TimerCallback_Parameters.ExpiredConnections = new ArrayList(); internal_TimerCallback_Parameters.SendPingTo = new ArrayList(); internal_TimerCallback_Parameters.CloseListenerConnectionsAfter = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]); internal_TimerCallback_Parameters.Now = GenuineUtility.TickCount; // go through the pool and close all expired connections this._persistent.InspectAllConnections(this._internal_TimerCallback_InspectPersistentConnections, internal_TimerCallback_Parameters); // send ping to expired foreach (HttpServerConnection httpServerConnection in internal_TimerCallback_Parameters.SendPingTo) this.Pool_SendThroughListener(httpServerConnection, HttpPacketType.ListenerTimedOut); // close expired connections foreach (HttpServerConnection httpServerConnection in internal_TimerCallback_Parameters.ExpiredConnections) { // just remove it silently this._persistent.Remove(httpServerConnection.Remote.Uri, httpServerConnection.ConnectionName); if (httpServerConnection.Listener != null) this.Pool_SendThroughListener(httpServerConnection, HttpPacketType.ClosedManually); } } #endregion #region -- Listening ----------------------------------------------------------------------- /// <summary> /// Starts listening to the specified end point and accepting incoming connections. /// </summary> /// <param name="endPoint">The end point.</param> public override void StartListening(object endPoint) { throw new NotSupportedException(); } /// <summary> /// Stops listening to the specified end point. Does not close any connections. /// </summary> /// <param name="endPoint">The end point</param> public override void StopListening(object endPoint) { throw new NotSupportedException(); } #endregion } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using DequeNet.Debugging; //Disable "a reference to a volatile field will not be treated as volatile" warnings. //As per the MSDN documentation: "There are exceptions to this, such as when calling an interlocked API". #pragma warning disable 420 // ReSharper disable InconsistentNaming namespace DequeNet { /// <summary> /// Represents a thread-safe lock-free concurrent double-ended queue, also known as deque (pronounced "deck"). /// Items can be appended to/removed from both ends of the deque. /// </summary> /// <typeparam name="T">Specifies the type of the elements in the deque.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ConcurrentDequeDebugView<>))] public class ConcurrentDeque<T> : IConcurrentDeque<T> { internal volatile Anchor _anchor; /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentDeque{T}"/> is empty. /// </summary> public bool IsEmpty { get { return _anchor._left == null; } } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentDeque{T}"/>. /// </summary> public int Count { get { return ToList().Count; } } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentDeque{T}"/> class. /// </summary> public ConcurrentDeque() { _anchor = new Anchor(); } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentDeque{T}"/> class /// that contains elements copied from the specified collection. /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see cref="ConcurrentDeque{T}"/>.</param> /// <exception cref="ArgumentNullException"> /// The <paramref name="collection"/> argument is null.c /// </exception> public ConcurrentDeque(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException("collection"); InitializeFromCollection(collection); } /// <summary> /// Initialize the contents of the deque from an existing collection. /// </summary> /// <param name="collection">A collection from which to copy elements.</param> private void InitializeFromCollection(IEnumerable<T> collection) { var iterator = collection.GetEnumerator(); if (iterator.MoveNext()) { Node first = new Node(iterator.Current); Node last = first; while (iterator.MoveNext()) { //create node and assign pointers Node newLast = new Node(iterator.Current) { _left = last }; last._right = newLast; //replace last node last = newLast; } //initialize anchor _anchor = new Anchor(first, last, DequeStatus.Stable); } else { //collection is empty _anchor = new Anchor(); } } /// <summary> /// Adds an item to the right end of the <see cref="ConcurrentDeque{T}"/>. /// </summary> /// <param name="item">The item to be added to the <see cref="ConcurrentDeque{T}"/>.</param> public void PushRight(T item) { var newNode = new Node(item); var spinner = new SpinWait(); while (true) { var anchor = _anchor; anchor.Validate(); //If the deque is empty if (anchor._right == null) { //update both pointers to point to the new node var newAnchor = new Anchor(newNode, newNode, anchor._status); if (Interlocked.CompareExchange(ref _anchor, newAnchor, anchor) == anchor) return; } else if (anchor._status == DequeStatus.Stable) { //make new node point to the rightmost node newNode._left = anchor._right; //update the anchor's right pointer //and change the status to RPush var newAnchor = new Anchor(anchor._left, newNode, DequeStatus.RPush); if (Interlocked.CompareExchange(ref _anchor, newAnchor, anchor) == anchor) { //stabilize deque StabilizeRight(newAnchor); return; } } else { //if the deque is unstable, //attempt to bring it to a stable state before trying to insert the node. Stabilize(anchor); } spinner.SpinOnce(); } } /// <summary> /// Adds an item to the left end of the <see cref="ConcurrentDeque{T}"/>. /// </summary> /// <param name="item">The item to be added to the <see cref="ConcurrentDeque{T}"/>.</param> public void PushLeft(T item) { var newNode = new Node(item); var spinner = new SpinWait(); while (true) { var anchor = _anchor; anchor.Validate(); //If the deque is empty if (anchor._left == null) { //update both pointers to point to the new node var newAnchor = new Anchor(newNode, newNode, anchor._status); if (Interlocked.CompareExchange(ref _anchor, newAnchor, anchor) == anchor) return; } else if (anchor._status == DequeStatus.Stable) { //make new node point to the leftmost node newNode._right = anchor._left; //update anchor's left pointer //and change the status to LPush var newAnchor = new Anchor(newNode, anchor._right, DequeStatus.LPush); if (Interlocked.CompareExchange(ref _anchor, newAnchor, anchor) == anchor) { //stabilize deque StabilizeLeft(newAnchor); return; } } else { //if the deque is unstable, //attempt to bring it to a stable state before trying to insert the node. Stabilize(anchor); } spinner.SpinOnce(); } } /// <summary> /// Attempts to remove and return an item from the right end of the <see cref="ConcurrentDeque{T}"/>. /// </summary> /// <param name="item">When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified.</param> /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns> public bool TryPopRight(out T item) { Anchor anchor; var spinner = new SpinWait(); while (true) { anchor = _anchor; anchor.Validate(); if (anchor._right == null) { //return false if the deque is empty item = default(T); return false; } if (anchor._right == anchor._left) { //update both pointers if the deque has only one node var newAnchor = new Anchor(); if (Interlocked.CompareExchange(ref _anchor, newAnchor, anchor) == anchor) break; } else if (anchor._status == DequeStatus.Stable) { //update right pointer if deque has > 1 node var prev = anchor._right._left; var newAnchor = new Anchor(anchor._left, prev, anchor._status); if (Interlocked.CompareExchange(ref _anchor, newAnchor, anchor) == anchor) break; } else { //if the deque is unstable, //attempt to bring it to a stable state before trying to remove the node. Stabilize(anchor); } spinner.SpinOnce(); } var node = anchor._right; item = node._value; /* * Try to set the new rightmost node's right pointer to null to avoid memory leaks. * We try only once - if CAS fails, then another thread must have pushed a new node, in which case we simply carry on. */ var rightmostNode = node._left; if (rightmostNode != null) Interlocked.CompareExchange(ref rightmostNode._right, null, node); return true; } /// <summary> /// Attempts to remove and return an item from the left end of the <see cref="ConcurrentDeque{T}"/>. /// </summary> /// <param name="item">When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified.</param> /// <returns>true if an element was removed and returned succesfully; otherwise, false.</returns> public bool TryPopLeft(out T item) { Anchor anchor; var spinner = new SpinWait(); while (true) { anchor = _anchor; anchor.Validate(); if (anchor._left == null) { //return false if the deque is empty item = default(T); return false; } if (anchor._right == anchor._left) { //update both pointers if the deque has only one node var newAnchor = new Anchor(); if (Interlocked.CompareExchange(ref _anchor, newAnchor, anchor) == anchor) break; } else if (anchor._status == DequeStatus.Stable) { //update left pointer if deque has > 1 node var prev = anchor._left._right; var newAnchor = new Anchor(prev, anchor._right, anchor._status); if (Interlocked.CompareExchange(ref _anchor, newAnchor, anchor) == anchor) break; } else { //if the deque is unstable, //attempt to bring it to a stable state before trying to remove the node. Stabilize(anchor); } spinner.SpinOnce(); } var node = anchor._left; item = node._value; /* * Try to set the new leftmost node's left pointer to null to avoid memory leaks. * We try only once - if CAS fails, then another thread must have pushed a new node, in which case we simply carry on. */ var leftmostNode = node._right; if (leftmostNode != null) Interlocked.CompareExchange(ref leftmostNode._left, null, node); return true; } /// <summary> /// Attempts to return the rightmost item of the <see cref="ConcurrentDeque{T}"/> /// without removing it. /// </summary> /// <param name="item">When this method returns, <paramref name="item"/> contains the rightmost item /// of the <see cref="ConcurrentDeque{T}"/> or an unspecified value if the operation failed.</param> /// <returns>true if an item was returned successfully; otherwise, false.</returns> public bool TryPeekRight(out T item) { var rightmostNode = _anchor._right; if (rightmostNode != null) { item = rightmostNode._value; return true; } item = default(T); return false; } /// <summary> /// Attempts to return the leftmost item of the <see cref="ConcurrentDeque{T}"/> /// without removing it. /// </summary> /// <param name="item">When this method returns, <paramref name="item"/> contains the leftmost item /// of the <see cref="ConcurrentDeque{T}"/> or an unspecified value if the operation failed.</param> /// <returns>true if an item was returned successfully; otherwise, false.</returns> public bool TryPeekLeft(out T item) { var leftmostNode = _anchor._left; if (leftmostNode != null) { item = leftmostNode._value; return true; } item = default(T); return false; } private void Stabilize(Anchor anchor) { if(anchor._status == DequeStatus.RPush) StabilizeRight(anchor); else StabilizeLeft(anchor); } /// <summary> /// Stabilizes the deque when in <see cref="DequeStatus.RPush"/> status. /// </summary> /// <remarks> /// Stabilization is done in two steps: /// (1) update the previous rightmost node's right pointer to point to the new rightmost node; /// (2) update the anchor, changing the status to <see cref="DequeStatus.Stable"/>. /// </remarks> /// <param name="anchor"></param> private void StabilizeRight(Anchor anchor) { //quick check to see if the anchor has been updated by another thread if (_anchor != anchor) return; //grab a reference to the new node var newNode = anchor._right; //grab a reference to the previous rightmost node and its right pointer var prev = newNode._left; //quick check to see if the deque has been modified by another thread if (prev == null) return; var prevNext = prev._right; //if the previous rightmost node doesn't point to the new rightmost node, we need to update it if (prevNext != newNode) { /* * Quick check to see if the anchor has been updated by another thread. * If it has been updated, we can't touch the prev node. * Some other thread may have popped the new node, pushed another node and stabilized the deque. * If that's the case, then prev node's right pointer is pointing to the other node. */ if (_anchor != anchor) return; //try to make the previous rightmost node point to the next node. //CAS failure means that another thread already stabilized the deque. if (Interlocked.CompareExchange(ref prev._right, newNode, prevNext) != prevNext) return; } /* * Try to mark the anchor as stable. * This step is done outside of the previous "if" block: * even though another thread may have already updated prev's right pointer, * this thread might still preempt the other and perform the second step (i.e., update the anchor). */ var newAnchor = new Anchor(anchor._left, anchor._right, DequeStatus.Stable); Interlocked.CompareExchange(ref _anchor, newAnchor, anchor); } /// <summary> /// Stabilizes the deque when in <see cref="DequeStatus.LPush"/> status. /// </summary> /// <remarks> /// Stabilization is done in two steps: /// (1) update the previous leftmost node's left pointer to point to the new leftmost node; /// (2) update the anchor, changing the status to <see cref="DequeStatus.Stable"/>. /// </remarks> /// <param name="anchor"></param> private void StabilizeLeft(Anchor anchor) { //quick check to see if the anchor has been updated by another thread if (_anchor != anchor) return; //grab a reference to the new node var newNode = anchor._left; //grab a reference to the previous leftmost node and its left pointer var prev = newNode._right; //quick check to see if the deque has been modified by another thread if (prev == null) return; var prevNext = prev._left; //if the previous leftmost node doesn't point to the new leftmost node, we need to update it if (prevNext != newNode) { /* * Quick check to see if the anchor has been updated by another thread. * If it has been updated, we can't touch the prev node. * Some other thread may have popped the new node, pushed another node and stabilized the deque. * If that's the case, then prev node's left pointer is pointing to the other node. */ if (_anchor != anchor) return; //try to make the previous leftmost node point to the next node. //CAS failure means that another thread already stabilized the deque. if (Interlocked.CompareExchange(ref prev._left, newNode, prevNext) != prevNext) return; } /* * Try to mark the anchor as stable. * This step is done outside of the previous "if" block: * even though another thread may have already updated prev's left pointer, * this thread might still preempt the other and perform the second step (i.e., update the anchor). */ var newAnchor = new Anchor(anchor._left, anchor._right, DequeStatus.Stable); Interlocked.CompareExchange(ref _anchor, newAnchor, anchor); } /// <summary> /// Returns an enumerator that iterates through the <see cref="ConcurrentDeque{T}"/> from left to right. /// </summary> /// <returns>An enumerator for the <see cref="ConcurrentDeque{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the deque. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the deque. /// </remarks> public IEnumerator<T> GetEnumerator() { return ToList().GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the deque. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the deque. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Removes all objects from the <see cref="ConcurrentDeque{T}"/>. /// </summary> public void Clear() { /* * Clear the list by setting the anchor to a new one * with null left and right pointers. */ _anchor = new Anchor(); } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns> /// An object that can be used to synchronize access to the <see cref="ICollection"/>. /// </returns> /// <exception cref="NotSupportedException">The SyncRoot property is not supported.</exception> object ICollection.SyncRoot { get { throw new NotSupportedException("The SyncRoot property may not be used for the synchronization of concurrent collections."); } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns> /// true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false. /// For <see cref="ConcurrentDeque{T}"/>, this property always returns false. /// </returns> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in fact thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Attempts to add an object to the <see cref="IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="IProducerConsumerCollection{T}"/>.</param> /// <returns> /// true if the object was added successfully; otherwise, false. /// </returns> /// <remarks> /// For <see cref="ConcurrentDeque{T}"/>, this operation will always add the object to the right /// end of the <see cref="ConcurrentDeque{T}"/> and return true. /// </remarks> bool IProducerConsumerCollection<T>.TryAdd(T item) { PushRight(item); return true; } /// <summary> /// Attempts to remove and return an object from the <see cref="IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item"> /// When this method returns, if the object was removed and returned successfully, <paramref name="item"/> contains the removed object. /// If no object was available to be removed, the value is unspecified. /// </param> /// <returns> /// true if an object was removed and returned successfully; otherwise, false. /// </returns> /// <remarks> /// For <see cref="ConcurrentDeque{T}"/>, this operation will attempt to remove the object /// from the left end of the <see cref="ConcurrentDeque{T}"/>. /// </remarks> bool IProducerConsumerCollection<T>.TryTake(out T item) { return TryPopLeft(out item); } /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, /// starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array">Array</see> that is the destination of the elements copied from the <see cref="ICollection"/>. The <see cref="Array">Array</see> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see cref="ICollection"/> cannot be cast /// automatically to the type of the destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException("array"); // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the deque's contents. ((ICollection) ToList()).CopyTo(array, index); } /// <summary> /// Copies the <see cref="ConcurrentDeque{T}"/> elements to an existing one-dimensional <see cref="Array">Array</see>, starting at the specified array index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array">Array</see> that is the destination of the elements copied from the <see cref="ConcurrentDeque{T}"/>. The <see cref="Array">Array</see> must have zero-based indexing. /// </param> /// <param name="index"> /// The zero-based index in <paramref name="array"/> at which copying begins. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="array"/> is a null reference (Nothing in Visual Basic). /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than zero. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentDeque{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) throw new ArgumentNullException("array"); // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the deque's contents. ToList().CopyTo(array, index); } /// <summary> /// Copies the items stored in the <see cref="ConcurrentDeque{T}"/> to a new array. /// </summary> /// <returns> /// A new array containing a snapshot of elements copied from the <see cref="ConcurrentDeque{T}"/>. /// </returns> public T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Takes a moment-in-time snapshot of the deque. /// </summary> /// <returns>A list representing a moment-in-time snapshot of the deque.</returns> /// <remarks> /// The algorithm runs in linear O(n) time. /// /// This implementation relies on the following invariant: /// If at time t, x was the leftmost node and y was the rightmost node, /// regardless of how many nodes are pushed/popped from either end thereafter, the paths /// (a) x->a (obtained by traversing the deque recursively using a node's right pointer starting from x), and /// (b) y->b (obtained by traversing the deque recursively using a node's left pointer starting from y) /// will always have at least 1 node in common. /// /// This means that, for a given x and y, even if the deque is mutated during the algorithm's /// execution, we can always rebuild the original x-y sequence by finding a node c, common to both /// x->a and y->b paths, and merging the paths by the common node. /// </remarks> private List<T> ToList() { //try to grab a reference to a stable anchor (fast route) Anchor anchor = _anchor; anchor.Validate(); //try to grab a reference to a stable anchor (slow route) if (anchor._status != DequeStatus.Stable) { var spinner = new SpinWait(); do { anchor = _anchor; anchor.Validate(); spinner.SpinOnce(); } while (anchor._status != DequeStatus.Stable); } var x = anchor._left; var y = anchor._right; //check if deque is empty if(x == null) return new List<T>(); //check if deque has only 1 item if (x == y) return new List<T> {x._value}; var xaPath = new List<Node>(); var current = x; while (current != null && current != y) { xaPath.Add(current); current = current._right; } /* * If the 'y' node hasn't been popped from the right side of the deque, * then we should still be able to find the original x-y sequence * using a node's right pointer. * * If 'current' does not equal 'y', then the 'y' node must have been popped by * another thread during the while loop and the traversal wasn't successful. */ if (current == y) { xaPath.Add(current); return xaPath.Select(node => node._value).ToList(); } /* * If the 'y' node has been popped from the right end, we need to find all nodes that have * been popped from the right end and rebuild the original sequence. * * To do this, we need to traverse the deque from right to left (using a node's left pointer) * until we find a node c common to both x->a and y->b paths. Such a node is either: * (a) currently part of the deque or * (b) the last node of the x->a path (i.e., node 'a') or * (c) the last node to be popped from the left (if all nodes between 'x' and 'y' were popped from the deque). * * -- Predicate (a) -- * A node belongs to the deque if node.left.right == node (except for the leftmost node) if the deque has > 1 nodes. * If the deque has exactly one node, we know we've found that node if: * (1) all nodes to its right in the x-y sequence don't fall under predicates (a), (b) and (c) and * (2) node.left == null * * -- Predicate (b) -- * True for a node n if n == a * * -- Predicate (c) -- * True for a node n if: * (1) all nodes to its right in the x-y sequence don't fall under predicates (a), (b) and (c) and * (2) node.left == null */ current = y; var a = xaPath.Last(); var ycPath = new Stack<Node>(); while (current._left != null && current._left._right != current && current != a) { ycPath.Push(current); current = current._left; } //this node is common to the list and the stack var common = current; ycPath.Push(common); /* * Merge the x->a and the y->c paths by the common node. * This is done by removing the nodes in x->a that come after c, * and appending all nodes in the y->c path in reverse order. * Since we used a LIFO stack to store all nodes in the y->c path, * we can simply iterate over it to reverse the order in which they were inserted. */ var xySequence = xaPath .TakeWhile(node => node != common) .Select(node => node._value) .Concat( ycPath.Select(node => node._value)); return xySequence.ToList(); } internal class Anchor { internal readonly Node _left; internal readonly Node _right; internal readonly DequeStatus _status; internal Anchor() { _right = _left = null; _status = DequeStatus.Stable; } internal Anchor(Node left, Node right, DequeStatus status) { _left = left; _right = right; _status = status; } /// <summary> /// Validates the anchor's state. /// </summary> [Conditional("DEBUG")] public void Validate() { //assert that either both pointers are null or not null Debug.Assert((_left == null && _right == null) || (_left != null && _right != null)); //assert that if the anchor is empty, then it is stable if(_left == null) Debug.Assert(_status == DequeStatus.Stable); } } internal enum DequeStatus { Stable, LPush, RPush }; internal class Node { internal volatile Node _left; internal volatile Node _right; internal readonly T _value; internal Node(T value) { _value = value; } } } } #pragma warning restore 420 // ReSharper restore InconsistentNaming
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Subjects; using Microsoft.Its.Domain.Sql.CommandScheduler; using Microsoft.Its.Recipes; using Pocket; namespace Microsoft.Its.Domain.Sql { /// <summary> /// Provides methods for preparing the domain configuration. /// </summary> public static class ConfigurationExtensions { public static SqlCommandScheduler SqlCommandScheduler(this Configuration configuration) { if (configuration.IsUsingCommandSchedulerPipeline()) { throw new InvalidOperationException("You must first call UseSqlCommandScheduling to enable the use of the legacy SqlCommandScheduler."); } return configuration.Container.Resolve<SqlCommandScheduler>(); } public static ISchedulerClockRepository SchedulerClockRepository(this Configuration configuration) { return configuration.Container.Resolve<ISchedulerClockRepository>(); } public static ISchedulerClockTrigger SchedulerClockTrigger(this Configuration configuration) { return configuration.Container.Resolve<ISchedulerClockTrigger>(); } /// <summary> /// Configures the system to use a SQL-based event store. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="createEventStoreDbContext">A function that returns an <see cref="EventStoreDbContext" />, if something different from the default is desired.</param> /// <returns>The updated configuration.</returns> public static Configuration UseSqlEventStore( this Configuration configuration, Func<EventStoreDbContext> createEventStoreDbContext = null) { configuration.Container.AddStrategy(SqlEventSourcedRepositoryStrategy); configuration.IsUsingSqlEventStore(true); createEventStoreDbContext = createEventStoreDbContext ?? (() => new EventStoreDbContext()); configuration.Container .Register(c => createEventStoreDbContext()) .Register<ICommandPreconditionVerifier>(c => c.Resolve<CommandPreconditionVerifier>()); return configuration; } /// <summary> /// Configures the system to use SQL-backed command scheduling. /// </summary> /// <param name="configuration">The configuration.</param> /// <returns>The updated configuration.</returns> [Obsolete("Please move to UseSqlStorageForScheduledCommands.")] public static Configuration UseSqlCommandScheduling( this Configuration configuration, Action<ReadModelCatchup<CommandSchedulerDbContext>> configureCatchup = null) { var container = configuration.Container; container.RegisterDefaultClockName(); var scheduler = new SqlCommandScheduler( configuration, container.Resolve<Func<CommandSchedulerDbContext>>(), container.Resolve<GetClockName>()); if (container.All(r => r.Key != typeof (SqlCommandScheduler))) { container.Register(c => scheduler) .Register<ISchedulerClockTrigger>(c => scheduler) .Register<ISchedulerClockRepository>(c => scheduler); } var subscription = container.Resolve<IEventBus>().Subscribe(scheduler); configuration.RegisterForDisposal(subscription); container.RegisterSingle(c => scheduler); if (configureCatchup != null) { var catchup = new ReadModelCatchup<CommandSchedulerDbContext>(scheduler) { CreateReadModelDbContext = scheduler.CreateCommandSchedulerDbContext }; configureCatchup(catchup); catchup.PollEventStore(); container.RegisterSingle(c => catchup); configuration.RegisterForDisposal(catchup); } configuration.IsUsingCommandSchedulerPipeline(false); return configuration; } public static Configuration UseSqlStorageForScheduledCommands( this Configuration configuration) { var container = configuration.Container; container.RegisterDefaultClockName() .Register<ISchedulerClockRepository>( c => c.Resolve<SchedulerClockRepository>()) .Register<ICommandPreconditionVerifier>( c => c.Resolve<CommandPreconditionVerifier>()) .Register<ISchedulerClockTrigger>( c => c.Resolve<SchedulerClockTrigger>()); configuration.Container .Resolve<SqlCommandSchedulerPipelineInitializer>() .Initialize(configuration); var schedulerFuncs = new Dictionary<string, Func<dynamic>>(); AggregateType.KnownTypes.ForEach(aggregateType => { var schedulerType = typeof (ICommandScheduler<>).MakeGenericType(aggregateType); schedulerFuncs.Add( AggregateType.EventStreamName(aggregateType), () => container.Resolve(schedulerType)); }); container .Register( c => new SchedulerClockTrigger( c.Resolve<CommandSchedulerDbContext>, async (serializedCommand, result, db) => { dynamic scheduler = schedulerFuncs[serializedCommand.AggregateType]; await Storage.DeserializeAndDeliverScheduledCommand( serializedCommand, scheduler()); result.Add(serializedCommand.Result); serializedCommand.Attempts++; await db.SaveChangesAsync(); })) .Register<ISchedulerClockTrigger>(c => c.Resolve<SchedulerClockTrigger>()); return configuration; } internal static void IsUsingSqlEventStore(this Configuration configuration, bool value) { configuration.Properties["IsUsingSqlEventStore"] = value; } internal static bool IsUsingSqlEventStore(this Configuration configuration) { return configuration.Properties .IfContains("IsUsingSqlEventStore") .And() .IfTypeIs<bool>() .ElseDefault(); } internal static Func<PocketContainer, object> SqlEventSourcedRepositoryStrategy(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (IEventSourcedRepository<>)) { var aggregateType = type.GenericTypeArguments.Single(); var genericType = typeof (SqlEventSourcedRepository<>).MakeGenericType(aggregateType); return c => c.Resolve(genericType); } return null; } internal static ICommandSchedulerDispatcher[] InitializeSchedulersPerAggregateType( PocketContainer container, GetClockName getClockName, ISubject<ICommandSchedulerActivity> subject) { var binders = AggregateType.KnownTypes .Select(aggregateType => { var initializerType = typeof (SchedulerInitializer<>).MakeGenericType(aggregateType); dynamic initializer = container.Resolve(initializerType); return (ICommandSchedulerDispatcher) initializer.InitializeScheduler( subject, container, getClockName); }) .ToArray(); return binders; } internal static PocketContainer RegisterDefaultClockName(this PocketContainer container) { return container.AddStrategy(t => { if (t == typeof (GetClockName)) { return c => new GetClockName(e => CommandScheduler.SqlCommandScheduler.DefaultClockName); } return null; }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Cryptography; using Internal.NativeCrypto; using System.IO; namespace System.Security.Cryptography { public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm { private const int DefaultKeySize = 1024; private readonly RSA _impl; private bool _publicOnly; public RSACryptoServiceProvider() : this(DefaultKeySize) { } public RSACryptoServiceProvider(int dwKeySize) { if (dwKeySize < 0) throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum); // This class wraps RSA _impl = RSA.Create(dwKeySize); } public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters) => throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspParameters))); public RSACryptoServiceProvider(CspParameters parameters) => throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspParameters))); public CspKeyContainerInfo CspKeyContainerInfo => throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspKeyContainerInfo))); public byte[] Decrypt(byte[] rgb, bool fOAEP) { if (rgb == null) throw new ArgumentNullException(nameof(rgb)); // size check -- must be at most the modulus size if (rgb.Length > (KeySize / 8)) throw new CryptographicException(SR.Format(SR.Cryptography_Padding_DecDataTooBig, Convert.ToString(KeySize / 8))); return _impl.Decrypt(rgb, fOAEP ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1); } public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); return padding == RSAEncryptionPadding.Pkcs1 ? Decrypt(data, fOAEP: false) : padding == RSAEncryptionPadding.OaepSHA1 ? Decrypt(data, fOAEP: true) : // For compat, this prevents OaepSHA2 options as fOAEP==true will cause Decrypt to use OaepSHA1 throw PaddingModeNotSupported(); } public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { if (padding == null) throw new ArgumentNullException(nameof(padding)); if (data.Length > (KeySize / 8)) throw new CryptographicException(SR.Format(SR.Cryptography_Padding_DecDataTooBig, Convert.ToString(KeySize / 8))); if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1) throw PaddingModeNotSupported(); return _impl.TryDecrypt(data, destination, padding, out bytesWritten); } protected override void Dispose(bool disposing) { if (disposing) { _impl.Dispose(); base.Dispose(disposing); } } public byte[] Encrypt(byte[] rgb, bool fOAEP) { if (rgb == null) throw new ArgumentNullException(nameof(rgb)); return _impl.Encrypt(rgb, fOAEP ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1); } public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); return padding == RSAEncryptionPadding.Pkcs1 ? Encrypt(data, fOAEP: false) : padding == RSAEncryptionPadding.OaepSHA1 ? Encrypt(data, fOAEP: true) : // For compat, this prevents OaepSHA2 options as fOAEP==true will cause Decrypt to use OaepSHA1 throw PaddingModeNotSupported(); } public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1) throw PaddingModeNotSupported(); return _impl.TryEncrypt(data, destination, padding, out bytesWritten); } public byte[] ExportCspBlob(bool includePrivateParameters) { RSAParameters parameters = ExportParameters(includePrivateParameters); return parameters.ToKeyBlob(); } public override RSAParameters ExportParameters(bool includePrivateParameters) => _impl.ExportParameters(includePrivateParameters); protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm); protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) => AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten); protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm); public override void FromXmlString(string xmlString) => _impl.FromXmlString(xmlString); public void ImportCspBlob(byte[] keyBlob) { RSAParameters parameters = CapiHelper.ToRSAParameters(keyBlob, !IsPublic(keyBlob)); ImportParameters(parameters); } public override void ImportParameters(RSAParameters parameters) { // Although _impl supports larger Exponent, limit here for compat. if (parameters.Exponent == null || parameters.Exponent.Length > 4) throw new CryptographicException(SR.Argument_InvalidValue); _impl.ImportParameters(parameters); // P was verified in ImportParameters _publicOnly = (parameters.P == null || parameters.P.Length == 0); } public override string KeyExchangeAlgorithm => _impl.KeyExchangeAlgorithm; public override int KeySize { get { return _impl.KeySize; } set { _impl.KeySize = value; } } public override KeySizes[] LegalKeySizes => _impl.LegalKeySizes; // Csp Windows and RSAOpenSsl are the same (384, 16384, 8) // PersistKeyInCsp has no effect in Unix public bool PersistKeyInCsp { get; set; } public bool PublicOnly => _publicOnly; public override string SignatureAlgorithm => "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignData(data, hashAlgorithm, padding); public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignData(data, offset, count, hashAlgorithm, padding); public override bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) => _impl.TrySignData(data, destination, hashAlgorithm, padding, out bytesWritten); public byte[] SignData(byte[] buffer, int offset, int count, object halg) => _impl.SignData(buffer, offset, count, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); public byte[] SignData(byte[] buffer, object halg) => _impl.SignData(buffer, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); public byte[] SignData(Stream inputStream, object halg) => _impl.SignData(inputStream, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignHash(hash, hashAlgorithm, padding); public override bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) => _impl.TrySignHash(hash, destination, hashAlgorithm, padding, out bytesWritten); public byte[] SignHash(byte[] rgbHash, string str) { if (rgbHash == null) throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); HashAlgorithmName algName = HashAlgorithmNames.NameOrOidToHashAlgorithmName(str); return _impl.SignHash(rgbHash, algName, RSASignaturePadding.Pkcs1); } public override string ToXmlString(bool includePrivateParameters) => _impl.ToXmlString(includePrivateParameters); public bool VerifyData(byte[] buffer, object halg, byte[] signature) => _impl.VerifyData(buffer, signature, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.VerifyData(data, offset, count, signature, hashAlgorithm, padding); public override bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.VerifyData(data, signature, hashAlgorithm, padding); public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) { throw new ArgumentNullException(nameof(hash)); } if (signature == null) { throw new ArgumentNullException(nameof(signature)); } return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature, hashAlgorithm, padding); } public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => padding == null ? throw new ArgumentNullException(nameof(padding)) : padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.VerifyHash(hash, signature, hashAlgorithm, padding); public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { if (rgbHash == null) { throw new ArgumentNullException(nameof(rgbHash)); } if (rgbSignature == null) { throw new ArgumentNullException(nameof(rgbSignature)); } return VerifyHash( (ReadOnlySpan<byte>)rgbHash, (ReadOnlySpan<byte>)rgbSignature, HashAlgorithmNames.NameOrOidToHashAlgorithmName(str), RSASignaturePadding.Pkcs1); } // UseMachineKeyStore has no effect in Unix public static bool UseMachineKeyStore { get; set; } private static Exception PaddingModeNotSupported() { return new CryptographicException(SR.Cryptography_InvalidPaddingMode); } /// <summary> /// find whether an RSA key blob is public. /// </summary> private static bool IsPublic(byte[] keyBlob) { if (keyBlob == null) throw new ArgumentNullException(nameof(keyBlob)); // The CAPI RSA public key representation consists of the following sequence: // - BLOBHEADER // - RSAPUBKEY // The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1" if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB) { return false; } if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52) { return false; } return true; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class NamedParameterCompletionProvider : AbstractCompletionProvider, IEqualityComparer<IParameterSymbol> { private const string ColonString = ":"; public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options) { return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); } protected override async Task<bool> IsExclusiveAsync(Document document, int caretPosition, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTree.FindTokenOnLeftOfPosition(caretPosition, cancellationToken) .GetPreviousTokenIfTouchingWord(caretPosition); return token.IsMandatoryNamedParameterPosition(); } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync( Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return null; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() != SyntaxKind.OpenParenToken && token.Kind() != SyntaxKind.OpenBracketToken && token.Kind() != SyntaxKind.CommaToken) { return null; } var argumentList = token.Parent as BaseArgumentListSyntax; if (argumentList == null) { return null; } var semanticModel = await document.GetSemanticModelForNodeAsync(argumentList, cancellationToken).ConfigureAwait(false); var parameterLists = GetParameterLists(semanticModel, position, argumentList.Parent, cancellationToken); if (parameterLists == null) { return null; } var existingNamedParameters = GetExistingNamedParameters(argumentList, position); parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters)); var unspecifiedParameters = parameterLists.SelectMany(pl => pl) .Where(p => !existingNamedParameters.Contains(p.Name)) .Distinct(this); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); return unspecifiedParameters.Select( p => { // Note: the filter text does not include the ':'. We want to ensure that if // the user types the name exactly (up to the colon) that it is selected as an // exact match. var workspace = document.Project.Solution.Workspace; var escaped = p.Name.ToIdentifierToken().ToString(); return new CompletionItem( this, escaped + ColonString, CompletionUtilities.GetTextChangeSpan(text, position), CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p), p.GetGlyph(), sortText: p.Name, filterText: escaped, rules: ItemRules.Instance); }); } private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters) { // A parameter list is valid if it has parameters that match in name all the existing // named parameters that have been provided. return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty(); } private ISet<string> GetExistingNamedParameters(BaseArgumentListSyntax argumentList, int position) { var existingArguments = argumentList.Arguments.Where(a => a.Span.End <= position && a.NameColon != null) .Select(a => a.NameColon.Name.Identifier.ValueText); return existingArguments.ToSet(); } private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists( SemanticModel semanticModel, int position, SyntaxNode invocableNode, CancellationToken cancellationToken) { return invocableNode.TypeSwitch( (InvocationExpressionSyntax invocationExpression) => GetInvocationExpressionParameterLists(semanticModel, position, invocationExpression, cancellationToken), (ConstructorInitializerSyntax constructorInitializer) => GetConstructorInitializerParameterLists(semanticModel, position, constructorInitializer, cancellationToken), (ElementAccessExpressionSyntax elementAccessExpression) => GetElementAccessExpressionParameterLists(semanticModel, position, elementAccessExpression, cancellationToken), (ObjectCreationExpressionSyntax objectCreationExpression) => GetObjectCreationExpressionParameterLists(semanticModel, position, objectCreationExpression, cancellationToken)); } private IEnumerable<ImmutableArray<IParameterSymbol>> GetObjectCreationExpressionParameterLists( SemanticModel semanticModel, int position, ObjectCreationExpressionSyntax objectCreationExpression, CancellationToken cancellationToken) { var type = semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type as INamedTypeSymbol; var within = semanticModel.GetEnclosingNamedType(position, cancellationToken); if (type != null && within != null && type.TypeKind != TypeKind.Delegate) { return type.InstanceConstructors.Where(c => c.IsAccessibleWithin(within)) .Select(c => c.Parameters); } return null; } private IEnumerable<ImmutableArray<IParameterSymbol>> GetElementAccessExpressionParameterLists( SemanticModel semanticModel, int position, ElementAccessExpressionSyntax elementAccessExpression, CancellationToken cancellationToken) { var expressionSymbol = semanticModel.GetSymbolInfo(elementAccessExpression.Expression, cancellationToken).GetAnySymbol(); var expressionType = semanticModel.GetTypeInfo(elementAccessExpression.Expression, cancellationToken).Type; if (expressionSymbol != null && expressionType != null) { var indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer).OfType<IPropertySymbol>(); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within != null) { return indexers.Where(i => i.IsAccessibleWithin(within, throughTypeOpt: expressionType)) .Select(i => i.Parameters); } } return null; } private IEnumerable<ImmutableArray<IParameterSymbol>> GetConstructorInitializerParameterLists( SemanticModel semanticModel, int position, ConstructorInitializerSyntax constructorInitializer, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedType(position, cancellationToken); if (within != null && (within.TypeKind == TypeKind.Struct || within.TypeKind == TypeKind.Class)) { var type = constructorInitializer.Kind() == SyntaxKind.BaseConstructorInitializer ? within.BaseType : within; if (type != null) { return type.InstanceConstructors.Where(c => c.IsAccessibleWithin(within)) .Select(c => c.Parameters); } } return null; } private IEnumerable<ImmutableArray<IParameterSymbol>> GetInvocationExpressionParameterLists( SemanticModel semanticModel, int position, InvocationExpressionSyntax invocationExpression, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within != null) { var methodGroup = semanticModel.GetMemberGroup(invocationExpression.Expression, cancellationToken).OfType<IMethodSymbol>(); var expressionType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type as INamedTypeSymbol; if (methodGroup.Any()) { return methodGroup.Where(m => m.IsAccessibleWithin(within)) .Select(m => m.Parameters); } else if (expressionType.IsDelegateType()) { var delegateType = (INamedTypeSymbol)expressionType; return SpecializedCollections.SingletonEnumerable(delegateType.DelegateInvokeMethod.Parameters); } } return null; } bool IEqualityComparer<IParameterSymbol>.Equals(IParameterSymbol x, IParameterSymbol y) { return x.Name.Equals(y.Name); } int IEqualityComparer<IParameterSymbol>.GetHashCode(IParameterSymbol obj) { return obj.Name.GetHashCode(); } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Calendar ///<para>SObject Name: CalendarView</para> ///<para>Custom Object: False</para> ///</summary> public class SfCalendarView : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "CalendarView"; } } ///<summary> /// Calendar ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Owner ID /// <para>Name: OwnerId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "ownerId")] public string OwnerId { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Calendar Name /// <para>Name: Name</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Is Displayed /// <para>Name: IsDisplayed</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDisplayed")] public bool? IsDisplayed { get; set; } ///<summary> /// Color /// <para>Name: Color</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "color")] public string Color { get; set; } ///<summary> /// Fill Pattern /// <para>Name: FillPattern</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "fillPattern")] public string FillPattern { get; set; } ///<summary> /// List View ID /// <para>Name: ListViewFilterId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "listViewFilterId")] public string ListViewFilterId { get; set; } ///<summary> /// ReferenceTo: ListView /// <para>RelationshipName: ListViewFilter</para> ///</summary> [JsonProperty(PropertyName = "listViewFilter")] [Updateable(false), Createable(false)] public SfListView ListViewFilter { get; set; } ///<summary> /// Date Handling Type /// <para>Name: DateHandlingType</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "dateHandlingType")] [Updateable(false), Createable(false)] public string DateHandlingType { get; set; } ///<summary> /// Start Field /// <para>Name: StartField</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "startField")] public string StartField { get; set; } ///<summary> /// End Field /// <para>Name: EndField</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "endField")] public string EndField { get; set; } ///<summary> /// Display Field /// <para>Name: DisplayField</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "displayField")] public string DisplayField { get; set; } ///<summary> /// sObject Type /// <para>Name: SobjectType</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "sobjectType")] [Updateable(false), Createable(true)] public string SobjectType { get; set; } } }
/* * 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.Runtime.Remoting.Lifetime; using System.Threading; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass : MarshalByRefObject { public IOSSL_Api m_OSSL_Functions; public void ApiTypeOSSL(IScriptApi api) { if (!(api is IOSSL_Api)) return; m_OSSL_Functions = (IOSSL_Api)api; Prim = new OSSLPrim(this); } public void osSetRegionWaterHeight(double height) { m_OSSL_Functions.osSetRegionWaterHeight(height); } public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour) { m_OSSL_Functions.osSetRegionSunSettings(useEstateSun, sunFixed, sunHour); } public void osSetEstateSunSettings(bool sunFixed, double sunHour) { m_OSSL_Functions.osSetEstateSunSettings(sunFixed, sunHour); } public double osGetCurrentSunHour() { return m_OSSL_Functions.osGetCurrentSunHour(); } public double osSunGetParam(string param) { return m_OSSL_Functions.osSunGetParam(param); } public void osSunSetParam(string param, double value) { m_OSSL_Functions.osSunSetParam(param, value); } public string osWindActiveModelPluginName() { return m_OSSL_Functions.osWindActiveModelPluginName(); } // Not yet plugged in as available OSSL functions, so commented out // void osWindParamSet(string plugin, string param, float value) // { // m_OSSL_Functions.osWindParamSet(plugin, param, value); // } // // float osWindParamGet(string plugin, string param) // { // return m_OSSL_Functions.osWindParamGet(plugin, param); // } public void osParcelJoin(vector pos1, vector pos2) { m_OSSL_Functions.osParcelJoin(pos1,pos2); } public void osParcelSubdivide(vector pos1, vector pos2) { m_OSSL_Functions.osParcelSubdivide(pos1, pos2); } public void osParcelSetDetails(vector pos, LSL_List rules) { m_OSSL_Functions.osParcelSetDetails(pos,rules); } public double osList2Double(LSL_Types.list src, int index) { return m_OSSL_Functions.osList2Double(src, index); } public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer) { return m_OSSL_Functions.osSetDynamicTextureURL(dynamicID, contentType, url, extraParams, timer); } public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer) { return m_OSSL_Functions.osSetDynamicTextureData(dynamicID, contentType, data, extraParams, timer); } public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams, int timer, int alpha) { return m_OSSL_Functions.osSetDynamicTextureURLBlend(dynamicID, contentType, url, extraParams, timer, alpha); } public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams, int timer, int alpha) { return m_OSSL_Functions.osSetDynamicTextureDataBlend(dynamicID, contentType, data, extraParams, timer, alpha); } public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams, bool blend, int disp, int timer, int alpha, int face) { return m_OSSL_Functions.osSetDynamicTextureURLBlendFace(dynamicID, contentType, url, extraParams, blend, disp, timer, alpha, face); } public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams, bool blend, int disp, int timer, int alpha, int face) { return m_OSSL_Functions.osSetDynamicTextureDataBlendFace(dynamicID, contentType, data, extraParams, blend, disp, timer, alpha, face); } public LSL_Float osTerrainGetHeight(int x, int y) { return m_OSSL_Functions.osTerrainGetHeight(x, y); } public LSL_Integer osTerrainSetHeight(int x, int y, double val) { return m_OSSL_Functions.osTerrainSetHeight(x, y, val); } public void osTerrainFlush() { m_OSSL_Functions.osTerrainFlush(); } public int osRegionRestart(double seconds) { return m_OSSL_Functions.osRegionRestart(seconds); } public void osRegionNotice(string msg) { m_OSSL_Functions.osRegionNotice(msg); } public bool osConsoleCommand(string Command) { return m_OSSL_Functions.osConsoleCommand(Command); } public void osSetParcelMediaURL(string url) { m_OSSL_Functions.osSetParcelMediaURL(url); } public void osSetParcelSIPAddress(string SIPAddress) { m_OSSL_Functions.osSetParcelSIPAddress(SIPAddress); } public void osSetPrimFloatOnWater(int floatYN) { m_OSSL_Functions.osSetPrimFloatOnWater(floatYN); } // Teleport Functions public void osTeleportAgent(string agent, string regionName, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, regionName, position, lookat); } public void osTeleportAgent(string agent, int regionX, int regionY, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, regionX, regionY, position, lookat); } public void osTeleportAgent(string agent, vector position, vector lookat) { m_OSSL_Functions.osTeleportAgent(agent, position, lookat); } // Avatar info functions public string osGetAgentIP(string agent) { return m_OSSL_Functions.osGetAgentIP(agent); } public LSL_List osGetAgents() { return m_OSSL_Functions.osGetAgents(); } // Animation Functions public void osAvatarPlayAnimation(string avatar, string animation) { m_OSSL_Functions.osAvatarPlayAnimation(avatar, animation); } public void osAvatarStopAnimation(string avatar, string animation) { m_OSSL_Functions.osAvatarStopAnimation(avatar, animation); } //Texture Draw functions public string osMovePen(string drawList, int x, int y) { return m_OSSL_Functions.osMovePen(drawList, x, y); } public string osDrawLine(string drawList, int startX, int startY, int endX, int endY) { return m_OSSL_Functions.osDrawLine(drawList, startX, startY, endX, endY); } public string osDrawLine(string drawList, int endX, int endY) { return m_OSSL_Functions.osDrawLine(drawList, endX, endY); } public string osDrawText(string drawList, string text) { return m_OSSL_Functions.osDrawText(drawList, text); } public string osDrawEllipse(string drawList, int width, int height) { return m_OSSL_Functions.osDrawEllipse(drawList, width, height); } public string osDrawRectangle(string drawList, int width, int height) { return m_OSSL_Functions.osDrawRectangle(drawList, width, height); } public string osDrawFilledRectangle(string drawList, int width, int height) { return m_OSSL_Functions.osDrawFilledRectangle(drawList, width, height); } public string osDrawPolygon(string drawList, LSL_List x, LSL_List y) { return m_OSSL_Functions.osDrawPolygon(drawList, x, y); } public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y) { return m_OSSL_Functions.osDrawFilledPolygon(drawList, x, y); } public string osSetFontSize(string drawList, int fontSize) { return m_OSSL_Functions.osSetFontSize(drawList, fontSize); } public string osSetFontName(string drawList, string fontName) { return m_OSSL_Functions.osSetFontName(drawList, fontName); } public string osSetPenSize(string drawList, int penSize) { return m_OSSL_Functions.osSetPenSize(drawList, penSize); } public string osSetPenCap(string drawList, string direction, string type) { return m_OSSL_Functions.osSetPenCap(drawList, direction, type); } public string osSetPenColour(string drawList, string colour) { return m_OSSL_Functions.osSetPenColour(drawList, colour); } public string osDrawImage(string drawList, int width, int height, string imageUrl) { return m_OSSL_Functions.osDrawImage(drawList, width, height, imageUrl); } public vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize) { return m_OSSL_Functions.osGetDrawStringSize(contentType, text, fontName, fontSize); } public void osSetStateEvents(int events) { m_OSSL_Functions.osSetStateEvents(events); } public string osGetScriptEngineName() { return m_OSSL_Functions.osGetScriptEngineName(); } public string osGetSimulatorVersion() { return m_OSSL_Functions.osGetSimulatorVersion(); } public Hashtable osParseJSON(string JSON) { return m_OSSL_Functions.osParseJSON(JSON); } public void osMessageObject(key objectUUID,string message) { m_OSSL_Functions.osMessageObject(objectUUID,message); } public void osMakeNotecard(string notecardName, LSL_Types.list contents) { m_OSSL_Functions.osMakeNotecard(notecardName, contents); } public string osGetNotecardLine(string name, int line) { return m_OSSL_Functions.osGetNotecardLine(name, line); } public string osGetNotecard(string name) { return m_OSSL_Functions.osGetNotecard(name); } public int osGetNumberOfNotecardLines(string name) { return m_OSSL_Functions.osGetNumberOfNotecardLines(name); } public string osAvatarName2Key(string firstname, string lastname) { return m_OSSL_Functions.osAvatarName2Key(firstname, lastname); } public string osKey2Name(string id) { return m_OSSL_Functions.osKey2Name(id); } public string osGetGridNick() { return m_OSSL_Functions.osGetGridNick(); } public string osGetGridName() { return m_OSSL_Functions.osGetGridName(); } public string osGetGridLoginURI() { return m_OSSL_Functions.osGetGridLoginURI(); } public LSL_String osFormatString(string str, LSL_List strings) { return m_OSSL_Functions.osFormatString(str, strings); } public LSL_List osMatchString(string src, string pattern, int start) { return m_OSSL_Functions.osMatchString(src, pattern, start); } // Information about data loaded into the region public string osLoadedCreationDate() { return m_OSSL_Functions.osLoadedCreationDate(); } public string osLoadedCreationTime() { return m_OSSL_Functions.osLoadedCreationTime(); } public string osLoadedCreationID() { return m_OSSL_Functions.osLoadedCreationID(); } public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules) { return m_OSSL_Functions.osGetLinkPrimitiveParams(linknumber, rules); } public key osNpcCreate(string user, string name, vector position, key cloneFrom) { return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom); } public void osNpcMoveTo(key npc, vector position) { m_OSSL_Functions.osNpcMoveTo(npc, position); } public void osNpcSay(key npc, string message) { m_OSSL_Functions.osNpcSay(npc, message); } public void osNpcRemove(key npc) { m_OSSL_Functions.osNpcRemove(npc); } public OSSLPrim Prim; [Serializable] public class OSSLPrim { internal ScriptBaseClass OSSL; public OSSLPrim(ScriptBaseClass bc) { OSSL = bc; Position = new OSSLPrim_Position(this); Rotation = new OSSLPrim_Rotation(this); } public OSSLPrim_Position Position; public OSSLPrim_Rotation Rotation; private TextStruct _text; public TextStruct Text { get { return _text; } set { _text = value; OSSL.llSetText(_text.Text, _text.color, _text.alpha); } } [Serializable] public struct TextStruct { public string Text; public LSL_Types.Vector3 color; public double alpha; } } [Serializable] public class OSSLPrim_Position { private OSSLPrim prim; private LSL_Types.Vector3 Position; public OSSLPrim_Position(OSSLPrim _prim) { prim = _prim; } private void Load() { Position = prim.OSSL.llGetPos(); } private void Save() { if (Position.x > ((int)Constants.RegionSize - 1)) Position.x = ((int)Constants.RegionSize - 1); if (Position.x < 0) Position.x = 0; if (Position.y > ((int)Constants.RegionSize - 1)) Position.y = ((int)Constants.RegionSize - 1); if (Position.y < 0) Position.y = 0; if (Position.z > 768) Position.z = 768; if (Position.z < 0) Position.z = 0; prim.OSSL.llSetPos(Position); } public double x { get { Load(); return Position.x; } set { Load(); Position.x = value; Save(); } } public double y { get { Load(); return Position.y; } set { Load(); Position.y = value; Save(); } } public double z { get { Load(); return Position.z; } set { Load(); Position.z = value; Save(); } } } [Serializable] public class OSSLPrim_Rotation { private OSSLPrim prim; private LSL_Types.Quaternion Rotation; public OSSLPrim_Rotation(OSSLPrim _prim) { prim = _prim; } private void Load() { Rotation = prim.OSSL.llGetRot(); } private void Save() { prim.OSSL.llSetRot(Rotation); } public double x { get { Load(); return Rotation.x; } set { Load(); Rotation.x = value; Save(); } } public double y { get { Load(); return Rotation.y; } set { Load(); Rotation.y = value; Save(); } } public double z { get { Load(); return Rotation.z; } set { Load(); Rotation.z = value; Save(); } } public double s { get { Load(); return Rotation.s; } set { Load(); Rotation.s = value; Save(); } } } public key osGetMapTexture() { return m_OSSL_Functions.osGetMapTexture(); } public key osGetRegionMapTexture(string regionName) { return m_OSSL_Functions.osGetRegionMapTexture(regionName); } public LSL_List osGetRegionStats() { return m_OSSL_Functions.osGetRegionStats(); } /// <summary> /// Returns the amount of memory in use by the Simulator Daemon. /// Amount in bytes - if >= 4GB, returns 4GB. (LSL is not 64-bit aware) /// </summary> /// <returns></returns> public LSL_Integer osGetSimulatorMemory() { return m_OSSL_Functions.osGetSimulatorMemory(); } public void osKickAvatar(string FirstName,string SurName,string alert) { m_OSSL_Functions.osKickAvatar(FirstName, SurName, alert); } public void osSetSpeed(string UUID, float SpeedModifier) { m_OSSL_Functions.osSetSpeed(UUID, SpeedModifier); } public void osCauseDamage(string avatar, double damage) { m_OSSL_Functions.osCauseDamage(avatar, damage); } public void osCauseHealing(string avatar, double healing) { m_OSSL_Functions.osCauseHealing(avatar, healing); } public LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules) { return m_OSSL_Functions.osGetPrimitiveParams(prim, rules); } public void osSetPrimitiveParams(LSL_Key prim, LSL_List rules) { m_OSSL_Functions.osSetPrimitiveParams(prim, rules); } public void osSetProjectionParams(bool projection, LSL_Key texture, double fov, double focus, double amb) { m_OSSL_Functions.osSetProjectionParams(projection, texture, fov, focus, amb); } public void osSetProjectionParams(LSL_Key prim, bool projection, LSL_Key texture, double fov, double focus, double amb) { m_OSSL_Functions.osSetProjectionParams(prim, projection, texture, fov, focus, amb); } public LSL_List osGetAvatarList() { return m_OSSL_Functions.osGetAvatarList(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Domain.Repositories; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.IdentityFramework; using Abp.Localization; using Abp.MultiTenancy; using Abp.Organizations; using Abp.Runtime.Caching; using Abp.Runtime.Security; using Abp.Runtime.Session; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNet.Identity; namespace Abp.Authorization.Users { /// <summary> /// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework. /// </summary> public abstract class AbpUserManager<TRole, TUser> : UserManager<TUser, long>, IDomainService where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { protected IUserPermissionStore<TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TUser>; } } public ILocalizationManager LocalizationManager { get; } public IAbpSession AbpSession { get; set; } public FeatureDependencyContext FeatureDependencyContext { get; set; } protected AbpRoleManager<TRole, TUser> RoleManager { get; } public AbpUserStore<TRole, TUser> AbpStore { get; } public IMultiTenancyConfig MultiTenancy { get; set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ICacheManager _cacheManager; private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository; private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository; private readonly IOrganizationUnitSettings _organizationUnitSettings; private readonly ISettingManager _settingManager; protected AbpUserManager( AbpUserStore<TRole, TUser> userStore, AbpRoleManager<TRole, TUser> roleManager, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ILocalizationManager localizationManager, IdentityEmailMessageService emailService, ISettingManager settingManager, IUserTokenProviderAccessor userTokenProviderAccessor) : base(userStore) { AbpStore = userStore; RoleManager = roleManager; LocalizationManager = localizationManager; _settingManager = settingManager; _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _cacheManager = cacheManager; _organizationUnitRepository = organizationUnitRepository; _userOrganizationUnitRepository = userOrganizationUnitRepository; _organizationUnitSettings = organizationUnitSettings; AbpSession = NullAbpSession.Instance; UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; EmailService = emailService; UserTokenProvider = userTokenProviderAccessor.GetUserTokenProviderOrNull<TUser>(); } public override async Task<IdentityResult> CreateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var tenantId = GetCurrentTenantId(); if (tenantId.HasValue && !user.TenantId.HasValue) { user.TenantId = tenantId.Value; } var isLockoutEnabled = user.IsLockoutEnabled; var identityResult = await base.CreateAsync(user); if (identityResult.Succeeded) { await _unitOfWorkManager.Current.SaveChangesAsync(); await SetLockoutEnabledAsync(user.Id, isLockoutEnabled); } return identityResult; } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission) { return IsGrantedAsync(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = await GetUserPermissionCacheItemAsync(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (await RoleManager.IsGrantedAsync(roleId, permission)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpStore.FindAllAsync(login); } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType) { var identity = await base.CreateIdentityAsync(user, authenticationType); if (user.TenantId.HasValue) { identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture))); } return identity; } public async override Task<IdentityResult> UpdateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } //Admin user's username can not be changed! if (user.UserName != AbpUser<TUser>.AdminUserName) { if ((await GetOldUserNameAsync(user.Id)) == AbpUser<TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TUser>.AdminUserName)); } } return await base.UpdateAsync(user); } public async override Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUser<TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TUser>.AdminUserName)); } return await base.DeleteAsync(user); } public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var result = await PasswordValidator.ValidateAsync(newPassword); if (!result.Succeeded) { return result; } await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword)); return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateUserName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames) { //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId); if (roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user.Id, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user.Id, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId) { return await IsInOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou) { return await _userOrganizationUnitRepository.CountAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; } public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId) { await AddToOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou) { var currentOus = await GetOrganizationUnitsAsync(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1); await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); } public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId) { await RemoveFromOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou) { await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id); } public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds) { await SetOrganizationUnitsAsync( await GetUserByIdAsync(userId), organizationUnitIds ); } private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount) { var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId); if (requestedCount > maxCount) { throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount)); } } public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds) { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length); var currentOus = await GetOrganizationUnitsAsync(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { await RemoveFromOrganizationUnitAsync(user, currentOu); } } //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { await AddToOrganizationUnitAsync( user, await _organizationUnitRepository.GetAsync(organizationUnitId) ); } } } [UnitOfWork] public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user) { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return Task.FromResult(query.ToList()); } [UnitOfWork] public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false) { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in AbpStore.Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return Task.FromResult(query.ToList()); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in AbpStore.Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return Task.FromResult(query.ToList()); } } public virtual void RegisterTwoFactorProviders(int? tenantId) { TwoFactorProviders.Clear(); if (!IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, tenantId)) { return; } if (EmailService != null && IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, tenantId)) { RegisterTwoFactorProvider( L("Email"), new EmailTokenProvider<TUser, long> { Subject = L("EmailSecurityCodeSubject"), BodyFormat = L("EmailSecurityCodeBody") } ); } if (SmsService != null && IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, tenantId)) { RegisterTwoFactorProvider( L("Sms"), new PhoneNumberTokenProvider<TUser, long> { MessageFormat = L("SmsSecurityCodeMessage") } ); } } public virtual void InitializeLockoutSettings(int? tenantId) { UserLockoutEnabledByDefault = IsTrue(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId); DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId)); MaxFailedAccessAttemptsBeforeLockout = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId); } public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(long userId) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.GetValidTwoFactorProvidersAsync(userId); } public override async Task<IdentityResult> NotifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.NotifyTwoFactorTokenAsync(userId, twoFactorProvider, token); } public override async Task<string> GenerateTwoFactorTokenAsync(long userId, string twoFactorProvider) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.GenerateTwoFactorTokenAsync(userId, twoFactorProvider); } public override async Task<bool> VerifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.VerifyTwoFactorTokenAsync(userId, twoFactorProvider, token); } protected virtual Task<string> GetOldUserNameAsync(long userId) { return AbpStore.GetUserNameFromDatabaseAsync(userId); } private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () => { var user = await FindByIdAsync(userId); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in await GetRolesAsync(userId)) { newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id); } foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } private bool IsTrue(string settingName, int? tenantId) { return GetSettingValue<bool>(settingName, tenantId); } private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplication<T>(settingName) : _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value); } private string L(string name) { return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name); } private int? GetCurrentTenantId() { if (_unitOfWorkManager.Current != null) { return _unitOfWorkManager.Current.GetTenantId(); } return AbpSession.TenantId; } private MultiTenancySides GetCurrentMultiTenancySide() { if (_unitOfWorkManager.Current != null) { return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue ? MultiTenancySides.Host : MultiTenancySides.Tenant; } return AbpSession.MultiTenancySide; } } }
using System; using System.Text; namespace uPLibrary.Networking.Http { /// <summary> /// Parser for HTTP response /// </summary> internal class HttpResponseParser { // parser state and line extract state private HttpResponseParserState state; private HttpResponseLineState lineState; #if !MF_FRAMEWORK_VERSION_V4_1 // HTTP line extracted private StringBuilder lineBuilder; #else // .NET MF doesn't support StringBuilder private string lineBuilder; #endif // HTTP response parsed private HttpResponse response; // callback to allow client to read body response // buffer to parse and relative size private byte[] buffer; private int size; // remaining bytes for response body (entire or chunk) private int bodyRemaining; // transfer encoding chunked private bool isChunked; // parsed and remaining bytes into the buffer private int parsed; private int remaining; // parser result HttpResponseParserResult result; internal event RecvBodyEventHandler ReceivingBody; /// <summary> /// HTTP response /// </summary> public HttpResponse Response { get { return this.response; } } /// <summary> /// Constructor /// </summary> internal HttpResponseParser() { // initialize parser state this.state = HttpResponseParserState.ResponseLine; this.lineState = HttpResponseLineState.Idle; #if !MF_FRAMEWORK_VERSION_V4_1 this.lineBuilder = new StringBuilder(); #else this.lineBuilder = String.Empty; #endif // create HTTP response object and assign read method for body response this.response = new HttpResponse(); this.response.Body.Read = this.ReadBody; } /// <summary> /// Extract a line (CRLF terminated) from HTTP response /// </summary> /// <param name="buffer">Buffer with HTTP response bytes</param> /// <param name="offset">Offset from extract</param> /// <param name="size">Number of bytes</param> /// <returns>Number of parsed bytes (it can be less then size if a line is recognized inside buffer</returns> private int ExtractLine(byte[] buffer, int offset, int size) { int i = offset; while ((i < size) && (this.lineState != HttpResponseLineState.End)) { switch (this.lineState) { case HttpResponseLineState.Idle: // CR recognized if (buffer[i] == HttpBase.CR) this.lineState = HttpResponseLineState.CarriageReturn; // some server don't respond with CRLF but only with LF else if (buffer[i] == HttpBase.LF) this.lineState = this.lineState = HttpResponseLineState.End; else #if !MF_FRAMEWORK_VERSION_V4_1 this.lineBuilder.Append((char)buffer[i]); #else this.lineBuilder += (char)buffer[i]; #endif break; case HttpResponseLineState.CarriageReturn: // LF recognized if (buffer[i] == HttpBase.LF) this.lineState = HttpResponseLineState.End; break; case HttpResponseLineState.End: break; default: break; } i++; } // return number of parsed bytes. it can be less then size if // a line is recognized inside buffer return (i - offset); } /// <summary> /// Execute HTTP response parsing /// </summary> /// <param name="buffer">Buffer with HTTP response bytes</param> /// <param name="size">Number of bytes</param> /// <returns>Parsing result</returns> internal HttpResponseParserResult Parse(byte[] buffer, int size) { this.result = HttpResponseParserResult.NotCompleted; this.parsed = 0; this.remaining = 0; this.buffer = buffer; this.size = size; // entire size is remaining bytes to parser this.remaining = this.size; while (this.remaining > 0) { switch (this.state) { // waiting for response line, start of HTTP response case HttpResponseParserState.ResponseLine: this.parsed += this.ExtractLine(this.buffer, this.parsed, this.size); // response line extracted if (this.lineState == HttpResponseLineState.End) { try { string[] token = this.lineBuilder.ToString().Split(HttpBase.RESPONSE_LINE_SEPARATOR); // set HTTP protocol, status code and reason phrase this.response.HttpProtocol = token[0]; this.response.StatusCode = (HttpStatusCode)Convert.ToInt32(token[1]); if (token.Length == 3) this.response.ReasonPhrase = token[2]; else { this.response.ReasonPhrase = string.Empty; for (int i = 2; i < token.Length; i++) this.response.ReasonPhrase += token[i]; } // change parser state for waiting headers this.state = HttpResponseParserState.Headers; // reset extract line parser state this.lineState = HttpResponseLineState.Idle; #if !MF_FRAMEWORK_VERSION_V4_1 this.lineBuilder.Clear(); #else this.lineBuilder = String.Empty; #endif } catch { this.result = HttpResponseParserResult.Malformed; } } this.remaining = (this.size - this.parsed); break; // receiving HTTP headers case HttpResponseParserState.Headers: this.parsed += this.ExtractLine(this.buffer, this.parsed, this.size); // line extracted if (this.lineState == HttpResponseLineState.End) { // header line if (this.lineBuilder.Length > 0) { string headerLine = this.lineBuilder.ToString(); // add header to response (key and value) this.response.Headers.Add( headerLine.Substring(0, headerLine.IndexOf(HttpBase.HEADER_VALUE_SEPARATOR)).Trim(), headerLine.Substring(headerLine.IndexOf(HttpBase.HEADER_VALUE_SEPARATOR) + 1).Trim() ); } // empty line, headers end else { // body chunked or not if ((this.response.ContentLength > 0) || (this.response.TransferEncoding != null)) { this.bodyRemaining = (this.response.ContentLength > 0) ? this.response.ContentLength : 0; if (this.response.TransferEncoding != null) this.isChunked = (this.response.TransferEncoding.Equals(HttpBase.TRANSFER_ENCODING_CHUNKED)); this.state = HttpResponseParserState.Body; } // no body, HTTP response end else { this.result = HttpResponseParserResult.Completed; this.state = HttpResponseParserState.ResponseLine; } } // reset extract line parser state this.lineState = HttpResponseLineState.Idle; #if !MF_FRAMEWORK_VERSION_V4_1 this.lineBuilder.Clear(); #else this.lineBuilder = String.Empty; #endif } this.remaining = (this.size - this.parsed); break; // receiving body case HttpResponseParserState.Body: // body chunked and no chunk size already found if ((this.isChunked) && (this.bodyRemaining == 0)) { this.parsed += this.ExtractLine(this.buffer, this.parsed, this.size); // line extracted if (this.lineState == HttpResponseLineState.End) { // line contains chunk size if (this.lineBuilder.Length > 0) { this.bodyRemaining = Convert.ToInt32(this.lineBuilder.ToString(), 16); } // empty line, body chunked end else { this.result = HttpResponseParserResult.Completed; this.state = HttpResponseParserState.ResponseLine; } // reset extract line parser state this.lineState = HttpResponseLineState.Idle; #if !MF_FRAMEWORK_VERSION_V4_1 this.lineBuilder.Clear(); #else this.lineBuilder = String.Empty; #endif } this.remaining = (this.size - this.parsed); } // read body or chunk else { // raise event for allow client to read body response this.OnReceivingBody(this.response); this.remaining = (this.size - this.parsed); } break; default: break; } // HTTP response malfomerd, break if (this.result == HttpResponseParserResult.Malformed) { this.response = null; break; } } return this.result; } /// <summary> /// Called for reading response body by client /// </summary> /// <param name="buffer">Destination client buffer</param> /// <param name="offset">Offset to start reading</param> /// <param name="count">Number of bytes to read</param> /// <returns>Number of bytes read</returns> private int ReadBody(byte[] buffer, int offset, int count) { int readBytes = 0; // we can read at most bytes inside buffer (remaining) readBytes = (this.bodyRemaining <= this.remaining) ? this.bodyRemaining : this.remaining; // if client want to read less then remaining bytes if (count < readBytes) readBytes = count; // copy bytes to client buffer Array.Copy(this.buffer, this.parsed, buffer, offset, readBytes); this.parsed += readBytes; // body chunked if (this.isChunked) { // if read all chunk, consider CR LF ending chunk if (readBytes == this.bodyRemaining) { this.parsed += HttpBase.CRLF.Length; // waiting for another chunk this.bodyRemaining = 0; } // not read entire current chunk else { this.bodyRemaining -= readBytes; } } else { this.bodyRemaining -= readBytes; // body and parsing end if (this.bodyRemaining == 0) { this.result = HttpResponseParserResult.Completed; this.state = HttpResponseParserState.ResponseLine; } } return readBytes; } /// <summary> /// Raise receving body event /// </summary> /// <param name="httpResp">HTTP response for reading body</param> private void OnReceivingBody(HttpResponse httpResp) { if (this.ReceivingBody != null) this.ReceivingBody(httpResp); } } /// <summary> /// HTTP response parser states /// </summary> internal enum HttpResponseParserState { /// <summary> /// Receiving response line /// </summary> ResponseLine, /// <summary> /// Receiving headers /// </summary> Headers, /// <summary> /// Receiving body /// </summary> Body } /// <summary> /// HTTP line states /// </summary> internal enum HttpResponseLineState { /// <summary> /// Idle /// </summary> Idle, /// <summary> /// Waiting for CR /// </summary> CarriageReturn, /// <summary> /// End line (LF recognized) /// </summary> End } /// <summary> /// HTTP response parser result /// </summary> internal enum HttpResponseParserResult { /// <summary> /// Completed response /// </summary> Completed, /// <summary> /// Not completed response /// </summary> NotCompleted, /// <summary> /// Malformed response /// </summary> Malformed } }
// /* // * Copyright (c) 2016, Alachisoft. 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. // */ #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Alachisoft.NosDB.Common.Protobuf { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class WriteQueryResponse { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_WriteQueryResponse__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse, global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_WriteQueryResponse__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static WriteQueryResponse() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChhXcml0ZVF1ZXJ5UmVzcG9uc2UucHJvdG8SIEFsYWNoaXNvZnQuTm9zREIu", "Q29tbW9uLlByb3RvYnVmIi8KEldyaXRlUXVlcnlSZXNwb25zZRIZChFhZmZl", "Y3RlZERvY3VtZW50cxgBIAEoA0JCCiRjb20uYWxhY2hpc29mdC5ub3NkYi5j", "b21tb24ucHJvdG9idWZCGldyaXRlUXVlcnlSZXNwb25zZVByb3RvY29s")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NosDB_Common_Protobuf_WriteQueryResponse__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NosDB_Common_Protobuf_WriteQueryResponse__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse, global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_WriteQueryResponse__Descriptor, new string[] { "AffectedDocuments", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class WriteQueryResponse : pb::GeneratedMessage<WriteQueryResponse, WriteQueryResponse.Builder> { private WriteQueryResponse() { } private static readonly WriteQueryResponse defaultInstance = new WriteQueryResponse().MakeReadOnly(); private static readonly string[] _writeQueryResponseFieldNames = new string[] { "affectedDocuments" }; private static readonly uint[] _writeQueryResponseFieldTags = new uint[] { 8 }; public static WriteQueryResponse DefaultInstance { get { return defaultInstance; } } public override WriteQueryResponse DefaultInstanceForType { get { return DefaultInstance; } } protected override WriteQueryResponse ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.WriteQueryResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_WriteQueryResponse__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<WriteQueryResponse, WriteQueryResponse.Builder> InternalFieldAccessors { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.WriteQueryResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_WriteQueryResponse__FieldAccessorTable; } } public const int AffectedDocumentsFieldNumber = 1; private bool hasAffectedDocuments; private long affectedDocuments_; public bool HasAffectedDocuments { get { return hasAffectedDocuments; } } public long AffectedDocuments { get { return affectedDocuments_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _writeQueryResponseFieldNames; if (hasAffectedDocuments) { output.WriteInt64(1, field_names[0], AffectedDocuments); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasAffectedDocuments) { size += pb::CodedOutputStream.ComputeInt64Size(1, AffectedDocuments); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static WriteQueryResponse ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static WriteQueryResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static WriteQueryResponse ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static WriteQueryResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static WriteQueryResponse ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static WriteQueryResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static WriteQueryResponse ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static WriteQueryResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static WriteQueryResponse ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static WriteQueryResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private WriteQueryResponse MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(WriteQueryResponse prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<WriteQueryResponse, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(WriteQueryResponse cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private WriteQueryResponse result; private WriteQueryResponse PrepareBuilder() { if (resultIsReadOnly) { WriteQueryResponse original = result; result = new WriteQueryResponse(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override WriteQueryResponse MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.Descriptor; } } public override WriteQueryResponse DefaultInstanceForType { get { return global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.DefaultInstance; } } public override WriteQueryResponse BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is WriteQueryResponse) { return MergeFrom((WriteQueryResponse) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(WriteQueryResponse other) { if (other == global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.DefaultInstance) return this; PrepareBuilder(); if (other.HasAffectedDocuments) { AffectedDocuments = other.AffectedDocuments; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_writeQueryResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _writeQueryResponseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 8: { result.hasAffectedDocuments = input.ReadInt64(ref result.affectedDocuments_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasAffectedDocuments { get { return result.hasAffectedDocuments; } } public long AffectedDocuments { get { return result.AffectedDocuments; } set { SetAffectedDocuments(value); } } public Builder SetAffectedDocuments(long value) { PrepareBuilder(); result.hasAffectedDocuments = true; result.affectedDocuments_ = value; return this; } public Builder ClearAffectedDocuments() { PrepareBuilder(); result.hasAffectedDocuments = false; result.affectedDocuments_ = 0L; return this; } } static WriteQueryResponse() { object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.WriteQueryResponse.Descriptor, null); } } #endregion } #endregion Designer generated code
// 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: Unsafe code that uses pointers should use ** SafePointer to fix subtle lifetime problems with the ** underlying resource. ** ===========================================================*/ // Design points: // *) Avoid handle-recycling problems (including ones triggered via // resurrection attacks) for all accesses via pointers. This requires tying // together the lifetime of the unmanaged resource with the code that reads // from that resource, in a package that uses synchronization to enforce // the correct semantics during finalization. We're using SafeHandle's // ref count as a gate on whether the pointer can be dereferenced because that // controls the lifetime of the resource. // // *) Keep the penalties for using this class small, both in terms of space // and time. Having multiple threads reading from a memory mapped file // will already require 2 additional interlocked operations. If we add in // a "current position" concept, that requires additional space in memory and // synchronization. Since the position in memory is often (but not always) // something that can be stored on the stack, we can save some memory by // excluding it from this object. However, avoiding the need for // synchronization is a more significant win. This design allows multiple // threads to read and write memory simultaneously without locks (as long as // you don't write to a region of memory that overlaps with what another // thread is accessing). // // *) Space-wise, we use the following memory, including SafeHandle's fields: // Object Header MT* handle int bool bool <2 pad bytes> length // On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes. // (We can safe 4 bytes on x86 only by shrinking SafeHandle) // // *) Wrapping a SafeHandle would have been a nice solution, but without an // ordering between critical finalizable objects, it would have required // changes to each SafeHandle subclass to opt in to being usable from a // SafeBuffer (or some clever exposure of SafeHandle's state fields and a // way of forcing ReleaseHandle to run even after the SafeHandle has been // finalized with a ref count > 1). We can use less memory and create fewer // objects by simply inserting a SafeBuffer into the class hierarchy. // // *) In an ideal world, we could get marshaling support for SafeBuffer that // would allow us to annotate a P/Invoke declaration, saying this parameter // specifies the length of the buffer, and the units of that length are X. // P/Invoke would then pass that size parameter to SafeBuffer. // [DllImport(...)] // static extern SafeMemoryHandle AllocCharBuffer(int numChars); // If we could put an attribute on the SafeMemoryHandle saying numChars is // the element length, and it must be multiplied by 2 to get to the byte // length, we can simplify the usage model for SafeBuffer. // // *) This class could benefit from a constraint saying T is a value type // containing no GC references. // Implementation notes: // *) The Initialize method must be called before you use any instance of // a SafeBuffer. To avoid race conditions when storing SafeBuffers in statics, // you either need to take a lock when publishing the SafeBuffer, or you // need to create a local, initialize the SafeBuffer, then assign to the // static variable (perhaps using Interlocked.CompareExchange). Of course, // assignments in a static class constructor are under a lock implicitly. namespace System.Runtime.InteropServices { using System; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; using System.Diagnostics.Contracts; [System.Security.SecurityCritical] public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid { // Steal UIntPtr.MaxValue as our uninitialized value. private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ? ((UIntPtr) UInt32.MaxValue) : ((UIntPtr) UInt64.MaxValue); private UIntPtr _numBytes; protected SafeBuffer(bool ownsHandle) : base(ownsHandle) { _numBytes = Uninitialized; } /// <summary> /// Specifies the size of the region of memory, in bytes. Must be /// called before using the SafeBuffer. /// </summary> /// <param name="numBytes">Number of valid bytes in memory.</param> [CLSCompliant(false)] public void Initialize(ulong numBytes) { if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); Contract.EndContractBlock(); if (numBytes >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); _numBytes = (UIntPtr) numBytes; } /// <summary> /// Specifies the the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { if (numElements < 0) throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (sizeOfEachElement < 0) throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); Contract.EndContractBlock(); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); _numBytes = checked((UIntPtr) (numElements * sizeOfEachElement)); } /// <summary> /// Specifies the the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize<T>(uint numElements) where T : struct { Initialize(numElements, Marshal.AlignedSizeOf<T>()); } // Callers should ensure that they check whether the pointer ref param // is null when AcquirePointer returns. If it is not null, they must // call ReleasePointer in a CER. This method calls DangerousAddRef // & exposes the pointer. Unlike Read, it does not alter the "current // position" of the pointer. Here's how to use it: // // byte* pointer = null; // RuntimeHelpers.PrepareConstrainedRegions(); // try { // safeBuffer.AcquirePointer(ref pointer); // // Use pointer here, with your own bounds checking // } // finally { // if (pointer != null) // safeBuffer.ReleasePointer(); // } // // Note: If you cast this byte* to a T*, you have to worry about // whether your pointer is aligned. Additionally, you must take // responsibility for all bounds checking with this pointer. /// <summary> /// Obtain the pointer from a SafeBuffer for a block of code, /// with the express responsibility for bounds checking and calling /// ReleasePointer later within a CER to ensure the pointer can be /// freed later. This method either completes successfully or /// throws an exception and returns with pointer set to null. /// </summary> /// <param name="pointer">A byte*, passed by reference, to receive /// the pointer from within the SafeBuffer. You must set /// pointer to null before calling this method.</param> [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void AcquirePointer(ref byte* pointer) { if (_numBytes == Uninitialized) throw NotInitialized(); pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { bool junk = false; DangerousAddRef(ref junk); pointer = (byte*)handle; } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public void ReleasePointer() { if (_numBytes == Uninitialized) throw NotInitialized(); DangerousRelease(); } /// <summary> /// Read a value type from memory at the given offset. This is /// equivalent to: return *(T*)(bytePtr + byteOffset); /// </summary> /// <typeparam name="T">The value type to read</typeparam> /// <param name="byteOffset">Where to start reading from memory. You /// may have to consider alignment.</param> /// <returns>An instance of T read from memory.</returns> [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public T Read<T>(ulong byteOffset) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = Marshal.SizeOfType(typeof(T)); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // return *(T*) (_ptr + byteOffset); T value; bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustCallRelease); GenericPtrToStructure<T>(ptr, out value, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } return value; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = Marshal.SizeOfType(typeof(T)); uint alignedSizeofT = Marshal.AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustCallRelease); for (int i = 0; i < count; i++) unsafe { GenericPtrToStructure<T>(ptr + alignedSizeofT * i, out array[i + index], sizeofT); } } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Write a value type to memory at the given offset. This is /// equivalent to: *(T*)(bytePtr + byteOffset) = value; /// </summary> /// <typeparam name="T">The type of the value type to write to memory.</typeparam> /// <param name="byteOffset">The location in memory to write to. You /// may have to consider alignment.</param> /// <param name="value">The value type to write to memory.</param> [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void Write<T>(ulong byteOffset, T value) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = Marshal.SizeOfType(typeof(T)); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // *((T*) (_ptr + byteOffset)) = value; bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustCallRelease); GenericStructureToPtr(ref value, ptr, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = Marshal.SizeOfType(typeof(T)); uint alignedSizeofT = Marshal.AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustCallRelease); for (int i = 0; i < count; i++) unsafe { GenericStructureToPtr(ref array[i + index], ptr + alignedSizeofT * i, sizeofT); } } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Returns the number of bytes in the memory region. /// </summary> [CLSCompliant(false)] public ulong ByteLength { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { if (_numBytes == Uninitialized) throw NotInitialized(); return (ulong) _numBytes; } } /* No indexer. The perf would be misleadingly bad. People should use * AcquirePointer and ReleasePointer instead. */ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private void SpaceCheck(byte* ptr, ulong sizeInBytes) { if ((ulong)_numBytes < sizeInBytes) NotEnoughRoom(); if ((ulong)(ptr - (byte*) handle) > ((ulong)_numBytes) - sizeInBytes) NotEnoughRoom(); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static void NotEnoughRoom() { throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall")); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static InvalidOperationException NotInitialized() { Contract.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize")); } // FCALL limitations mean we can't have generic FCALL methods. However, we can pass // TypedReferences to FCALL methods. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static void GenericPtrToStructure<T>(byte* ptr, out T structure, uint sizeofT) where T : struct { structure = default(T); // Dummy assignment to silence the compiler PtrToStructureNative(ptr, __makeref(structure), sizeofT); } [MethodImpl(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern void PtrToStructureNative(byte* ptr, /*out T*/ TypedReference structure, uint sizeofT); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static void GenericStructureToPtr<T>(ref T structure, byte* ptr, uint sizeofT) where T : struct { StructureToPtrNative(__makeref(structure), ptr, sizeofT); } [MethodImpl(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern void StructureToPtrNative(/*ref T*/ TypedReference structure, byte* ptr, uint sizeofT); } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // GroupByQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using IEnumerator = System.Collections.IEnumerator; namespace System.Linq.Parallel { /// <summary> /// The operator type for GroupBy statements. This operator groups the input based on /// a key-selection routine, yielding one-to-many values of key-to-elements. The /// implementation is very much like the hash join operator, in which we first build /// a big hashtable of the input; then we just iterate over each unique key in the /// hashtable, yielding it plus all of the elements with the same key. /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TGroupKey"></typeparam> /// <typeparam name="TElement"></typeparam> internal sealed class GroupByQueryOperator<TSource, TGroupKey, TElement> : UnaryQueryOperator<TSource, IGrouping<TGroupKey, TElement>> { private readonly Func<TSource, TGroupKey> _keySelector; // Key selection function. private readonly Func<TSource, TElement> _elementSelector; // Optional element selection function. private readonly IEqualityComparer<TGroupKey> _keyComparer; // An optional key comparison object. //--------------------------------------------------------------------------------------- // Initializes a new group by operator. // // Arguments: // child - the child operator or data source from which to pull data // keySelector - a delegate representing the key selector function // elementSelector - a delegate representing the element selector function // keyComparer - an optional key comparison routine // // Assumptions: // keySelector must be non null. // elementSelector must be non null. // internal GroupByQueryOperator(IEnumerable<TSource> child, Func<TSource, TGroupKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TGroupKey> keyComparer) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); Debug.Assert(keySelector != null, "need a selector function"); Debug.Assert(elementSelector != null || typeof(TSource) == typeof(TElement), "need an element function if TSource!=TElement"); _keySelector = keySelector; _elementSelector = elementSelector; _keyComparer = keyComparer; SetOrdinalIndexState(OrdinalIndexState.Shuffled); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient, bool preferStriping, QuerySettings settings) { // Hash-repartition the source stream if (Child.OutputOrdered) { WrapPartitionedStreamHelperOrdered<TKey>( ExchangeUtilities.HashRepartitionOrdered<TSource, TGroupKey, TKey>( inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken), recipient, settings.CancellationState.MergedCancellationToken ); } else { WrapPartitionedStreamHelper<TKey, int>( ExchangeUtilities.HashRepartition<TSource, TGroupKey, TKey>( inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken), recipient, settings.CancellationState.MergedCancellationToken ); } } //--------------------------------------------------------------------------------------- // This is a helper method. WrapPartitionedStream decides what type TKey is going // to be, and then call this method with that key as a generic parameter. // private void WrapPartitionedStreamHelper<TIgnoreKey, TKey>( PartitionedStream<Pair<TSource, TGroupKey>, TKey> hashStream, IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient, CancellationToken cancellationToken) { int partitionCount = hashStream.PartitionCount; PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream = new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled); // If there is no element selector, we return a special identity enumerator. Otherwise, // we return one that will apply the element selection function during enumeration. for (int i = 0; i < partitionCount; i++) { if (_elementSelector == null) { Debug.Assert(typeof(TSource) == typeof(TElement)); var enumerator = new GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>( hashStream[i], _keyComparer, cancellationToken); outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator; } else { outputStream[i] = new GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>( hashStream[i], _keyComparer, _elementSelector, cancellationToken); } } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // This is a helper method. WrapPartitionedStream decides what type TKey is going // to be, and then call this method with that key as a generic parameter. // private void WrapPartitionedStreamHelperOrdered<TKey>( PartitionedStream<Pair<TSource, TGroupKey>, TKey> hashStream, IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient, CancellationToken cancellationToken) { int partitionCount = hashStream.PartitionCount; PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream = new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled); // If there is no element selector, we return a special identity enumerator. Otherwise, // we return one that will apply the element selection function during enumeration. IComparer<TKey> orderComparer = hashStream.KeyComparer; for (int i = 0; i < partitionCount; i++) { if (_elementSelector == null) { Debug.Assert(typeof(TSource) == typeof(TElement)); var enumerator = new OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>( hashStream[i], _keySelector, _keyComparer, orderComparer, cancellationToken); outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator; } else { outputStream[i] = new OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>( hashStream[i], _keySelector, _elementSelector, _keyComparer, orderComparer, cancellationToken); } } recipient.Receive(outputStream); } //----------------------------------------------------------------------------------- // Override of the query operator base class's Open method. // internal override QueryResults<IGrouping<TGroupKey, TElement>> Open(QuerySettings settings, bool preferStriping) { // We just open our child operator. Do not propagate the preferStriping value, but instead explicitly // set it to false. Regardless of whether the parent prefers striping or range partitioning, the output // will be hash-partitioned. QueryResults<TSource> childResults = Child.Open(settings, false); return new UnaryQueryOperatorResults(childResults, this, settings, false); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<IGrouping<TGroupKey, TElement>> AsSequentialQuery(CancellationToken token) { IEnumerable<TSource> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); if (_elementSelector == null) { Debug.Assert(typeof(TElement) == typeof(TSource)); return (IEnumerable<IGrouping<TGroupKey, TElement>>)wrappedChild.GroupBy(_keySelector, _keyComparer); } else { return wrappedChild.GroupBy(_keySelector, _elementSelector, _keyComparer); } } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for grouping elements and yielding the key-value sets. // // Assumptions: // Just like the Join operator, this won't work properly at all if the analysis engine // didn't choose to hash partition. We will simply not yield correct groupings. // internal abstract class GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> : QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey> { protected readonly QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> _source; // The data source to enumerate. protected readonly IEqualityComparer<TGroupKey> _keyComparer; // A key comparer. protected readonly CancellationToken _cancellationToken; private Mutables _mutables; // All of the mutable state. class Mutables { internal HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> _hashLookup; // The lookup with key-value mappings. internal int _hashLookupIndex; // The current index within the lookup. } //--------------------------------------------------------------------------------------- // Instantiates a new group by enumerator. // protected GroupByQueryOperatorEnumerator( QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source, IEqualityComparer<TGroupKey> keyComparer, CancellationToken cancellationToken) { Debug.Assert(source != null); _source = source; _keyComparer = keyComparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // MoveNext will invoke the entire query sub-tree, accumulating results into a hash- // table, upon the first call. Then for the first call and all subsequent calls, we will // just enumerate the key-set from the hash-table, retrieving groupings of key-elements. // internal override bool MoveNext(ref IGrouping<TGroupKey, TElement> currentElement, ref TOrderKey currentKey) { Debug.Assert(_source != null); // Lazy-init the mutable state. This also means we haven't yet built our lookup of // groupings, so we can go ahead and do that too. Mutables mutables = _mutables; if (mutables == null) { mutables = _mutables = new Mutables(); // Build the hash lookup and start enumerating the lookup at the beginning. mutables._hashLookup = BuildHashLookup(); Debug.Assert(mutables._hashLookup != null); mutables._hashLookupIndex = -1; } // Now, with a hash lookup in hand, we just enumerate the keys. So long // as the key-value lookup has elements, we have elements. if (++mutables._hashLookupIndex < mutables._hashLookup.Count) { currentElement = new GroupByGrouping<TGroupKey, TElement>( mutables._hashLookup[mutables._hashLookupIndex]); return true; } return false; } //----------------------------------------------------------------------------------- // Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate. // protected abstract HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup(); protected override void Dispose(bool disposing) { _source.Dispose(); } } //--------------------------------------------------------------------------------------- // A specialization of the group by enumerator for yielding elements with the identity // function. // internal sealed class GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> : GroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey> { //--------------------------------------------------------------------------------------- // Instantiates a new group by enumerator. // internal GroupByIdentityQueryOperatorEnumerator( QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source, IEqualityComparer<TGroupKey> keyComparer, CancellationToken cancellationToken) : base(source, keyComparer, cancellationToken) { } //----------------------------------------------------------------------------------- // Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate. // protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> BuildHashLookup() { HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> hashlookup = new HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer)); Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>); TOrderKey sourceKeyUnused = default(TOrderKey); int i = 0; while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Generate a key and place it into the hashtable. Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second); // If the key already exists, we just append it to the existing list -- // otherwise we will create a new one and add it to that instead. ListChunk<TSource> currentValue = null; if (!hashlookup.TryGetValue(key, ref currentValue)) { const int INITIAL_CHUNK_SIZE = 2; currentValue = new ListChunk<TSource>(INITIAL_CHUNK_SIZE); hashlookup.Add(key, currentValue); } Debug.Assert(currentValue != null); // Call to the base class to yield the current value. currentValue.Add(sourceElement.First); } return hashlookup; } } //--------------------------------------------------------------------------------------- // A specialization of the group by enumerator for yielding elements with any arbitrary // element selection function. // internal sealed class GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> : GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> { private readonly Func<TSource, TElement> _elementSelector; // Function to select elements. //--------------------------------------------------------------------------------------- // Instantiates a new group by enumerator. // internal GroupByElementSelectorQueryOperatorEnumerator( QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source, IEqualityComparer<TGroupKey> keyComparer, Func<TSource, TElement> elementSelector, CancellationToken cancellationToken) : base(source, keyComparer, cancellationToken) { Debug.Assert(elementSelector != null); _elementSelector = elementSelector; } //----------------------------------------------------------------------------------- // Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate. // protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup() { HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> hashlookup = new HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer)); Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>); TOrderKey sourceKeyUnused = default(TOrderKey); int i = 0; while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Generate a key and place it into the hashtable. Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second); // If the key already exists, we just append it to the existing list -- // otherwise we will create a new one and add it to that instead. ListChunk<TElement> currentValue = null; if (!hashlookup.TryGetValue(key, ref currentValue)) { const int INITIAL_CHUNK_SIZE = 2; currentValue = new ListChunk<TElement>(INITIAL_CHUNK_SIZE); hashlookup.Add(key, currentValue); } Debug.Assert(currentValue != null); // Call to the base class to yield the current value. currentValue.Add(_elementSelector(sourceElement.First)); } return hashlookup; } } //--------------------------------------------------------------------------------------- // Ordered version of the GroupBy operator. // internal abstract class OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> : QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey> { protected readonly QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> _source; // The data source to enumerate. private readonly Func<TSource, TGroupKey> _keySelector; // The key selection routine. protected readonly IEqualityComparer<TGroupKey> _keyComparer; // The key comparison routine. protected readonly IComparer<TOrderKey> _orderComparer; // The comparison routine for order keys. protected readonly CancellationToken _cancellationToken; private Mutables _mutables; // All the mutable state. class Mutables { internal HashLookup<Wrapper<TGroupKey>, GroupKeyData> _hashLookup; // The lookup with key-value mappings. internal int _hashLookupIndex; // The current index within the lookup. } //--------------------------------------------------------------------------------------- // Instantiates a new group by enumerator. // protected OrderedGroupByQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source, Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer, CancellationToken cancellationToken) { Debug.Assert(source != null); Debug.Assert(keySelector != null); _source = source; _keySelector = keySelector; _keyComparer = keyComparer; _orderComparer = orderComparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // MoveNext will invoke the entire query sub-tree, accumulating results into a hash- // table, upon the first call. Then for the first call and all subsequent calls, we will // just enumerate the key-set from the hash-table, retrieving groupings of key-elements. // internal override bool MoveNext(ref IGrouping<TGroupKey, TElement> currentElement, ref TOrderKey currentKey) { Debug.Assert(_source != null); Debug.Assert(_keySelector != null); // Lazy-init the mutable state. This also means we haven't yet built our lookup of // groupings, so we can go ahead and do that too. Mutables mutables = _mutables; if (mutables == null) { mutables = _mutables = new Mutables(); // Build the hash lookup and start enumerating the lookup at the beginning. mutables._hashLookup = BuildHashLookup(); Debug.Assert(mutables._hashLookup != null); mutables._hashLookupIndex = -1; } // Now, with a hash lookup in hand, we just enumerate the keys. So long // as the key-value lookup has elements, we have elements. if (++mutables._hashLookupIndex < mutables._hashLookup.Count) { GroupKeyData value = mutables._hashLookup[mutables._hashLookupIndex].Value; currentElement = value._grouping; currentKey = value._orderKey; return true; } return false; } //----------------------------------------------------------------------------------- // Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate. // protected abstract HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup(); protected override void Dispose(bool disposing) { _source.Dispose(); } //----------------------------------------------------------------------------------- // A data structure that holds information about elements with a particular key. // // This information includes two parts: // - An order key for the grouping. // - The grouping itself. The grouping consists of elements and the grouping key. // protected class GroupKeyData { internal TOrderKey _orderKey; internal OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> _grouping; internal GroupKeyData(TOrderKey orderKey, TGroupKey hashKey, IComparer<TOrderKey> orderComparer) { _orderKey = orderKey; _grouping = new OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement>(hashKey, orderComparer); } } } //--------------------------------------------------------------------------------------- // A specialization of the ordered GroupBy enumerator for yielding elements with the identity // function. // internal sealed class OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> : OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey> { //--------------------------------------------------------------------------------------- // Instantiates a new group by enumerator. // internal OrderedGroupByIdentityQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source, Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer, CancellationToken cancellationToken) : base(source, keySelector, keyComparer, orderComparer, cancellationToken) { } //----------------------------------------------------------------------------------- // Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate. // protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup() { HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>( new WrapperEqualityComparer<TGroupKey>(_keyComparer)); Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>); TOrderKey sourceOrderKey = default(TOrderKey); int i = 0; while (_source.MoveNext(ref sourceElement, ref sourceOrderKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Generate a key and place it into the hashtable. Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second); // If the key already exists, we just append it to the existing list -- // otherwise we will create a new one and add it to that instead. GroupKeyData currentValue = null; if (hashLookup.TryGetValue(key, ref currentValue)) { if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0) { currentValue._orderKey = sourceOrderKey; } } else { currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer); hashLookup.Add(key, currentValue); } Debug.Assert(currentValue != null); currentValue._grouping.Add(sourceElement.First, sourceOrderKey); } // Sort the elements within each group for (int j = 0; j < hashLookup.Count; j++) { hashLookup[j].Value._grouping.DoneAdding(); } return hashLookup; } } //--------------------------------------------------------------------------------------- // A specialization of the ordered GroupBy enumerator for yielding elements with any arbitrary // element selection function. // internal sealed class OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> : OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> { private readonly Func<TSource, TElement> _elementSelector; // Function to select elements. //--------------------------------------------------------------------------------------- // Instantiates a new group by enumerator. // internal OrderedGroupByElementSelectorQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source, Func<TSource, TGroupKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer, CancellationToken cancellationToken) : base(source, keySelector, keyComparer, orderComparer, cancellationToken) { Debug.Assert(elementSelector != null); _elementSelector = elementSelector; } //----------------------------------------------------------------------------------- // Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate. // protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup() { HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>( new WrapperEqualityComparer<TGroupKey>(_keyComparer)); Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>); TOrderKey sourceOrderKey = default(TOrderKey); int i = 0; while (_source.MoveNext(ref sourceElement, ref sourceOrderKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Generate a key and place it into the hashtable. Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second); // If the key already exists, we just append it to the existing list -- // otherwise we will create a new one and add it to that instead. GroupKeyData currentValue = null; if (hashLookup.TryGetValue(key, ref currentValue)) { if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0) { currentValue._orderKey = sourceOrderKey; } } else { currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer); hashLookup.Add(key, currentValue); } Debug.Assert(currentValue != null); // Call to the base class to yield the current value. currentValue._grouping.Add(_elementSelector(sourceElement.First), sourceOrderKey); } // Sort the elements within each group for (int j = 0; j < hashLookup.Count; j++) { hashLookup[j].Value._grouping.DoneAdding(); } return hashLookup; } } //--------------------------------------------------------------------------------------- // This little type implements the IGrouping<K,T> interface, and exposes a single // key-to-many-values mapping. // internal class GroupByGrouping<TGroupKey, TElement> : IGrouping<TGroupKey, TElement> { private KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> _keyValues; // A key value pair. //--------------------------------------------------------------------------------------- // Constructs a new grouping out of the key value pair. // internal GroupByGrouping(KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> keyValues) { Debug.Assert(keyValues.Value != null); _keyValues = keyValues; } //--------------------------------------------------------------------------------------- // The key this mapping represents. // TGroupKey IGrouping<TGroupKey, TElement>.Key { get { return _keyValues.Key.Value; } } //--------------------------------------------------------------------------------------- // Access to value enumerators. // IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator() { Debug.Assert(_keyValues.Value != null); return _keyValues.Value.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TElement>)this).GetEnumerator(); } } /// <summary> /// An ordered version of the grouping data structure. Represents an ordered group of elements that /// have the same grouping key. /// </summary> internal class OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> : IGrouping<TGroupKey, TElement> { const int INITIAL_CHUNK_SIZE = 2; private TGroupKey _groupKey; // The group key for this grouping private ListChunk<Pair<TOrderKey, TElement>> _values; // Values in this group private TElement[] _sortedValues; // Sorted values (allocated in DoneAdding) private IComparer<TOrderKey> _orderComparer; // Comparer for order keys /// <summary> /// Constructs a new grouping /// </summary> internal OrderedGroupByGrouping( TGroupKey groupKey, IComparer<TOrderKey> orderComparer) { _groupKey = groupKey; _values = new ListChunk<Pair<TOrderKey, TElement>>(INITIAL_CHUNK_SIZE); _orderComparer = orderComparer; } /// <summary> /// The key this grouping represents. /// </summary> TGroupKey IGrouping<TGroupKey, TElement>.Key { get { return _groupKey; } } IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator() { Debug.Assert(_sortedValues != null); return ((IEnumerable<TElement>)_sortedValues).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TElement>)this).GetEnumerator(); } /// <summary> /// Add an element /// </summary> internal void Add(TElement value, TOrderKey orderKey) { Debug.Assert(_values != null); _values.Add(new Pair<TOrderKey, TElement>(orderKey, value)); } /// <summary> /// No more elements will be added, so we can sort the group now. /// </summary> internal void DoneAdding() { Debug.Assert(_values != null); int count = _values.Count; ListChunk<Pair<TOrderKey, TElement>> curChunk = _values; while ((curChunk = curChunk.Next) != null) { count += curChunk.Count; } TElement[] values = new TElement[count]; TOrderKey[] orderKeys = new TOrderKey[count]; int idx = 0; foreach (Pair<TOrderKey, TElement> p in _values) { orderKeys[idx] = p.First; values[idx] = p.Second; idx++; } Array.Sort(orderKeys, values, _orderComparer); _sortedValues = values; #if DEBUG _values = null; // Any future calls to Add() or DoneAdding() will fail #endif } } }
using UnityEngine; using System; public class FSliceSprite : FSprite { private float _insetTop; private float _insetRight; private float _insetBottom; private float _insetLeft; private float _width; private float _height; private int _sliceCount; private Vector2[] _uvVertices; public FSliceSprite (string elementName, float width, float height, float insetTop, float insetRight, float insetBottom, float insetLeft) : this(Futile.atlasManager.GetElementWithName(elementName), width, height, insetTop, insetRight, insetBottom, insetLeft) { } public FSliceSprite (FAtlasElement element, float width, float height, float insetTop, float insetRight, float insetBottom, float insetLeft) : base() { _width = width; _height = height; _insetTop = insetTop; _insetRight = insetRight; _insetBottom = insetBottom; _insetLeft = insetLeft; Init(FFacetType.Quad, element,0); //this will call HandleElementChanged(), which will call SetupSlices(); _isAlphaDirty = true; UpdateLocalVertices(); } override public void HandleElementChanged() { SetupSlices(); } public void SetupSlices () { _insetTop = Math.Max (0,_insetTop); _insetRight = Math.Max(0,_insetRight); _insetBottom = Math.Max (0,_insetBottom); _insetLeft = Math.Max(0,_insetLeft); _sliceCount = 1; if(_insetTop > 0) _sliceCount++; if(_insetRight > 0) _sliceCount++; if(_insetLeft > 0) _sliceCount++; if(_insetBottom > 0) _sliceCount++; if(_insetTop > 0 && _insetRight > 0) _sliceCount++; if(_insetTop > 0 && _insetLeft > 0) _sliceCount++; if(_insetBottom > 0 && _insetRight > 0) _sliceCount++; if(_insetBottom > 0 && _insetLeft > 0) _sliceCount++; _numberOfFacetsNeeded = _sliceCount; _localVertices = new Vector2[_sliceCount*4]; _uvVertices = new Vector2[_sliceCount*4]; _areLocalVerticesDirty = true; if(_numberOfFacetsNeeded != _sliceCount) { _numberOfFacetsNeeded = _sliceCount; if(_isOnStage) _stage.HandleFacetsChanged(); } } override public void UpdateLocalVertices() { _areLocalVerticesDirty = false; Rect uvRect = element.uvRect; float itop = Math.Max(0,Math.Min(_insetTop, _element.sourceSize.y-_insetBottom)); float iright = Math.Max(0,Math.Min(_insetRight, _element.sourceSize.x-_insetLeft)); float ibottom = Math.Max(0,Math.Min(_insetBottom, _element.sourceSize.y-_insetTop)); float ileft = Math.Max(0,Math.Min(_insetLeft, _element.sourceSize.x-_insetRight)); float uvtop = uvRect.height*(itop/_element.sourceSize.y); float uvleft = uvRect.width*(ileft/_element.sourceSize.x); float uvbottom = uvRect.height*(ibottom/_element.sourceSize.y); float uvright = uvRect.width*(iright/_element.sourceSize.x); _textureRect.x = -_anchorX*_width; _textureRect.y = -_anchorY*_height; _textureRect.width = _width; _textureRect.height = _height; _localRect = _textureRect; float localXMin = _localRect.xMin; float localXMax = _localRect.xMax; float localYMin = _localRect.yMin; float localYMax = _localRect.yMax; float uvXMin = uvRect.xMin; float uvXMax = uvRect.xMax; float uvYMin = uvRect.yMin; float uvYMax = uvRect.yMax; int sliceVertIndex = 0; for(int s = 0; s<9; s++) { if(s == 0) //center slice { _localVertices[sliceVertIndex].Set (localXMin + ileft,localYMax - itop); _localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMax - itop); _localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMin + ibottom); _localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMin + ibottom); _uvVertices[sliceVertIndex].Set (uvXMin + uvleft,uvYMax - uvtop); _uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMax - uvtop); _uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMin + uvbottom); _uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMin + uvbottom); sliceVertIndex += 4; } else if (s == 1 && _insetTop > 0) //top center slice { _localVertices[sliceVertIndex].Set (localXMin + ileft,localYMax); _localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMax); _localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMax - itop); _localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMax - itop); _uvVertices[sliceVertIndex].Set (uvXMin + uvleft,uvYMax); _uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMax); _uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMax - uvtop); _uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMax - uvtop); sliceVertIndex += 4; } else if (s == 2 && _insetRight > 0) //right center slice { _localVertices[sliceVertIndex].Set (localXMax - iright,localYMax - itop); _localVertices[sliceVertIndex+1].Set (localXMax,localYMax - itop); _localVertices[sliceVertIndex+2].Set (localXMax,localYMin + ibottom); _localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMin + ibottom); _uvVertices[sliceVertIndex].Set (uvXMax - uvright,uvYMax - uvtop); _uvVertices[sliceVertIndex+1].Set (uvXMax,uvYMax - uvtop); _uvVertices[sliceVertIndex+2].Set (uvXMax,uvYMin + uvbottom); _uvVertices[sliceVertIndex+3].Set (uvXMax - uvright,uvYMin + uvbottom); sliceVertIndex += 4; } else if (s == 3 && _insetBottom > 0) //bottom center slice { _localVertices[sliceVertIndex].Set (localXMin + ileft,localYMin + ibottom); _localVertices[sliceVertIndex+1].Set (localXMax - iright,localYMin + ibottom); _localVertices[sliceVertIndex+2].Set (localXMax - iright,localYMin); _localVertices[sliceVertIndex+3].Set (localXMin + ileft,localYMin); _uvVertices[sliceVertIndex].Set (uvXMin + uvleft,uvYMin + uvbottom); _uvVertices[sliceVertIndex+1].Set (uvXMax - uvright,uvYMin + uvbottom); _uvVertices[sliceVertIndex+2].Set (uvXMax - uvright,uvYMin); _uvVertices[sliceVertIndex+3].Set (uvXMin + uvleft,uvYMin); sliceVertIndex += 4; } else if (s == 4 && _insetLeft > 0) //left center slice { _localVertices[sliceVertIndex].Set (localXMin,localYMax - itop); _localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMax - itop); _localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMin + ibottom); _localVertices[sliceVertIndex+3].Set (localXMin,localYMin + ibottom); _uvVertices[sliceVertIndex].Set (uvXMin,uvYMax - uvtop); _uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft,uvYMax - uvtop); _uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft,uvYMin + uvbottom); _uvVertices[sliceVertIndex+3].Set (uvXMin,uvYMin + uvbottom); sliceVertIndex += 4; } else if (s == 5 && _insetTop > 0 && _insetLeft > 0) //top left slice { _localVertices[sliceVertIndex].Set (localXMin,localYMax); _localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMax); _localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMax - itop); _localVertices[sliceVertIndex+3].Set (localXMin,localYMax - itop); _uvVertices[sliceVertIndex].Set (uvXMin,uvYMax); _uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft,uvYMax); _uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft,uvYMax - uvtop); _uvVertices[sliceVertIndex+3].Set (uvXMin,uvYMax - uvtop); sliceVertIndex += 4; } else if (s == 6 && _insetTop > 0 && _insetRight > 0) //top right slice { _localVertices[sliceVertIndex].Set (localXMax - iright,localYMax); _localVertices[sliceVertIndex+1].Set (localXMax,localYMax); _localVertices[sliceVertIndex+2].Set (localXMax,localYMax - itop); _localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMax - itop); _uvVertices[sliceVertIndex].Set (uvXMax - uvright, uvYMax); _uvVertices[sliceVertIndex+1].Set (uvXMax, uvYMax); _uvVertices[sliceVertIndex+2].Set (uvXMax, uvYMax - uvtop); _uvVertices[sliceVertIndex+3].Set (uvXMax - uvright, uvYMax - uvtop); sliceVertIndex += 4; } else if (s == 7 && _insetBottom > 0 && _insetRight > 0) //bottom right slice { _localVertices[sliceVertIndex].Set (localXMax - iright,localYMin + ibottom); _localVertices[sliceVertIndex+1].Set (localXMax,localYMin + ibottom); _localVertices[sliceVertIndex+2].Set (localXMax,localYMin); _localVertices[sliceVertIndex+3].Set (localXMax - iright,localYMin); _uvVertices[sliceVertIndex].Set (uvXMax - uvright, uvYMin + uvbottom); _uvVertices[sliceVertIndex+1].Set (uvXMax, uvYMin + uvbottom); _uvVertices[sliceVertIndex+2].Set (uvXMax, uvYMin); _uvVertices[sliceVertIndex+3].Set (uvXMax - uvright, uvYMin); sliceVertIndex += 4; } else if (s == 8 && _insetBottom > 0 && _insetLeft > 0) //bottom left slice { _localVertices[sliceVertIndex].Set (localXMin,localYMin + ibottom); _localVertices[sliceVertIndex+1].Set (localXMin + ileft,localYMin + ibottom); _localVertices[sliceVertIndex+2].Set (localXMin + ileft,localYMin); _localVertices[sliceVertIndex+3].Set (localXMin,localYMin); _uvVertices[sliceVertIndex].Set (uvXMin, uvYMin + uvbottom); _uvVertices[sliceVertIndex+1].Set (uvXMin + uvleft, uvYMin + uvbottom); _uvVertices[sliceVertIndex+2].Set (uvXMin + uvleft, uvYMin); _uvVertices[sliceVertIndex+3].Set (uvXMin, uvYMin); sliceVertIndex += 4; } } _isMeshDirty = true; } override public void PopulateRenderLayer() { if(_isOnStage && _firstFacetIndex != -1) { _isMeshDirty = false; for(int s = 0; s<_sliceCount; s++) { int sliceVertIndex = s*4; int vertexIndex0 = (_firstFacetIndex+s)*4; int vertexIndex1 = vertexIndex0 + 1; int vertexIndex2 = vertexIndex0 + 2; int vertexIndex3 = vertexIndex0 + 3; Vector3[] vertices = _renderLayer.vertices; Vector2[] uvs = _renderLayer.uvs; Color[] colors = _renderLayer.colors; _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0], _localVertices[sliceVertIndex],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex1], _localVertices[sliceVertIndex+1],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex2], _localVertices[sliceVertIndex+2],0); _concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex3], _localVertices[sliceVertIndex+3],0); uvs[vertexIndex0] = _uvVertices[sliceVertIndex]; uvs[vertexIndex1] = _uvVertices[sliceVertIndex+1]; uvs[vertexIndex2] = _uvVertices[sliceVertIndex+2]; uvs[vertexIndex3] = _uvVertices[sliceVertIndex+3]; colors[vertexIndex0] = _alphaColor; colors[vertexIndex1] = _alphaColor; colors[vertexIndex2] = _alphaColor; colors[vertexIndex3] = _alphaColor; _renderLayer.HandleVertsChange(); } } } public void SetInsets(float insetTop, float insetRight, float insetBottom, float insetLeft) { _insetTop = insetTop; _insetRight = insetRight; _insetBottom = insetBottom; _insetLeft = insetLeft; SetupSlices(); } override public float width { get { return _width; } set { _width = value; _areLocalVerticesDirty = true; } } override public float height { get { return _height; } set { _height = value; _areLocalVerticesDirty = true; } } }
/* * Reactor 3D MIT License * * Copyright (c) 2010 Reiser Games * * 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.Text; using Reactor; namespace WinGame { public class Game : RGame { RScene scene; RScreen2D screen; RCamera camera; RAtmosphere atmosphere; RActor mesh; RInput input; RParticleEmitter emitter; RParticleEmitter emitter2; RLandscape landscape; RWater water; RTextureFactory textures; RLightingFactory lighting; RMaterialFactory materials; RFONT font; bool fog = true; public Game() : base() { } public override void Init() { #if !XBOX this.Reactor.Init3DGame(1280, 720, false); #else this.Reactor.Init3DGame(180, 720, true); this.Reactor.SetXBox360Resolution(CONST_REACTOR_XBOX_RESOLUTION.r720P); #endif this.Reactor.SetWatermarkPosition(CONST_REACTOR_WATERMARK_POSITION.BOTTOM_RIGHT); Reactor.ShowFPS(true); Reactor.AllowEscapeQuit(true); Reactor.ShowMouse(false); //Reactor.SetDebugFile("debug.txt"); //Reactor.SetDebugMode(true); scene = new RScene(); screen = new RScreen2D(); textures = new RTextureFactory(); //lighting = new RLightingFactory(); //materials = new RMaterialFactory(); Reactor.Resized += new ViewportResized(Reactor_Resized); camera = this.Reactor.GetCamera(); camera.SetClipPlanes(1f, 180000); atmosphere = new RAtmosphere(); atmosphere.Initialize(); input = new RInput(); camera.Position = R3DVECTOR.Zero; camera.LookAt(new R3DVECTOR(0.5f,0f,0.5f)); font = screen.Create_TextureFont("Font1", "Font1"); //emitter = (RParticleEmitter)scene.CreateNode<RParticleEmitter>("myemitter"); //emitter2 = scene.CreateParticleEmitter(CONST_REACTOR_PARTICLETYPE.Billboard, "myemitter2"); landscape = (RLandscape)scene.CreateNode<RLandscape>("myland"); water = (RWater)scene.CreateNode<RWater>("mywater"); //mesh = (RActor)scene.CreateNode<RActor>("mymesh"); } void Reactor_Resized() { Reactor.Resize(Reactor.GetViewport().Width, Reactor.GetViewport().Height); } public override void Dispose() { //Reactor.ReleaseAll(); } public override void Load() { int islands_down = textures.LoadTexture("Textures\\islands_down", "islands_down", CONST_RTEXTURE_TYPE.Texture2D); int islands_up = textures.LoadTexture("Textures\\islands_up", "islands_up", CONST_RTEXTURE_TYPE.Texture2D); int islands_east = textures.LoadTexture("Textures\\islands_east", "islands_east", CONST_RTEXTURE_TYPE.Texture2D); int islands_west = textures.LoadTexture("Textures\\islands_west", "islands_west", CONST_RTEXTURE_TYPE.Texture2D); int islands_north = textures.LoadTexture("Textures\\islands_north", "islands_north", CONST_RTEXTURE_TYPE.Texture2D); int islands_south = textures.LoadTexture("Textures\\islands_south", "islands_south", CONST_RTEXTURE_TYPE.Texture2D); //int starstexture = textures.LoadTexture("stars", "starbg", CONST_RTEXTURE_TYPE.Texture2D); int skycube = textures.BuildCubeMap(1024, "bgcube", islands_west, islands_up, islands_north, islands_east, islands_down, islands_south, RSURFACEFORMAT.Bgr32); int skytexture = textures.LoadTexture("skybox001", "sky", CONST_RTEXTURE_TYPE.TextureCube); int pointtexture = textures.LoadTexture("point", "point", CONST_RTEXTURE_TYPE.Texture2D); int terraintexture = textures.LoadTexture("gcanyonTerrain", "terrainData", CONST_RTEXTURE_TYPE.Texture2D); int terrainheight = textures.LoadTexture("gcanyon", "terrain", CONST_RTEXTURE_TYPE.Texture2D); int rock = textures.LoadTexture("Textures\\rock", "rock", CONST_RTEXTURE_TYPE.Texture2D); int rocknormal = textures.LoadTexture("Textures\\rockNormal", "rockNormal", CONST_RTEXTURE_TYPE.Texture2D); int grass = textures.LoadTexture("Textures\\grass", "grass", CONST_RTEXTURE_TYPE.Texture2D); int grassnormal = textures.LoadTexture("Textures\\grassNormal", "grassNormal", CONST_RTEXTURE_TYPE.Texture2D); int sand = textures.LoadTexture("Textures\\sand", "sand", CONST_RTEXTURE_TYPE.Texture2D); int sandnormal = textures.LoadTexture("Textures\\sandNormal", "sandNormal", CONST_RTEXTURE_TYPE.Texture2D); int snow = textures.LoadTexture("Textures\\snow", "snow", CONST_RTEXTURE_TYPE.Texture2D); int snownormal = textures.LoadTexture("Textures\\snowNormal", "snowNormal", CONST_RTEXTURE_TYPE.Texture2D); //int billboardgrass = textures.LoadTexture("billboardgrass", "billboardgrass", CONST_RTEXTURE_TYPE.Texture2D); int tree = textures.LoadTexture("Textures\\Pine", "Pine", CONST_RTEXTURE_TYPE.Texture2D); //int grassbillboard = textures.LoadTexture("Textures\\billboardgrass", "GrassBillboard", CONST_RTEXTURE_TYPE.Texture2D); int wave0 = textures.LoadTexture("Textures\\wave0", "wave0", CONST_RTEXTURE_TYPE.Texture2D); int wave1 = textures.LoadTexture("Textures\\wave1", "wave1", CONST_RTEXTURE_TYPE.Texture2D); //mesh.Load("dude"); //mesh.SetPosition(0, 0, 0); //mesh.PlayAnimation("Take 001", 1.0f); //mesh.SetScale(0.1f, 0.1f, 0.1f); //mesh.SetLookAt(new R3DVECTOR(-1, 0, -1)); //R3DVECTOR scale = mesh.GetScale(); //emitter.SetTexture(pointtexture); //emitter.BuildEmitter(135000); //emitter2.BuildEmitter(500); //emitter2.SetTexture(pointtexture); //emitter.SetPointSettings(pointtexture, 135000, 10000, -1.0f,1.0f,0.0f,0.0f, R3DVECTOR.Down * 500f, 100.0f, 0.0f, 0.0f, 150, 150, 150,150); landscape.SetDetailLevel(RLANDSCAPE_LOD.Ultra); landscape.SetElevationStrength(10); landscape.SetMinGrassPlotElevation(1f); landscape.SetMaxGrassPlotElevation(700f); landscape.InitTerrainTextures(snow, grass, sand); landscape.InitTerrainNormalsTextures(snownormal, grassnormal, rocknormal); landscape.InitTerrainGrass(tree, terraintexture, 1750); landscape.SetTerrainGrassSize(18f, 40f); landscape.SetPosition(new R3DVECTOR((256f * 100f) - (512f * 100f), -300f, (256f * 100f) - (512f * 100f))); landscape.Initialize(terrainheight, terraintexture, 50, 12); landscape.SetupLODS(); // Put camera somewhere on the landscape. Rule is HeightMap Width x Scale for exact position. I'm dividing by 3 to place somewhere // in the first third area so we have landscape around us. //camera.Position = new R3DVECTOR((512 * 40) / 3, landscape.GetTerrainHeight((512*40)/3, (512*40)/3)+5f, (512 * 40) / 3); camera.Position = new R3DVECTOR(1.0f, 1.0f, 1.0f); camera.SetFieldOfView(45f); camera.SetClipPlanes(1f, 180000f); camera.LookAt(camera.Position * R3DVECTOR.Backward); //input.SetMousePosition(1280 / 2, 800 / 2); camera.CurrentBehavior = RCamera.Behavior.Flight; //mesh.SetPosition(camera.Position + (camera.ViewDirection*1.0001f)); //mesh.SetLookAt(new R3DVECTOR(mesh.GetPosition().X-1, mesh.GetPosition().Y, mesh.GetPosition().Z-1)); atmosphere.SkyBox_Enable(true); atmosphere.SkyBox_Initialize(); atmosphere.SkyBox_SetTextureCube(skycube); atmosphere.Fog_Enable(fog); atmosphere.Fog_SetDistance(9000f); atmosphere.Fog_SetColor(0.7f, 0.7f, 0.7f, 0.5f); atmosphere.Sky_SetSunlightColor(new R4DVECTOR(1f, 1f, 1f, 1.0f)); atmosphere.Sky_SetSunlightDirection(new R3DVECTOR(0.1f, -1.5f, 0.1f)); atmosphere.Sky_SetGlobalAmbientColor(new R4DVECTOR(0.1f, 0.1f, 0.1f, 1.0f)); //emitter.SetPosition(v); //emitter2.SetPosition(v); //emitter2.SetScale(1f); //emitter2.SetBillboardSize(5f); RWaterOptions options = new RWaterOptions(); options.WaveMapAsset0ID = wave0; options.WaveMapAsset1ID = wave1; options.WaveMapScale = 100.0f; options.WaterColor = new R4DVECTOR(0.5f, 0.6f, 0.7f, 0.5f); options.WaveMapVelocity0 = new R2DVECTOR(0.005f, 0.003f); options.WaveMapVelocity1 = new R2DVECTOR(-0.001f, 0.01f); options.SunFactor = 1.0f; options.SunPower = 350f; options.Width = 256; options.Height = 256; options.CellSpacing = 1.0f; options.RenderTargetSize = 256; water.SetOptions(options); water.SetReflectionRenderDelegate(Reflection); water.Init(64, 12f, new R2DVECTOR(0.00003f,-0.00001f)); water.SetScale(new R3DVECTOR(10000f,5f,10000f)); water.SetWaveNormalTexture(wave0); water.SetPosition(new R3DVECTOR(256*10000, 300f, 256*10000)); //water.SetWaveParameters(0.008f, 0.0003f, 0.38f, new R4DVECTOR(0.2f, 0.2f, 0.1f, 1f), 0.29f, 0.3f, new R4DVECTOR(0.5f, 0.5f, 0.5f, 0.5f), new R4DVECTOR(0.2f, 0.4f, 0.7f, 1f), false); //landscape.ToggleTerrainDraw(); } //This is where we render our objects for the water reflections! public void Reflection(R3DMATRIX ReflectionMatrix) { try { // Set our reflection matrix for the atmosphere to draw itself flipped atmosphere.SkyBox_SetReflectionMatrix(ReflectionMatrix); // Render our Sky atmosphere.SkyBox_Render(); // Reset the sky's matrix back to it's original atmosphere.SkyBox_ResetReflectionMatrix(); // Landscape is different as scaling is baked in, instead we call SetReflectionMatrix and it will do the rest. //landscape.SetReflectionMatrix(ReflectionMatrix); //landscape.Render(); //landscape.RenderGrass(); //landscape.ResetReflectionMatrix(); // Reset reflection matrix on the Landscape to draw as normal. // With any game objects, you want to get it's world matrix first, multiply the reflection, and set the matrix back to the game object. // The next time this is called, it will flip it back. //R3DMATRIX meshMatrix = mesh.GetMatrix(); //mesh.SetMatrix(meshMatrix * ReflectionMatrix); //mesh.Render(); //mesh.SetMatrix(meshMatrix); } catch (Exception e) { } } public override void Render2D() { //long mem = GC.GetTotalMemory(false)/1024; //screen.Action_Begin2D(); //screen.Draw_TextureFont(font, 40, 65, Reactor.GetCamera().ViewDirection.ToString()); //screen.Draw_TextureFont(font, 40, 80, "Garbage Memory: " + mem.ToString()+"kb"); //screen.Action_End2D(); } public override void Render() { try { atmosphere.SkyBox_Render(); landscape.Render(); water.Render(); //mesh.Render(); //landscape.RenderGrass(); //emitter.Render(); //emitter2.Render(); //screen.Draw_TextureFont(font, 40, 50, emitter.GetPosition().ToString()); //screen.Draw_Line3D(new R3DVECTOR(0,0,0), new R3DVECTOR(1500f, 150f, 1500f), new R4DVECTOR(1f,1f,1f,1f)); //screen.Draw_Rect2D(40, 75, 100, 2, new R4DVECTOR(1f, 1f, 1f, 1f)); //screen.Draw_Texture2D(0, 10, 20, 128, 128, 1, 1); } catch (Exception e) { } } R2DVECTOR lastMouseLocation; public override void Update() { int X,Y,Wheel; bool b1,b2,b3; #if !XBOX input.GetCenteredMouse(out X, out Y, out Wheel, out b1, out b2, out b3); R2DVECTOR mouseMoved = new R2DVECTOR(lastMouseLocation.X - X, lastMouseLocation.Y - Y); lastMouseLocation = new R2DVECTOR(X, Y); //camera.RotateFirstPerson(X * 0.1f, Y * 0.1f); camera.RotateFlight(X*0.1f, Y*0.1f, 0); //camera.LevelRoll(); if (input.IsKeyDown(CONST_REACTOR_KEY.A) && !input.IsKeyDown(CONST_REACTOR_KEY.LeftShift)) { camera.Move(-0.001f * Reactor.AccurateTimeElapsed(), 0f, 0f); //camera.RotateY(0.005f * Reactor.AccurateTimeElapsed()); } if (input.IsKeyDown(CONST_REACTOR_KEY.D) && !input.IsKeyDown(CONST_REACTOR_KEY.LeftShift)) { camera.Move(0.001f * Reactor.AccurateTimeElapsed(), 0f, 0f); //camera.RotateY(-0.005f * Reactor.AccurateTimeElapsed()); } if (input.IsKeyDown(CONST_REACTOR_KEY.W) && !input.IsKeyDown(CONST_REACTOR_KEY.LeftShift)) { camera.Move(0f, 0f, 0.001f * Reactor.AccurateTimeElapsed()); //camera.Position = new R3DVECTOR(camera.Position.X, landscape.GetTerrainHeight(camera.Position.X, camera.Position.Z)+2f, camera.Position.Z); } if (input.IsKeyDown(CONST_REACTOR_KEY.S) && !input.IsKeyDown(CONST_REACTOR_KEY.LeftShift)) { camera.Move(0f, 0f, -0.001f * Reactor.AccurateTimeElapsed()); //camera.Position = new R3DVECTOR(camera.Position.X, landscape.GetTerrainHeight(camera.Position.X, camera.Position.Z) + 2f, camera.Position.Z); } if (input.IsKeyDown(CONST_REACTOR_KEY.LeftShift) && input.IsKeyDown(CONST_REACTOR_KEY.W)) camera.Move(0f, 0f, 0.1f * Reactor.AccurateTimeElapsed()); if (input.IsKeyDown(CONST_REACTOR_KEY.LeftShift) && input.IsKeyDown(CONST_REACTOR_KEY.S)) camera.Move(0f, 0f, -0.1f * Reactor.AccurateTimeElapsed()); if (input.IsKeyDown(CONST_REACTOR_KEY.LeftShift) && input.IsKeyDown(CONST_REACTOR_KEY.A)) camera.Move(-0.1f * Reactor.AccurateTimeElapsed(), 0f, 0f); if (input.IsKeyDown(CONST_REACTOR_KEY.LeftShift) && input.IsKeyDown(CONST_REACTOR_KEY.D)) camera.Move(0.1f * Reactor.AccurateTimeElapsed(), 0f, 0f); if (input.IsKeyDown(CONST_REACTOR_KEY.T)) landscape.ToggleBoundingBoxDraw(); if (input.IsKeyDown(CONST_REACTOR_KEY.F)) { if (fog) { fog = false; } else { fog = true; } atmosphere.Fog_Enable(fog); } if (input.IsKeyDown(CONST_REACTOR_KEY.F2)) scene.SetShadeMode(CONST_REACTOR_FILLMODE.Wireframe); if (input.IsKeyDown(CONST_REACTOR_KEY.F3)) scene.SetShadeMode(CONST_REACTOR_FILLMODE.Solid); if (input.IsKeyDown(CONST_REACTOR_KEY.PrintScreen)) this.Reactor.TakeScreenshot("sshot"+Reactor.GetTicks().ToString()); if (input.IsKeyDown(CONST_REACTOR_KEY.Left)) camera.RotateX(0.1f); if (input.IsKeyDown(CONST_REACTOR_KEY.Right)) camera.RotateX(-0.1f); if (input.IsKeyDown(CONST_REACTOR_KEY.Space)) camera.LevelRoll(); #endif #if XBOX if (input.GetControllerState(0).IsConnected) { Microsoft.Xna.Framework.Input.GamePadState state = input.GetControllerState(0); camera.Move(state.ThumbSticks.Left.X*5.5f, 0, state.ThumbSticks.Left.Y*5.5f); camera.RotateFlight(state.ThumbSticks.Right.X, -state.ThumbSticks.Right.Y, 0.0f); //camera.RotateFirstPerson(state.ThumbSticks.Right.X, -state.ThumbSticks.Right.Y); if(input.GetControllerState(0).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.LeftShoulder)) camera.LevelRoll(); if (state.IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.Back)) Exit(); } #endif atmosphere.Update(); landscape.Update(); //float landheight = landscape.GetTerrainHeight(camera.Position.X, camera.Position.Z); //if (landheight < water.GetPosition().Y) //{ //landheight = water.GetPosition().Y; //} //R3DVECTOR ch = new R3DVECTOR(camera.Position.X, landheight + 30, camera.Position.Z); //camera.Position = ch; //camera.Update(); //mesh.Move(0f, 0, 0.03995f * Reactor.AccurateTimeElapsed()); //R3DVECTOR v = mesh.GetPosition(); //mesh.SetPosition(v.X, landscape.GetTerrainHeight(v.X, v.Z), v.Z); //mesh.SetLookAt(new R3DVECTOR(mesh.GetPosition().X - 1, mesh.GetPosition().Y, mesh.GetPosition().Z - 1)); //R3DVECTOR v = camera.Position; //v.Y = landscape.GetTerrainHeight(v.X, v.Z) + 50f; //if(fog) //camera.Position = v; //mesh.Update(); //camera.Position = v; //camera.Update(); //emitter.SetDirection(R3DVECTOR.Down * 50f); //emitter.SetPosition(emitter.GetPosition() * new Random().Next()); //r = new Random((int)Reactor.GetTicks()); //float x = (float)r.NextDouble() * (1000f) - 500f; //float z = (float)r.NextDouble() * (1000f) - 500f; //emitter.SetPosition(new R3DVECTOR(camera.Position.X + x, camera.Position.Y + 200f, camera.Position.Z + z)); //emitter.Update(); //R3DVECTOR v = Ball(); //emitter2.SetPosition(v); //emitter2.Update(); water.Update(); //landscape.Update(); } Random r = new Random(); float angle = 0f; float angle2 = 0f; R3DVECTOR Ball() { float radius = 10; angle += .005f; if (angle > 360) angle = 0; angle2 += .005f; if (angle2 > 360) angle2 = 0; float cos = radius * (float)Math.Cos(angle); float sin = radius * (float)Math.Sin(angle); float cos2 = radius * (float)Math.Cos(angle2); float sin2 = (float)Math.Pow(radius, 1) * (float)Math.Sin(angle2); return new R3DVECTOR(cos * cos2, sin * cos2, sin2); } } }
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Date; using Org.BouncyCastle.X509.Extension; namespace Org.BouncyCastle.X509.Store { /** * This class is an <code>Selector</code> like implementation to select * attribute certificates from a given set of criteria. * * @see org.bouncycastle.x509.X509AttributeCertificate * @see org.bouncycastle.x509.X509Store */ public class X509AttrCertStoreSelector : IX509Selector { // TODO: name constraints??? private IX509AttributeCertificate attributeCert; private DateTimeObject attributeCertificateValid; private AttributeCertificateHolder holder; private AttributeCertificateIssuer issuer; private IBigInteger serialNumber; private ISet targetNames = new HashSet(); private ISet targetGroups = new HashSet(); public X509AttrCertStoreSelector() { } private X509AttrCertStoreSelector( X509AttrCertStoreSelector o) { this.attributeCert = o.attributeCert; this.attributeCertificateValid = o.attributeCertificateValid; this.holder = o.holder; this.issuer = o.issuer; this.serialNumber = o.serialNumber; this.targetGroups = new HashSet(o.targetGroups); this.targetNames = new HashSet(o.targetNames); } /// <summary> /// Decides if the given attribute certificate should be selected. /// </summary> /// <param name="obj">The attribute certificate to be checked.</param> /// <returns><code>true</code> if the object matches this selector.</returns> public bool Match( object obj) { if (obj == null) throw new ArgumentNullException("obj"); IX509AttributeCertificate attrCert = obj as IX509AttributeCertificate; if (attrCert == null) return false; if (this.attributeCert != null && !this.attributeCert.Equals(attrCert)) return false; if (serialNumber != null && !attrCert.SerialNumber.Equals(serialNumber)) return false; if (holder != null && !attrCert.Holder.Equals(holder)) return false; if (issuer != null && !attrCert.Issuer.Equals(issuer)) return false; if (attributeCertificateValid != null && !attrCert.IsValid(attributeCertificateValid.Value)) return false; if (targetNames.Count > 0 || targetGroups.Count > 0) { Asn1OctetString targetInfoExt = attrCert.GetExtensionValue( X509Extensions.TargetInformation); if (targetInfoExt != null) { TargetInformation targetinfo; try { targetinfo = TargetInformation.GetInstance( X509ExtensionUtilities.FromExtensionValue(targetInfoExt)); } catch (Exception) { return false; } Targets[] targetss = targetinfo.GetTargetsObjects(); if (targetNames.Count > 0) { bool found = false; for (int i = 0; i < targetss.Length && !found; i++) { Target[] targets = targetss[i].GetTargets(); for (int j = 0; j < targets.Length; j++) { GeneralName targetName = targets[j].TargetName; if (targetName != null && targetNames.Contains(targetName)) { found = true; break; } } } if (!found) { return false; } } if (targetGroups.Count > 0) { bool found = false; for (int i = 0; i < targetss.Length && !found; i++) { Target[] targets = targetss[i].GetTargets(); for (int j = 0; j < targets.Length; j++) { GeneralName targetGroup = targets[j].TargetGroup; if (targetGroup != null && targetGroups.Contains(targetGroup)) { found = true; break; } } } if (!found) { return false; } } } } return true; } public object Clone() { return new X509AttrCertStoreSelector(this); } /// <summary>The attribute certificate which must be matched.</summary> /// <remarks>If <c>null</c> is given, any will do.</remarks> public IX509AttributeCertificate AttributeCert { get { return attributeCert; } set { this.attributeCert = value; } } [Obsolete("Use AttributeCertificateValid instead")] public DateTimeObject AttribueCertificateValid { get { return attributeCertificateValid; } set { this.attributeCertificateValid = value; } } /// <summary>The criteria for validity</summary> /// <remarks>If <c>null</c> is given any will do.</remarks> public DateTimeObject AttributeCertificateValid { get { return attributeCertificateValid; } set { this.attributeCertificateValid = value; } } /// <summary>The holder.</summary> /// <remarks>If <c>null</c> is given any will do.</remarks> public AttributeCertificateHolder Holder { get { return holder; } set { this.holder = value; } } /// <summary>The issuer.</summary> /// <remarks>If <c>null</c> is given any will do.</remarks> public AttributeCertificateIssuer Issuer { get { return issuer; } set { this.issuer = value; } } /// <summary>The serial number.</summary> /// <remarks>If <c>null</c> is given any will do.</remarks> public IBigInteger SerialNumber { get { return serialNumber; } set { this.serialNumber = value; } } /** * Adds a target name criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target names. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * </p> * * @param name The name as a GeneralName (not <code>null</code>) */ public void AddTargetName( GeneralName name) { targetNames.Add(name); } /** * Adds a target name criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target names. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * </p> * * @param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName * @throws IOException if a parsing error occurs. */ public void AddTargetName( byte[] name) { AddTargetName(GeneralName.GetInstance(Asn1Object.FromByteArray(name))); } /** * Adds a collection with target names criteria. If <code>null</code> is * given any will do. * <p> * The collection consists of either GeneralName objects or byte[] arrays representing * DER encoded GeneralName structures. * </p> * * @param names A collection of target names. * @throws IOException if a parsing error occurs. * @see #AddTargetName(byte[]) * @see #AddTargetName(GeneralName) */ public void SetTargetNames( IEnumerable names) { targetNames = ExtractGeneralNames(names); } /** * Gets the target names. The collection consists of <code>List</code>s * made up of an <code>Integer</code> in the first entry and a DER encoded * byte array or a <code>String</code> in the second entry. * <p>The returned collection is immutable.</p> * * @return The collection of target names * @see #setTargetNames(Collection) */ public IEnumerable GetTargetNames() { return new EnumerableProxy(targetNames); } /** * Adds a target group criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target groups. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * </p> * * @param group The group as GeneralName form (not <code>null</code>) */ public void AddTargetGroup( GeneralName group) { targetGroups.Add(group); } /** * Adds a target group criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target groups. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * </p> * * @param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName * @throws IOException if a parsing error occurs. */ public void AddTargetGroup( byte[] name) { AddTargetGroup(GeneralName.GetInstance(Asn1Object.FromByteArray(name))); } /** * Adds a collection with target groups criteria. If <code>null</code> is * given any will do. * <p> * The collection consists of <code>GeneralName</code> objects or <code>byte[]</code> * representing DER encoded GeneralNames. * </p> * * @param names A collection of target groups. * @throws IOException if a parsing error occurs. * @see #AddTargetGroup(byte[]) * @see #AddTargetGroup(GeneralName) */ public void SetTargetGroups( IEnumerable names) { targetGroups = ExtractGeneralNames(names); } /** * Gets the target groups. The collection consists of <code>List</code>s * made up of an <code>Integer</code> in the first entry and a DER encoded * byte array or a <code>String</code> in the second entry. * <p>The returned collection is immutable.</p> * * @return The collection of target groups. * @see #setTargetGroups(Collection) */ public IEnumerable GetTargetGroups() { return new EnumerableProxy(targetGroups); } private ISet ExtractGeneralNames( IEnumerable names) { ISet result = new HashSet(); if (names != null) { foreach (object o in names) { if (o is GeneralName) { result.Add(o); } else { result.Add(GeneralName.GetInstance(Asn1Object.FromByteArray((byte[]) o))); } } } return 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.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs.Asn1; using System.Security.Cryptography.X509Certificates; using Internal.Cryptography; namespace System.Security.Cryptography.Pkcs { internal partial class CmsSignature { static partial void PrepareRegistrationRsa(Dictionary<string, CmsSignature> lookup) { lookup.Add(Oids.Rsa, new RSAPkcs1CmsSignature()); lookup.Add(Oids.RsaPss, new RSAPssCmsSignature()); } private abstract class RSACmsSignature : CmsSignature { internal override bool VerifySignature( #if netcoreapp ReadOnlySpan<byte> valueHash, ReadOnlyMemory<byte> signature, #else byte[] valueHash, byte[] signature, #endif string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, ReadOnlyMemory<byte>? signatureParameters, X509Certificate2 certificate) { RSASignaturePadding padding = GetSignaturePadding( signatureParameters, digestAlgorithmOid, digestAlgorithmName, valueHash.Length); RSA publicKey = certificate.GetRSAPublicKey(); if (publicKey == null) { return false; } return publicKey.VerifyHash( valueHash, #if netcoreapp signature.Span, #else signature, #endif digestAlgorithmName, padding); } protected abstract RSASignaturePadding GetSignaturePadding( ReadOnlyMemory<byte>? signatureParameters, string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, int digestValueLength); } private sealed class RSAPkcs1CmsSignature : RSACmsSignature { protected override RSASignaturePadding GetSignaturePadding( ReadOnlyMemory<byte>? signatureParameters, string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, int digestValueLength) { if (signatureParameters == null) { return RSASignaturePadding.Pkcs1; } Span<byte> expectedParameters = stackalloc byte[2]; expectedParameters[0] = 0x05; expectedParameters[1] = 0x00; if (expectedParameters.SequenceEqual(signatureParameters.Value.Span)) { return RSASignaturePadding.Pkcs1; } throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters); } protected override bool Sign( #if netcoreapp ReadOnlySpan<byte> dataHash, #else byte[] dataHash, #endif HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, bool silent, out Oid signatureAlgorithm, out byte[] signatureValue) { // If there's no private key, fall back to the public key for a "no private key" exception. RSA privateKey = PkcsPal.Instance.GetPrivateKeyForSigning<RSA>(certificate, silent) ?? certificate.GetRSAPublicKey(); if (privateKey == null) { signatureAlgorithm = null; signatureValue = null; return false; } signatureAlgorithm = new Oid(Oids.Rsa, Oids.Rsa); #if netcoreapp byte[] signature = new byte[privateKey.KeySize / 8]; bool signed = privateKey.TrySignHash( dataHash, signature, hashAlgorithmName, RSASignaturePadding.Pkcs1, out int bytesWritten); if (signed && signature.Length == bytesWritten) { signatureValue = signature; return true; } #endif signatureValue = privateKey.SignHash( #if netcoreapp dataHash.ToArray(), #else dataHash, #endif hashAlgorithmName, RSASignaturePadding.Pkcs1); return true; } } private class RSAPssCmsSignature : RSACmsSignature { protected override RSASignaturePadding GetSignaturePadding( ReadOnlyMemory<byte>? signatureParameters, string digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, int digestValueLength) { if (signatureParameters == null) { throw new CryptographicException(SR.Cryptography_Pkcs_PssParametersMissing); } PssParamsAsn pssParams = AsnSerializer.Deserialize<PssParamsAsn>(signatureParameters.Value, AsnEncodingRules.DER); if (pssParams.HashAlgorithm.Algorithm.Value != digestAlgorithmOid) { throw new CryptographicException( SR.Format( SR.Cryptography_Pkcs_PssParametersHashMismatch, pssParams.HashAlgorithm.Algorithm.Value, digestAlgorithmOid)); } if (pssParams.TrailerField != 1) { throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters); } if (pssParams.SaltLength != digestValueLength) { throw new CryptographicException( SR.Format( SR.Cryptography_Pkcs_PssParametersSaltMismatch, pssParams.SaltLength, digestAlgorithmName.Name)); } if (pssParams.MaskGenAlgorithm.Algorithm.Value != Oids.Mgf1) { throw new CryptographicException( SR.Cryptography_Pkcs_PssParametersMgfNotSupported, pssParams.MaskGenAlgorithm.Algorithm.Value); } if (pssParams.MaskGenAlgorithm.Parameters == null) { throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters); } AlgorithmIdentifierAsn mgfParams = AsnSerializer.Deserialize<AlgorithmIdentifierAsn>( pssParams.MaskGenAlgorithm.Parameters.Value, AsnEncodingRules.DER); if (mgfParams.Algorithm.Value != digestAlgorithmOid) { throw new CryptographicException( SR.Format( SR.Cryptography_Pkcs_PssParametersMgfHashMismatch, mgfParams.Algorithm.Value, digestAlgorithmOid)); } // When RSASignaturePadding supports custom salt sizes this return will look different. return RSASignaturePadding.Pss; } protected override bool Sign( #if netcoreapp ReadOnlySpan<byte> dataHash, #else byte[] dataHash, #endif HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, bool silent, out Oid signatureAlgorithm, out byte[] signatureValue) { Debug.Fail("RSA-PSS requires building parameters, which has no API."); throw new CryptographicException(); } } } }
// Copyright 2017 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 Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks.Geocoding; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Windows.UI.Popups; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using ArcGISRuntime.Samples.Shared.Managers; namespace ArcGISRuntime.WinUI.Samples.FindPlace { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Find place", category: "Search", description: "Find places of interest near a location or within a specific area.", instructions: "Choose a type of place in the first field and an area to search within in the second field. Click the Search button to show the results of the query on the map. Click on a result pin to show its name and address. If you pan away from the result area, a \"Redo search in this area\" button will appear. Click it to query again for the currently viewed area on the map.", tags: new[] { "POI", "businesses", "geocode", "locations", "locator", "places of interest", "point of interest", "search", "suggestions" })] [ArcGISRuntime.Samples.Shared.Attributes.EmbeddedResource(@"PictureMarkerSymbols\pin_star_blue.png")] public partial class FindPlace { // The LocatorTask provides geocoding services private LocatorTask _geocoder; // Service Uri to be provided to the LocatorTask (geocoder) private Uri _serviceUri = new Uri("https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer"); public FindPlace() { InitializeComponent(); // Setup the control references and execute initialization Initialize(); } private async void Initialize() { if (await ApiKeyManager.CheckKeyValidity() != ApiKeyStatus.Valid) { await new MessageDialog2("Please use the settings dialog to configure an API Key.", "Error").ShowAsync(); return; } // Add event handler for when this sample is unloaded. Unloaded += SampleUnloaded; // Create new Map with basemap Map myMap = new Map(BasemapStyle.ArcGISStreets); // Subscribe to location changed event so that map can zoom to location MyMapView.LocationDisplay.LocationChanged += LocationDisplay_LocationChanged; // Enable location display MyMapView.LocationDisplay.IsEnabled = true; // Enable tap-for-info pattern on results MyMapView.GeoViewTapped += MyMapView_GeoViewTapped; // Assign the map to the MapView MyMapView.Map = myMap; // Initialize the LocatorTask with the provided service Uri _geocoder = await LocatorTask.CreateAsync(_serviceUri); // Enable all controls now that the locator task is ready SearchEntry.IsEnabled = true; LocationEntry.IsEnabled = true; SearchButton.IsEnabled = true; SearchViewButton.IsEnabled = true; } private void LocationDisplay_LocationChanged(object sender, Esri.ArcGISRuntime.Location.Location e) { // Return if position is null; event is raised with null location after if (e.Position == null) { return; } // Unsubscribe from further events; only want to zoom to location once ((LocationDisplay)sender).LocationChanged -= LocationDisplay_LocationChanged; // Need to use the dispatcher to interact with UI elements because this function is called from a background thread DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () => { MyMapView.SetViewpoint(new Viewpoint(e.Position, 100000)); }); } /// <summary> /// Gets the map point corresponding to the text in the location textbox. /// If the text is 'Current Location', the returned map point will be the device's location. /// </summary> /// <param name="locationText"></param> /// <returns></returns> private async Task<MapPoint> GetSearchMapPoint(string locationText) { // Get the map point for the search text if (locationText != "Current Location") { // Geocode the location IReadOnlyList<GeocodeResult> locations = await _geocoder.GeocodeAsync(locationText); // return if there are no results if (locations.Count < 1) { return null; } // Get the first result GeocodeResult result = locations.First(); // Return the map point return result.DisplayLocation; } else { // Get the current device location return MyMapView.LocationDisplay.Location?.Position; } } /// <summary> /// Runs a search and populates the map with results based on the provided information /// </summary> /// <param name="enteredText">Results to search for</param> /// <param name="locationText">Location around which to find results</param> /// <param name="restrictToExtent">If true, limits results to only those that are within the current extent</param> private async void UpdateSearch(string enteredText, string locationText, bool restrictToExtent = false) { // Clear any existing markers MyMapView.GraphicsOverlays.Clear(); // Return gracefully if the textbox is empty or the geocoder isn't ready if (String.IsNullOrWhiteSpace(enteredText) || _geocoder == null) { return; } // Create the geocode parameters GeocodeParameters parameters = new GeocodeParameters(); // Get the MapPoint for the current search location MapPoint searchLocation = await GetSearchMapPoint(locationText); // Update the geocode parameters if the map point is not null if (searchLocation != null) { parameters.PreferredSearchLocation = searchLocation; } // Update the search area if desired if (restrictToExtent) { // Get the current map extent Geometry extent = MyMapView.VisibleArea; // Update the search parameters parameters.SearchArea = extent; } // Show the progress bar ProgressBar.Visibility = Visibility.Visible; // Get the location information IReadOnlyList<GeocodeResult> locations = await _geocoder.GeocodeAsync(enteredText, parameters); // Stop gracefully and show a message if the geocoder does not return a result if (locations.Count < 1) { ProgressBar.Visibility = Visibility.Collapsed; // 1. Hide the progress bar ShowStatusMessage("No results found"); // 2. Show a message return; // 3. Stop } // Create the GraphicsOverlay so that results can be drawn on the map GraphicsOverlay resultOverlay = new GraphicsOverlay(); // Add each address to the map foreach (GeocodeResult location in locations) { // Get the Graphic to display Graphic point = await GraphicForPoint(location.DisplayLocation); // Add the specific result data to the point point.Attributes["Match_Title"] = location.Label; // Get the address for the point IReadOnlyList<GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(location.DisplayLocation); // Add the first suitable address if possible if (addresses.Any()) { point.Attributes["Match_Address"] = addresses[0].Label; } // Add the Graphic to the GraphicsOverlay resultOverlay.Graphics.Add(point); } // Hide the progress bar ProgressBar.Visibility = Visibility.Collapsed; // Add the GraphicsOverlay to the MapView MyMapView.GraphicsOverlays.Add(resultOverlay); // Update the map viewpoint await MyMapView.SetViewpointGeometryAsync(resultOverlay.Extent, 50); } /// <summary> /// Creates and returns a Graphic associated with the given MapPoint /// </summary> private async Task<Graphic> GraphicForPoint(MapPoint point) { // Get current assembly that contains the image Assembly currentAssembly = GetType().GetTypeInfo().Assembly; // Get image as a stream from the resources // Picture is defined as EmbeddedResource and DoNotCopy Stream resourceStream = currentAssembly.GetManifestResourceStream( "ArcGISRuntime.WinUI.Viewer.Resources.PictureMarkerSymbols.pin_star_blue.png"); // Create new symbol using asynchronous factory method from stream PictureMarkerSymbol pinSymbol = await PictureMarkerSymbol.CreateAsync(resourceStream); pinSymbol.Width = 60; pinSymbol.Height = 60; // The image is a pin; offset the image so that the pinpoint // is on the point rather than the image's true center pinSymbol.LeaderOffsetX = 30; pinSymbol.OffsetY = 14; return new Graphic(point, pinSymbol); } /// <summary> /// Shows a callout for any tapped graphics /// </summary> private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { // Search for the graphics underneath the user's tap IReadOnlyList<IdentifyGraphicsOverlayResult> results = await MyMapView.IdentifyGraphicsOverlaysAsync(e.Position, 12, false); // Clear callouts and return if there was no result if (results.Count < 1 || results.First().Graphics.Count < 1) { MyMapView.DismissCallout(); return; } // Get the first graphic from the first result Graphic matchingGraphic = results.First().Graphics.First(); // Get the title; manually added to the point's attributes in UpdateSearch string title = matchingGraphic.Attributes["Match_Title"] as String; // Get the address; manually added to the point's attributes in UpdateSearch string address = matchingGraphic.Attributes["Match_Address"] as String; // Define the callout CalloutDefinition calloutBody = new CalloutDefinition(title, address); // Show the callout on the map at the tapped location MyMapView.ShowCalloutAt(e.Location, calloutBody); } /// <summary> /// Returns a list of suggestions based on the input search text and limited by the specified parameters /// </summary> /// <param name="searchText">Text to get suggestions for</param> /// <param name="location">Location around which to look for suggestions</param> /// <param name="poiOnly">If true, restricts suggestions to only Points of Interest (e.g. businesses, parks), /// rather than all matching results</param> /// <returns>List of suggestions as strings</returns> private async Task<List<string>> GetSuggestResults(string searchText, string location = "", bool poiOnly = false) { // Quit if string is null, empty, or whitespace if (String.IsNullOrWhiteSpace(searchText)) { return new List<string>(); } // Quit if the geocoder isn't ready if (_geocoder == null) { return new List<string>(); } // Create geocode parameters SuggestParameters parameters = new SuggestParameters(); // Restrict suggestions to points of interest if desired if (poiOnly) { parameters.Categories.Add("POI"); } // Set the location for the suggest parameters if (!String.IsNullOrWhiteSpace(location)) { // Get the MapPoint for the current search location MapPoint searchLocation = await GetSearchMapPoint(location); // Update the geocode parameters if the map point is not null if (searchLocation != null) { parameters.PreferredSearchLocation = searchLocation; } } // Get the updated results from the query so far IReadOnlyList<SuggestResult> results = await _geocoder.SuggestAsync(searchText, parameters); // Return the list return results.Select(result => result.Label).ToList(); } /// <summary> /// Method abstracts the platform-specific message box functionality to maximize re-use of common code /// </summary> /// <param name="message">Text of the message to show.</param> private async void ShowStatusMessage(string message) { // Display the message to the user var dialog = new MessageDialog2(message); await dialog.ShowAsync(); } /// <summary> /// Method used to keep the suggestions up-to-date for the search box /// </summary> private async void MySearchBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { // Dismiss callout, if any UserInteracted(); // Get the current text string searchText = SearchEntry.Text; // Get the current search location string locationText = LocationEntry.Text; // Convert the list into a usable format for the suggest box List<string> results = await GetSuggestResults(searchText, locationText, true); // Quit if there are no results if (!results.Any()) { return; } // Update the list of options SearchEntry.ItemsSource = results; } /// <summary> /// Method used to keep the suggestions up-to-date for the location box /// </summary> private async void MyLocationBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { // Dismiss callout, if any UserInteracted(); // Get the current text string searchText = LocationEntry.Text; // Get the results List<string> results = await GetSuggestResults(searchText); // Quit if there are no results if (!results.Any()) { return; } // Add a 'current location' option to the list results.Insert(0, "Current Location"); // Update the list of options LocationEntry.ItemsSource = results; } /// <summary> /// Method called to start a search that is restricted to results within the current extent /// </summary> private void SearchViewButton_Click(object sender, RoutedEventArgs e) { // Dismiss callout, if any UserInteracted(); // Get the search text string searchText = SearchEntry.Text; // Get the location text string locationText = LocationEntry.Text; // Run the search UpdateSearch(searchText, locationText, true); } /// <summary> /// Method called to start an unrestricted search /// </summary> private void SearchButton_Click(object sender, RoutedEventArgs e) { // Dismiss callout, if any UserInteracted(); // Get the search text string searchText = SearchEntry.Text; // Get the location text string locationText = LocationEntry.Text; // Run the search UpdateSearch(searchText, locationText); } /// <summary> /// Method to handle hiding the callout, should be called by all UI event handlers /// </summary> private void UserInteracted() { // Hide the callout MyMapView.DismissCallout(); } private void SampleUnloaded(object sender, RoutedEventArgs e) { // Stop the location data source. MyMapView.LocationDisplay?.DataSource?.StopAsync(); } } }
// 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.Linq; using System.Diagnostics; using System.Diagnostics.Tracing; // We wish to test both Microsoft.Diagnostics.Tracing (Nuget) // and System.Diagnostics.Tracing (Framewwork), we use this Ifdef make each kind namespace SdtEventSources { /// <summary> /// A sample Event source. The Guid and Name attributes are "idempotent", i.e. they /// don't change the default computed by EventSource; they're specified here just to /// increase the code coverage. /// </summary> [EventSource(Guid = "69e2aa3e-083b-5014-cad4-3e511a0b94cf", Name = "EventSourceTest")] public sealed class EventSourceTest : EventSource { public EventSourceTest(bool useSelfDescribingEvents = false) : base(true) { } protected override void OnEventCommand(EventCommandEventArgs command) { Debug.WriteLine(String.Format("EventSourceTest: Got Command {0}", command.Command)); Debug.WriteLine(" Args: " + string.Join(", ", command.Arguments.Select((pair) => string.Format("{0} -> {1}", pair.Key, pair.Value)))); } [Event(1, Keywords = Keywords.HasNoArgs, Level = EventLevel.Informational)] public void Event0() { WriteEvent(1); } [Event(2, Keywords = Keywords.HasIntArgs, Level = EventLevel.Informational)] public void EventI(int arg1) { WriteEvent(2, arg1); } [Event(3, Keywords = Keywords.HasIntArgs, Level = EventLevel.Informational)] public void EventII(int arg1, int arg2) { WriteEvent(3, arg1, arg2); } [Event(4, Keywords = Keywords.HasIntArgs, Level = EventLevel.Informational)] public void EventIII(int arg1, int arg2, int arg3 = 12) { WriteEvent(4, arg1, arg2, arg3); } [Event(5, Keywords = Keywords.HasLongArgs, Level = EventLevel.Informational)] public void EventL(long arg1) { WriteEvent(5, arg1); } [Event(6, Keywords = Keywords.HasLongArgs, Level = EventLevel.Informational)] public void EventLL(long arg1, long arg2) { WriteEvent(6, arg1, arg2); } [Event(7, Keywords = Keywords.HasLongArgs, Level = EventLevel.Informational)] public void EventLLL(long arg1, long arg2, long arg3) { WriteEvent(7, arg1, arg2, arg3); } [Event(8, Keywords = Keywords.HasStringArgs, Level = EventLevel.Informational)] public void EventS(string arg1) { WriteEvent(8, arg1); } [Event(9, Keywords = Keywords.HasStringArgs, Level = EventLevel.Informational)] public void EventSS(string arg1, string arg2) { WriteEvent(9, arg1, arg2); } [Event(10, Keywords = Keywords.HasStringArgs, Level = EventLevel.Informational)] public void EventSSS(string arg1, string arg2, string arg3) { WriteEvent(10, arg1, arg2, arg3); } [Event(11, Keywords = Keywords.HasStringArgs | Keywords.HasIntArgs, Level = EventLevel.Informational)] public void EventSI(string arg1, int arg2) { WriteEvent(11, arg1, arg2); } [Event(12, Keywords = Keywords.HasStringArgs | Keywords.HasLongArgs, Level = EventLevel.Informational)] public void EventSL(string arg1, long arg2) { WriteEvent(12, arg1, arg2); } [Event(13, Keywords = Keywords.HasStringArgs | Keywords.HasIntArgs, Level = EventLevel.Informational)] public void EventSII(string arg1, int arg2, int arg3) { WriteEvent(13, arg1, arg2, arg3); } [Event(14, Keywords = Keywords.HasStringArgs, Level = EventLevel.Informational)] public void Message(string arg1) { WriteEvent(14, arg1); } [Event(15, Keywords = Keywords.HasNoArgs, Level = EventLevel.Informational, Task = Tasks.WorkItem)] public void StartTrackingActivity() { WriteEvent(15); } // Make sure this is before any #if so it gets a deterministic ID public void EventNoAttributes(string s) { WriteEvent(16, s); } [Event(17, Keywords = Keywords.Transfer | Keywords.HasStringArgs, Opcode = EventOpcode.Send, Task = Tasks.WorkItem)] unsafe public void LogTaskScheduled(Guid RelatedActivityId, string message) { unsafe { if (message == null) message = ""; fixed (char* string1Bytes = message) { EventSource.EventData* descrs = stackalloc EventSource.EventData[1]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((message.Length + 1) * 2); WriteEventWithRelatedActivityIdCore(17, &RelatedActivityId, 1, descrs); } } } [Event(18, Keywords = Keywords.HasStringArgs | Keywords.HasIntArgs, Level = EventLevel.Informational)] public void SlowerHelper(int arg1, string arg2) { if (IsEnabled()) WriteEvent(18, arg1, arg2); } [Event(19, Keywords = Keywords.HasEnumArgs, Level = EventLevel.Informational)] public void EventEnum(MyColor x) { WriteEvent(19, (int)x); } [Event(20, Keywords = Keywords.HasEnumArgs, Level = EventLevel.Informational)] public void EventEnum1(MyColor x) { WriteEvent(20, x); } [Event(21, Keywords = Keywords.HasEnumArgs, Level = EventLevel.Informational)] public void EventFlags(MyFlags x) { WriteEvent(21, (int)x); } [Event(22, Keywords = Keywords.HasEnumArgs, Level = EventLevel.Informational)] public void EventFlags1(MyFlags x) { WriteEvent(22, x); } [Event(23, Keywords = Keywords.Transfer | Keywords.HasStringArgs, Opcode = EventOpcode.Send, Task = Tasks.WorkItemBad)] public void LogTaskScheduledBad(Guid RelatedActivityId, string message) { unsafe { if (message == null) message = ""; fixed (char* string1Bytes = message) { EventSource.EventData* descrs = stackalloc EventSource.EventData[1]; descrs[0].DataPointer = (IntPtr)string1Bytes; descrs[0].Size = ((message.Length + 1) * 2); WriteEventWithRelatedActivityIdCore(23, &RelatedActivityId, 1, descrs); } } } // v4.5 does not support DateTime (until v4.5.1) [Event(24, Keywords = Keywords.HasDateTimeArgs, Message = "DateTime passed in: <{0}>", Opcode = Opcodes.Opcode1, Task = Tasks.WorkDateTime, Level = EventLevel.Informational)] public void EventDateTime(DateTime dt) { WriteEvent(24, dt); } [Event(25, Keywords = Keywords.HasNoArgs, Level = EventLevel.Informational)] public void EventWithManyTypeArgs(string msg, long l, uint ui, UInt64 ui64, byte b, sbyte sb, short sh, ushort ush, float f, double d, Guid guid) { if (IsEnabled(EventLevel.Informational, Keywords.HasNoArgs)) // 4.5 EventSource does not support "Char" type WriteEvent(25, msg, l, ui, ui64, b, sb, sh, ush, f, d, guid); } [Event(26)] public void EventWith7Strings(string s0, string s1, string s2, string s3, string s4, string s5, string s6) { WriteEvent(26, s0, s1, s2, s3, s4, s5, s6); } [Event(27)] public void EventWith9Strings(string s0, string s1, string s2, string s3, string s4, string s5, string s6, string s7, string s8) { WriteEvent(27, s0, s1, s2, s3, s4, s5, s6, s7, s8); } [Event(28, Keywords = Keywords.Transfer | Keywords.HasNoArgs)] public void LogTransferNoOpcode(Guid RelatedActivityId) { unsafe { WriteEventWithRelatedActivityIdCore(28, &RelatedActivityId, 0, null); } } [Event(29, Keywords = Keywords.Transfer | Keywords.HasNoArgs, Level = EventLevel.Informational, Opcode = EventOpcode.Send, Task = Tasks.WorkManyArgs)] public void EventWithXferManyTypeArgs(Guid RelatedActivityId, long l, uint ui, UInt64 ui64, char ch, byte b, sbyte sb, short sh, ushort ush, float f, double d, Guid guid) { if (IsEnabled(EventLevel.Informational, Keywords.HasNoArgs)) { unsafe { EventSource.EventData* descrs = stackalloc EventSource.EventData[11]; descrs[0].DataPointer = (IntPtr)(&l); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&ui); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)(&ui64); descrs[2].Size = 8; descrs[3].DataPointer = (IntPtr)(&ch); descrs[3].Size = 2; descrs[4].DataPointer = (IntPtr)(&b); descrs[4].Size = 1; descrs[5].DataPointer = (IntPtr)(&sb); descrs[5].Size = 1; descrs[6].DataPointer = (IntPtr)(&sh); descrs[6].Size = 2; descrs[7].DataPointer = (IntPtr)(&ush); descrs[7].Size = 2; descrs[8].DataPointer = (IntPtr)(&f); descrs[8].Size = 4; descrs[9].DataPointer = (IntPtr)(&d); descrs[9].Size = 8; descrs[10].DataPointer = (IntPtr)(&guid); descrs[10].Size = 16; WriteEventWithRelatedActivityIdCore(29, &RelatedActivityId, 11, descrs); } } } [Event(30)] // 4.5 EventSource does not support IntPtr args public void EventWithWeirdArgs(IntPtr iptr, bool b, MyLongEnum le /*, decimal dec*/) { WriteEvent(30, iptr, b, le /*, dec*/); } [Event(31, Keywords = Keywords.Transfer | Keywords.HasNoArgs, Level = EventLevel.Informational, Opcode = EventOpcode.Send, Task = Tasks.WorkWeirdArgs)] public void EventWithXferWeirdArgs(Guid RelatedActivityId, IntPtr iptr, bool b, MyLongEnum le /*, decimal dec */) { unsafe { EventSource.EventData* descrs = stackalloc EventSource.EventData[4]; descrs[0].DataPointer = (IntPtr)(&iptr); descrs[0].Size = IntPtr.Size; int boolval = b ? 1 : 0; descrs[1].DataPointer = (IntPtr)(&boolval); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)(&le); descrs[2].Size = 8; // descrs[3].DataPointer = (IntPtr)(&dec); // descrs[3].Size = 16; WriteEventWithRelatedActivityIdCore(31, &RelatedActivityId, 3 /*4*/, descrs); } } [NonEvent] public void NonEvent() { EventNoAttributes(DateTime.Now.ToString()); } // The above produces different results on 4.5 vs. 4.5.1. Skip the test for those EventSources [Event(32, Level = EventLevel.Informational, Message = "msg={0}, n={1}!")] public void EventWithEscapingMessage(string msg, int n) { WriteEvent(32, msg, n); } // The above produces different results on 4.5 vs. 4.5.1. Skip the test for those EventSources [Event(33, Level = EventLevel.Informational, Message = "{{msg}}={0}! percentage={1}%")] public void EventWithMoreEscapingMessage(string msg, int percentage) { WriteEvent(33, msg, percentage); } [Event(36, Level = EventLevel.Informational, Message = "Int arg after byte ptr: {2}")] public unsafe void EventWithIncorrectNumberOfParameters(string message, string path = "", int line = 0) { string text = string.Concat("{", path, ":", line, "}", message); WriteEvent(36, text); } [Event(39, Level = EventLevel.Informational, Message = "int int string event")] public void EventWithIntIntString(int i1, int i2, string str) { WriteEvent(39, i1, i2, str); } [Event(40, Level = EventLevel.Informational, Message = "int long string")] public void EventWithIntLongString(int i1, long l1, string str) { WriteEvent(40, i1, l1, str); } [Event(41)] public void EventWithString(string str) { this.WriteEvent(41, str); } [Event(42)] public void EventWithIntAndString(int i, string str) { this.WriteEvent(42, i, str); } [Event(43)] public void EventWithLongAndString(long l, string str) { this.WriteEvent(43, l, str); } [Event(44)] public void EventWithStringAndInt(string str, int i) { this.WriteEvent(44, str, i); } [Event(45)] public void EventWithStringAndIntAndInt(string str, int i, int j) { this.WriteEvent(45, str, i, j); } [Event(46)] public void EventWithStringAndLong(string str, long l) { this.WriteEvent(46, str, l); } [Event(47)] public void EventWithStringAndString(string str, string str2) { this.WriteEvent(47, str, str2); } [Event(48)] public void EventWithStringAndStringAndString(string str, string str2, string str3) { this.WriteEvent(48, str, str2, str3); } [Event(49)] public void EventVarArgsWithString(int i, int j, int k, string str) { this.WriteEvent(49, i, j, k, str); } /// <summary> /// This event, combined with the one after it, test whether an Event named "Foo" and one named /// "FooStart" can coexist. /// </summary> [Event(50)] public void EventNamedEvent() { this.WriteEvent(50); } /// <summary> /// This event, combined with the one before it, test whether an Event named "Foo" and one named /// "FooStart" can coexist. /// </summary> [Event(51)] public void EventNamedEventStart() { this.WriteEvent(51); } [Event(52)] public void EventWithByteArray(byte[] arr) { this.WriteEvent(52, arr); } #region Keywords / Tasks /Opcodes / Channels public class Keywords { public const EventKeywords HasNoArgs = (EventKeywords)0x0001; public const EventKeywords HasIntArgs = (EventKeywords)0x0002; public const EventKeywords HasLongArgs = (EventKeywords)0x0004; public const EventKeywords HasStringArgs = (EventKeywords)0x0008; public const EventKeywords HasDateTimeArgs = (EventKeywords)0x0010; public const EventKeywords HasEnumArgs = (EventKeywords)0x0020; public const EventKeywords Transfer = (EventKeywords)0x0040; } public class Tasks { public const EventTask WorkItem = (EventTask)1; public const EventTask WorkItemBad = (EventTask)2; public const EventTask WorkManyArgs = (EventTask)3; public const EventTask WorkWeirdArgs = (EventTask)4; public const EventTask WorkDateTime = (EventTask)5; } public class Opcodes { public const EventOpcode Opcode1 = (EventOpcode)11; public const EventOpcode Opcode2 = (EventOpcode)12; } #endregion } public enum MyColor { Red, Blue, Green, } public enum MyLongEnum : long { LongVal1 = (long)0x13 << 32, LongVal2 = (long)0x20 << 32, } [Flags] public enum MyFlags { Flag1 = 1, Flag2 = 2, Flag3 = 4, } }
// *********************************************************************** // Copyright (c) 2011-2021 Charlie Poole, Terje Sandstrom // // 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.Text.RegularExpressions; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using NUnit.VisualStudio.TestAdapter.NUnitEngine; using VSTestResult = Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult; namespace NUnit.VisualStudio.TestAdapter { public sealed class TestConverter : IDisposable, ITestConverter { private readonly ITestLogger _logger; private readonly Dictionary<string, TestCase> _vsTestCaseMap; private readonly string _sourceAssembly; private readonly NavigationDataProvider _navigationDataProvider; private bool CollectSourceInformation => adapterSettings.CollectSourceInformation; private readonly IAdapterSettings adapterSettings; private static readonly string NL = Environment.NewLine; private readonly IDiscoveryConverter discoveryConverter; public TestConverter(ITestLogger logger, string sourceAssembly, IAdapterSettings settings, IDiscoveryConverter discoveryConverter) { this.discoveryConverter = discoveryConverter; adapterSettings = settings; _logger = logger; _sourceAssembly = sourceAssembly; _vsTestCaseMap = new Dictionary<string, TestCase>(); TraitsCache = new Dictionary<string, TraitsFeature.CachedTestCaseInfo>(); if (CollectSourceInformation) { _navigationDataProvider = new NavigationDataProvider(sourceAssembly, logger); } } public void Dispose() { _navigationDataProvider?.Dispose(); } public IDictionary<string, TraitsFeature.CachedTestCaseInfo> TraitsCache { get; } #region Public Methods /// <summary> /// Converts an NUnit test into a TestCase for Visual Studio, /// using the best method available according to the exact /// type passed and caching results for efficiency. /// </summary> public TestCase ConvertTestCase(NUnitDiscoveryTestCase testNode) { // Return cached value if we have one string id = testNode.Id; if (_vsTestCaseMap.ContainsKey(id)) return _vsTestCaseMap[id]; // Convert to VS TestCase and cache the result var testCase = MakeTestCaseFromDiscoveryNode(testNode); _vsTestCaseMap.Add(id, testCase); return testCase; } public TestCase GetCachedTestCase(string id) { if (_vsTestCaseMap.ContainsKey(id)) return _vsTestCaseMap[id]; _logger.Debug("Test " + id + " not found in cache"); return null; } public TestConverterForXml.TestResultSet GetVsTestResults(INUnitTestEventTestCase resultNode, ICollection<INUnitTestEventTestOutput> outputNodes) { var results = new List<VSTestResult>(); var testCaseResult = GetBasicResult(resultNode, outputNodes); if (testCaseResult != null) { switch (testCaseResult.Outcome) { case TestOutcome.Failed: case TestOutcome.NotFound: { testCaseResult.ErrorMessage = resultNode.Failure?.Message; testCaseResult.ErrorStackTrace = resultNode.Failure?.Stacktrace ?? resultNode.StackTrace; break; } case TestOutcome.Skipped: case TestOutcome.None: testCaseResult.ErrorMessage = resultNode.ReasonMessage; testCaseResult.Messages.Add(new TestResultMessage(TestResultMessage.StandardOutCategory, resultNode.ReasonMessage)); break; default: { if (adapterSettings.ConsoleOut > 0 && !string.IsNullOrEmpty(resultNode.ReasonMessage)) testCaseResult.Messages.Add(new TestResultMessage(TestResultMessage.StandardOutCategory, resultNode.ReasonMessage)); break; } } results.Add(testCaseResult); } if (results.Count == 0) { var result = MakeTestResultFromLegacyXmlNode(resultNode, outputNodes); if (result != null) results.Add(result); } return new TestConverterForXml.TestResultSet { TestCaseResult = testCaseResult, TestResults = results, ConsoleOutput = resultNode.Output }; } #endregion #region Helper Methods /// <summary> /// Makes a TestCase from an NUnit test, adding /// navigation data if it can be found. /// </summary> private TestCase MakeTestCaseFromDiscoveryNode(NUnitDiscoveryTestCase testNode) { string fullyQualifiedName = testNode.FullName; if (adapterSettings.UseParentFQNForParametrizedTests) { var parent = testNode.Parent; if (parent != null && parent.IsParameterizedMethod) { var parameterizedTestFullName = parent.FullName; // VS expected FullyQualifiedName to be the actual class+type name,optionally with parameter types // in parenthesis, but they must fit the pattern of a value returned by object.GetType(). // It should _not_ include custom name or param values (just their types). // However, the "fullname" from NUnit's file generation is the custom name of the test, so // this code must convert from one to the other. // Reference: https://github.com/microsoft/vstest-docs/blob/master/RFCs/0017-Managed-TestCase-Properties.md // Using the nUnit-provided "fullname" will cause failures at test execution time due to // the FilterExpressionWrapper not being able to parse the test names passed-in as filters. // To resolve this issue, for parameterized tests (which are the only tests that allow custom names), // the parent node's "fullname" value is used instead. This is the name of the actual test method // and will allow the filtering to work as expected. // Note that this also means you can no longer select a single tests of these to run. // When you do that, all tests within the parent node will be executed if (!string.IsNullOrEmpty(parameterizedTestFullName)) { fullyQualifiedName = parameterizedTestFullName; } } } var testCase = new TestCase( fullyQualifiedName, new Uri(NUnitTestAdapter.ExecutorUri), _sourceAssembly) { DisplayName = CreateDisplayName(fullyQualifiedName, testNode.Name), CodeFilePath = null, LineNumber = 0 }; if (adapterSettings.UseNUnitIdforTestCaseId) { testCase.Id = EqtHash.GuidFromString(testNode.Id); } if (CollectSourceInformation && _navigationDataProvider != null) { if (!CheckCodeFilePathOverride()) { var navData = _navigationDataProvider.GetNavigationData(testNode.ClassName, testNode.MethodName); if (navData.IsValid) { testCase.CodeFilePath = navData.FilePath; testCase.LineNumber = navData.LineNumber; } } } else { _ = CheckCodeFilePathOverride(); } testCase.AddTraitsFromTestNode(testNode, TraitsCache, _logger, adapterSettings); testCase.SetPropertyValue(Seed.NUnitSeedProperty, testNode.Seed.ToString()); return testCase; bool CheckCodeFilePathOverride() { var codeFilePath = testNode.Properties.FirstOrDefault(p => p.Name == "_CodeFilePath"); if (codeFilePath == null) return false; testCase.CodeFilePath = codeFilePath.Value; var lineNumber = testNode.Properties.FirstOrDefault(p => p.Name == "_LineNumber"); testCase.LineNumber = lineNumber != null ? Convert.ToInt32(lineNumber.Value) : 1; return true; } } private string CreateDisplayName(string fullyQualifiedName, string testNodeName) { return adapterSettings.FreakMode ? "N:Name -> MS:DisplayName (default)" : adapterSettings.DisplayName switch { DisplayNameOptions.Name => testNodeName, DisplayNameOptions.FullName => fullyQualifiedName, DisplayNameOptions.FullNameSep => fullyQualifiedName.Replace('.', adapterSettings.FullnameSeparator), _ => throw new ArgumentOutOfRangeException(), }; } private VSTestResult MakeTestResultFromLegacyXmlNode(INUnitTestEventTestCase resultNode, IEnumerable<INUnitTestEventTestOutput> outputNodes) { var ourResult = GetBasicResult(resultNode, outputNodes); if (ourResult == null) return null; string message = resultNode.HasFailure ? resultNode.Failure.Message : resultNode.HasReason ? resultNode.ReasonMessage : null; // If we're running in the IDE, remove any caret line from the message // since it will be displayed using a variable font and won't make sense. if (!string.IsNullOrEmpty(message) && NUnitTestAdapter.IsRunningUnderIde) { string pattern = NL + " -*\\^" + NL; message = Regex.Replace(message, pattern, NL, RegexOptions.Multiline); } ourResult.ErrorMessage = message; ourResult.ErrorStackTrace = resultNode.Failure?.Stacktrace; return ourResult; } private VSTestResult GetBasicResult(INUnitTestEvent resultNode, IEnumerable<INUnitTestEventTestOutput> outputNodes) { var vsTest = GetCachedTestCase(resultNode.Id); if (vsTest == null) { var discoveredTest = discoveryConverter.AllTestCases.FirstOrDefault(o => o.Id == resultNode.Id); if (discoveredTest != null) { vsTest = ConvertTestCase(discoveredTest); } else { return null; } } var vsResult = new VSTestResult(vsTest) { DisplayName = vsTest.DisplayName, Outcome = GetTestOutcome(resultNode), Duration = resultNode.Duration }; var startTime = resultNode.StartTime(); if (startTime.Ok) vsResult.StartTime = startTime.Time; var endTime = resultNode.EndTime(); if (endTime.Ok) vsResult.EndTime = endTime.Time; // TODO: Remove this when NUnit provides a better duration if (vsResult.Duration == TimeSpan.Zero && (vsResult.Outcome == TestOutcome.Passed || vsResult.Outcome == TestOutcome.Failed)) vsResult.Duration = TimeSpan.FromTicks(1); vsResult.ComputerName = Environment.MachineName; vsResult.SetPropertyValue(Seed.NUnitSeedProperty, resultNode.Seed); if (adapterSettings.Verbosity >= 5) { vsResult.Messages.Add(new TestResultMessage(TestResultMessage.StandardOutCategory, $"seed: {resultNode.Seed}")); } FillResultFromOutputNodes(outputNodes, vsResult); // Add stdOut messages from TestFinished element to vstest result var output = resultNode.Output; if (!string.IsNullOrEmpty(output)) vsResult.Messages.Add(new TestResultMessage(TestResultMessage.StandardOutCategory, output)); var attachmentSet = ParseAttachments(resultNode); if (attachmentSet.Attachments.Count > 0) vsResult.Attachments.Add(attachmentSet); return vsResult; } private static void FillResultFromOutputNodes(IEnumerable<INUnitTestEventTestOutput> outputNodes, VSTestResult vsResult) { foreach (var output in outputNodes) { if (output.IsNullOrEmptyStream || output.IsProgressStream) // Don't add progress streams as output { continue; } // Add stdErr/Progress messages from TestOutputXml element to vstest result vsResult.Messages.Add(new TestResultMessage( output.IsErrorStream ? TestResultMessage.StandardErrorCategory : TestResultMessage.StandardOutCategory, output.Content)); } } /// <summary> /// Looks for attachments in a results node and if any attachments are found they /// are returned"/>. /// </summary> /// <param name="resultNode">xml node for test result.</param> /// <returns>attachments to be added to the test, it will be empty if no attachments are found.</returns> private AttachmentSet ParseAttachments(INUnitTestEvent resultNode) { const string fileUriScheme = "file://"; var attachmentSet = new AttachmentSet(new Uri(NUnitTestAdapter.ExecutorUri), "Attachments"); foreach (var attachment in resultNode.NUnitAttachments) { var description = attachment.Description; var path = attachment.FilePath; if (adapterSettings.EnsureAttachmentFileScheme) { if (!(string.IsNullOrEmpty(path) || path.StartsWith(fileUriScheme, StringComparison.OrdinalIgnoreCase))) { path = fileUriScheme + path; } } // For Linux paths if (!(string.IsNullOrEmpty(path) || path.StartsWith(fileUriScheme, StringComparison.OrdinalIgnoreCase)) && !path.Contains(':')) { path = fileUriScheme + path; } try { // We only support absolute paths since we dont lookup working directory here // any problem with path will throw an exception var fileUri = new Uri(path, UriKind.Absolute); attachmentSet.Attachments.Add(new UriDataAttachment(fileUri, description)); } catch (UriFormatException ex) { _logger.Warning($"Ignoring attachment with path '{path}' due to problem with path: {ex.Message}"); } catch (Exception ex) { _logger.Warning($"Ignoring attachment with path '{path}': {ex.Message}."); } } return attachmentSet; } // Public for testing public TestOutcome GetTestOutcome(INUnitTestEvent resultNode) { return resultNode.Result() switch { NUnitTestEvent.ResultType.Success => TestOutcome.Passed, NUnitTestEvent.ResultType.Failed => TestOutcome.Failed, NUnitTestEvent.ResultType.Skipped => (resultNode.IsIgnored ? TestOutcome.Skipped : TestOutcome.None), NUnitTestEvent.ResultType.Warning => adapterSettings.MapWarningTo, _ => TestOutcome.None }; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Xml; using System.Net; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.Versioning; namespace System.Xml.Resolvers { // // XmlPreloadedResolver is an XmlResolver that which can be pre-loaded with data. // By default it contains well-known DTDs for XHTML 1.0 and RSS 0.91. // Custom mappings of URIs to data can be added with the Add method. // public partial class XmlPreloadedResolver : XmlResolver { // // PreloadedData class // private abstract class PreloadedData { // Returns preloaded data as Stream; Stream must always be supported internal abstract Stream AsStream(); // Returns preloaded data as TextReader, or throws when not supported internal virtual TextReader AsTextReader() { throw new XmlException(SR.Xml_UnsupportedClass); } // Returns true for types that are supported for this preloaded data; Stream must always be supported internal virtual bool SupportsType(Type type) { if (type == null || type == typeof(Stream)) { return true; } return false; } }; // // XmlKnownDtdData class // private class XmlKnownDtdData : PreloadedData { internal string publicId; internal string systemId; private string _resourceName; internal XmlKnownDtdData(string publicId, string systemId, string resourceName) { this.publicId = publicId; this.systemId = systemId; _resourceName = resourceName; } internal override Stream AsStream() { Assembly asm = GetType().Assembly; return asm.GetManifestResourceStream(_resourceName); } } private class ByteArrayChunk : PreloadedData { private byte[] _array; private int _offset; private int _length; internal ByteArrayChunk(byte[] array) : this(array, 0, array.Length) { } internal ByteArrayChunk(byte[] array, int offset, int length) { _array = array; _offset = offset; _length = length; } internal override Stream AsStream() { return new MemoryStream(_array, _offset, _length); } } private class StringData : PreloadedData { private string _str; internal StringData(string str) { _str = str; } internal override Stream AsStream() { return new MemoryStream(Encoding.Unicode.GetBytes(_str)); } internal override TextReader AsTextReader() { return new StringReader(_str); } internal override bool SupportsType(Type type) { if (type == typeof(TextReader)) { return true; } return base.SupportsType(type); } } // // Fields // private XmlResolver _fallbackResolver; private Dictionary<Uri, PreloadedData> _mappings; private XmlKnownDtds _preloadedDtds; // // Static/constant fiels // private static XmlKnownDtdData[] s_xhtml10_Dtd = new XmlKnownDtdData[] { new XmlKnownDtdData( "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", "xhtml1-strict.dtd" ), new XmlKnownDtdData( "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", "xhtml1-transitional.dtd" ), new XmlKnownDtdData( "-//W3C//DTD XHTML 1.0 Frameset//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd", "xhtml1-frameset.dtd" ), new XmlKnownDtdData( "-//W3C//ENTITIES Latin 1 for XHTML//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent", "xhtml-lat1.ent" ), new XmlKnownDtdData( "-//W3C//ENTITIES Symbols for XHTML//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent", "xhtml-symbol.ent" ), new XmlKnownDtdData( "-//W3C//ENTITIES Special for XHTML//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent", "xhtml-special.ent" ), }; private static XmlKnownDtdData[] s_rss091_Dtd = new XmlKnownDtdData[] { new XmlKnownDtdData( "-//Netscape Communications//DTD RSS 0.91//EN", "http://my.netscape.com/publish/formats/rss-0.91.dtd", "rss-0.91.dtd" ), }; // // Constructors // public XmlPreloadedResolver() : this(null) { } public XmlPreloadedResolver(XmlKnownDtds preloadedDtds) : this(null, preloadedDtds, null) { } public XmlPreloadedResolver(XmlResolver fallbackResolver) : this(fallbackResolver, XmlKnownDtds.All, null) { } public XmlPreloadedResolver(XmlResolver fallbackResolver, XmlKnownDtds preloadedDtds) : this(fallbackResolver, preloadedDtds, null) { } public XmlPreloadedResolver(XmlResolver fallbackResolver, XmlKnownDtds preloadedDtds, IEqualityComparer<Uri> uriComparer) { _fallbackResolver = fallbackResolver; _mappings = new Dictionary<Uri, PreloadedData>(16, uriComparer); _preloadedDtds = preloadedDtds; // load known DTDs if (preloadedDtds != 0) { if ((preloadedDtds & XmlKnownDtds.Xhtml10) != 0) { AddKnownDtd(s_xhtml10_Dtd); } if ((preloadedDtds & XmlKnownDtds.Rss091) != 0) { AddKnownDtd(s_rss091_Dtd); } } } public override Uri ResolveUri(Uri baseUri, string relativeUri) { // 1) special-case well-known public IDs // 2) To make FxCop happy we need to use StartsWith() overload that takes StringComparison -> // .StartsWith(string) is equal to .StartsWith(string, StringComparison.CurrentCulture); if (relativeUri != null && relativeUri.StartsWith("-//", StringComparison.CurrentCulture)) { // 1) XHTML 1.0 public IDs // 2) To make FxCop happy we need to use StartsWith() overload that takes StringComparison -> // .StartsWith(string) is equal to .StartsWith(string, StringComparison.CurrentCulture); if ((_preloadedDtds & XmlKnownDtds.Xhtml10) != 0 && relativeUri.StartsWith("-//W3C//", StringComparison.CurrentCulture)) { for (int i = 0; i < s_xhtml10_Dtd.Length; i++) { if (relativeUri == s_xhtml10_Dtd[i].publicId) { return new Uri(relativeUri, UriKind.Relative); } } } // RSS 0.91 public IDs if ((_preloadedDtds & XmlKnownDtds.Rss091) != 0) { Debug.Assert(s_rss091_Dtd.Length == 1); if (relativeUri == s_rss091_Dtd[0].publicId) { return new Uri(relativeUri, UriKind.Relative); } } } return base.ResolveUri(baseUri, relativeUri); } public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { if (absoluteUri == null) { throw new ArgumentNullException(nameof(absoluteUri)); } PreloadedData data; if (!_mappings.TryGetValue(absoluteUri, out data)) { if (_fallbackResolver != null) { return _fallbackResolver.GetEntity(absoluteUri, role, ofObjectToReturn); } throw new XmlException(SR.Format(SR.Xml_CannotResolveUrl, absoluteUri.ToString())); } if (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream) || ofObjectToReturn == typeof(object)) { return data.AsStream(); } else if (ofObjectToReturn == typeof(TextReader)) { return data.AsTextReader(); } else { throw new XmlException(SR.Xml_UnsupportedClass); } } public override ICredentials Credentials { set { if (_fallbackResolver != null) { _fallbackResolver.Credentials = value; } } } public override bool SupportsType(Uri absoluteUri, Type type) { if (absoluteUri == null) { throw new ArgumentNullException(nameof(absoluteUri)); } PreloadedData data; if (!_mappings.TryGetValue(absoluteUri, out data)) { if (_fallbackResolver != null) { return _fallbackResolver.SupportsType(absoluteUri, type); } return base.SupportsType(absoluteUri, type); } return data.SupportsType(type); } public void Add(Uri uri, byte[] value) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Add(uri, new ByteArrayChunk(value, 0, value.Length)); } public void Add(Uri uri, byte[] value, int offset, int count) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (value.Length - offset < count) { throw new ArgumentOutOfRangeException(nameof(count)); } Add(uri, new ByteArrayChunk(value, offset, count)); } public void Add(Uri uri, Stream value) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value.CanSeek) { // stream of known length -> allocate the byte array and read all data into it int size = checked((int)value.Length); byte[] bytes = new byte[size]; value.Read(bytes, 0, size); Add(uri, new ByteArrayChunk(bytes)); } else { // stream of unknown length -> read into memory stream and then get internal the byte array MemoryStream ms = new MemoryStream(); byte[] buffer = new byte[4096]; int read; while ((read = value.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } int size = checked((int)ms.Position); byte[] bytes = new byte[size]; Array.Copy(ms.ToArray(), bytes, size); Add(uri, new ByteArrayChunk(bytes)); } } public void Add(Uri uri, string value) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Add(uri, new StringData(value)); } public IEnumerable<Uri> PreloadedUris { get { // read-only collection of keys return _mappings.Keys; } } public void Remove(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } _mappings.Remove(uri); } // // Private implementation methods // private void Add(Uri uri, PreloadedData data) { Debug.Assert(uri != null); // override if exists if (_mappings.ContainsKey(uri)) { _mappings[uri] = data; } else { _mappings.Add(uri, data); } } private void AddKnownDtd(XmlKnownDtdData[] dtdSet) { for (int i = 0; i < dtdSet.Length; i++) { XmlKnownDtdData dtdInfo = dtdSet[i]; _mappings.Add(new Uri(dtdInfo.publicId, UriKind.RelativeOrAbsolute), dtdInfo); _mappings.Add(new Uri(dtdInfo.systemId, UriKind.RelativeOrAbsolute), dtdInfo); } } } }
/// Credit BinaryX /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1945602 /// Updated by ddreaper - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect. using System; using UnityEngine.EventSystems; namespace UnityEngine.UI.Extensions { [RequireComponent(typeof(ScrollRect))] [AddComponentMenu("Layout/Extensions/Vertical Scroll Snap")] public class VerticalScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler { private Transform _screensContainer; private int _screens = 1; private bool _fastSwipeTimer = false; private int _fastSwipeCounter = 0; private int _fastSwipeTarget = 30; private System.Collections.Generic.List<Vector3> _positions; private ScrollRect _scroll_rect; private Vector3 _lerp_target; private bool _lerp; [Tooltip("The gameobject that contains toggles which suggest pagination. (optional)")] public GameObject Pagination; [Tooltip("Button to go to the next page. (optional)")] public GameObject NextButton; [Tooltip("Button to go to the previous page. (optional)")] public GameObject PrevButton; [Tooltip("Transition speed between pages. (optional)")] public float transitionSpeed = 7.5f; public Boolean UseFastSwipe = true; public int FastSwipeThreshold = 100; private bool _startDrag = true; private Vector3 _startPosition = new Vector3(); [Tooltip("The currently active page")] [SerializeField] private int _currentScreen; [Tooltip("The screen / page to start the control on")] public int StartingScreen = 1; [Tooltip("The distance between two pages, by default 3 times the width of the control")] public int PageStep = 0; public int CurrentPage { get { return _currentScreen; } } // Use this for initialization void Start() { _scroll_rect = gameObject.GetComponent<ScrollRect>(); if (_scroll_rect.horizontalScrollbar || _scroll_rect.verticalScrollbar) { Debug.LogWarning("Warning, using scrollbors with the Scroll Snap controls is not advised as it causes unpredictable results"); } _screensContainer = _scroll_rect.content; if (PageStep == 0) { PageStep = (int)_scroll_rect.GetComponent<RectTransform>().rect.height * 3; } DistributePages(); _lerp = false; _currentScreen = StartingScreen; _scroll_rect.verticalNormalizedPosition = (float)(_currentScreen - 1) / (float)(_screens - 1); ChangeBulletsInfo(_currentScreen); if (NextButton) NextButton.GetComponent<Button>().onClick.AddListener(() => { NextScreen(); }); if (PrevButton) PrevButton.GetComponent<Button>().onClick.AddListener(() => { PreviousScreen(); }); } void Update() { if (_lerp) { _screensContainer.localPosition = Vector3.Lerp(_screensContainer.localPosition, _lerp_target, transitionSpeed * Time.deltaTime); if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 0.005f) { _lerp = false; } //change the info bullets at the bottom of the screen. Just for visual effect if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 10f) { ChangeBulletsInfo(CurrentScreen()); } } if (_fastSwipeTimer) { _fastSwipeCounter++; } } private bool fastSwipe = false; //to determine if a fast swipe was performed //Function for switching screens with buttons public void NextScreen() { if (_currentScreen < _screens - 1) { _currentScreen++; _lerp = true; _lerp_target = _positions[_currentScreen]; ChangeBulletsInfo(_currentScreen); } } //Function for switching screens with buttons public void PreviousScreen() { if (_currentScreen > 0) { _currentScreen--; _lerp = true; _lerp_target = _positions[_currentScreen]; ChangeBulletsInfo(_currentScreen); } } //Function for switching to a specific screen public void GoToScreen(int screenIndex) { if (screenIndex <= _screens && screenIndex >= 0) { _lerp = true; _lerp_target = _positions[screenIndex]; ChangeBulletsInfo(screenIndex); } } //Because the CurrentScreen function is not so reliable, these are the functions used for swipes private void NextScreenCommand() { if (_currentScreen < _screens - 1) { _lerp = true; _lerp_target = _positions[_currentScreen + 1]; ChangeBulletsInfo(_currentScreen + 1); } } //Because the CurrentScreen function is not so reliable, these are the functions used for swipes private void PrevScreenCommand() { if (_currentScreen > 0) { _lerp = true; _lerp_target = _positions[_currentScreen - 1]; ChangeBulletsInfo(_currentScreen - 1); } } //find the closest registered point to the releasing point private Vector3 FindClosestFrom(Vector3 start, System.Collections.Generic.List<Vector3> positions) { Vector3 closest = Vector3.zero; float distance = Mathf.Infinity; foreach (Vector3 position in _positions) { if (Vector3.Distance(start, position) < distance) { distance = Vector3.Distance(start, position); closest = position; } } return closest; } //returns the current screen that the is seeing public int CurrentScreen() { var pos = FindClosestFrom(_screensContainer.localPosition, _positions); return _currentScreen = GetPageforPosition(pos); } //changes the bullets on the bottom of the page - pagination private void ChangeBulletsInfo(int currentScreen) { if (Pagination) for (int i = 0; i < Pagination.transform.childCount; i++) { Pagination.transform.GetChild(i).GetComponent<Toggle>().isOn = (currentScreen == i) ? true : false; } } //used for changing between screen resolutions public void DistributePages() { float _offset = 0; float _dimension = 0; Vector2 panelDimensions = gameObject.GetComponent<RectTransform>().sizeDelta; float currentYPosition = 0; for (int i = 0; i < _screensContainer.transform.childCount; i++) { RectTransform child = _screensContainer.transform.GetChild(i).gameObject.GetComponent<RectTransform>(); currentYPosition = _offset + i * PageStep; child.sizeDelta = new Vector2(panelDimensions.x, panelDimensions.y); child.anchoredPosition = new Vector2(0f - panelDimensions.x / 2, currentYPosition + panelDimensions.y / 2); } _dimension = currentYPosition + _offset * -1; _screensContainer.GetComponent<RectTransform>().offsetMax = new Vector2(0f,_dimension); _screens = _screensContainer.childCount; _positions = new System.Collections.Generic.List<Vector3>(); if (_screens > 0) { for (int i = 0; i < _screens; ++i) { _scroll_rect.verticalNormalizedPosition = (float)i / (float)(_screens - 1); _positions.Add(_screensContainer.localPosition); } } } int GetPageforPosition(Vector3 pos) { for (int i = 0; i < _positions.Count; i++) { if (_positions[i] == pos) { return i; } } return 0; } void OnValidate() { var childCount = gameObject.GetComponent<ScrollRect>().content.childCount; if (StartingScreen > childCount) { StartingScreen = childCount; } if (StartingScreen < 1) { StartingScreen = 1; } } /// <summary> /// Add a new child to this Scroll Snap and recalculate it's children /// </summary> /// <param name="GO">GameObject to add to the ScrollSnap</param> public void AddChild(GameObject GO) { _scroll_rect.verticalNormalizedPosition = 0; GO.transform.SetParent(_screensContainer); DistributePages(); _scroll_rect.verticalNormalizedPosition = (float)(_currentScreen) / (_screens - 1); } /// <summary> /// Remove a new child to this Scroll Snap and recalculate it's children /// *Note, this is an index address (0-x) /// </summary> /// <param name="index"></param> /// <param name="ChildRemoved"></param> public void RemoveChild(int index, out GameObject ChildRemoved) { ChildRemoved = null; if (index < 0 || index > _screensContainer.childCount) { return; } _scroll_rect.verticalNormalizedPosition = 0; var children = _screensContainer.transform; int i = 0; foreach (Transform child in children) { if (i == index) { child.SetParent(null); ChildRemoved = child.gameObject; break; } i++; } DistributePages(); if (_currentScreen > _screens - 1) { _currentScreen = _screens - 1; } _scroll_rect.verticalNormalizedPosition = (float)(_currentScreen) / (_screens - 1); } #region Interfaces public void OnBeginDrag(PointerEventData eventData) { _startPosition = _screensContainer.localPosition; _fastSwipeCounter = 0; _fastSwipeTimer = true; _currentScreen = CurrentScreen(); } public void OnEndDrag(PointerEventData eventData) { _startDrag = true; if (_scroll_rect.vertical) { if (UseFastSwipe) { fastSwipe = false; _fastSwipeTimer = false; if (_fastSwipeCounter <= _fastSwipeTarget) { if (Math.Abs(_startPosition.y - _screensContainer.localPosition.y) > FastSwipeThreshold) { fastSwipe = true; } } if (fastSwipe) { if (_startPosition.y - _screensContainer.localPosition.y > 0) { NextScreenCommand(); } else { PrevScreenCommand(); } } else { _lerp = true; _lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions); _currentScreen = GetPageforPosition(_lerp_target); } } else { _lerp = true; _lerp_target = FindClosestFrom(_screensContainer.localPosition, _positions); _currentScreen = GetPageforPosition(_lerp_target); } } } public void OnDrag(PointerEventData eventData) { _lerp = false; if (_startDrag) { OnBeginDrag(eventData); _startDrag = false; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Intrinsics; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE4.1 hardware instructions via intrinsics /// </summary> [CLSCompliant(false)] public abstract class Sse41 : Ssse3 { internal Sse41() { } public new static bool IsSupported { get => IsSupported; } /// <summary> /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8) /// PBLENDW xmm, xmm/m128 imm8 /// </summary> public static Vector128<short> Blend(Vector128<short> left, Vector128<short> right, byte control) => Blend(left, right, control); /// <summary> /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8) /// PBLENDW xmm, xmm/m128 imm8 /// </summary> public static Vector128<ushort> Blend(Vector128<ushort> left, Vector128<ushort> right, byte control) => Blend(left, right, control); /// <summary> /// __m128 _mm_blend_ps (__m128 a, __m128 b, const int imm8) /// BLENDPS xmm, xmm/m128, imm8 /// </summary> public static Vector128<float> Blend(Vector128<float> left, Vector128<float> right, byte control) => Blend(left, right, control); /// <summary> /// __m128d _mm_blend_pd (__m128d a, __m128d b, const int imm8) /// BLENDPD xmm, xmm/m128, imm8 /// </summary> public static Vector128<double> Blend(Vector128<double> left, Vector128<double> right, byte control) => Blend(left, right, control); /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// PBLENDVB xmm, xmm/m128, xmm /// </summary> public static Vector128<sbyte> BlendVariable(Vector128<sbyte> left, Vector128<sbyte> right, Vector128<sbyte> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// PBLENDVB xmm, xmm/m128, xmm /// </summary> public static Vector128<byte> BlendVariable(Vector128<byte> left, Vector128<byte> right, Vector128<byte> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// PBLENDVB xmm, xmm/m128, xmm /// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements. /// </summary> public static Vector128<short> BlendVariable(Vector128<short> left, Vector128<short> right, Vector128<short> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// PBLENDVB xmm, xmm/m128, xmm /// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements. /// </summary> public static Vector128<ushort> BlendVariable(Vector128<ushort> left, Vector128<ushort> right, Vector128<ushort> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// PBLENDVB xmm, xmm/m128, xmm /// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements. /// </summary> public static Vector128<int> BlendVariable(Vector128<int> left, Vector128<int> right, Vector128<int> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// PBLENDVB xmm, xmm/m128, xmm /// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements. /// </summary> public static Vector128<uint> BlendVariable(Vector128<uint> left, Vector128<uint> right, Vector128<uint> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// PBLENDVB xmm, xmm/m128, xmm /// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements. /// </summary> public static Vector128<long> BlendVariable(Vector128<long> left, Vector128<long> right, Vector128<long> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// PBLENDVB xmm, xmm/m128, xmm /// This intrinsic generates PBLENDVB that needs a BYTE mask-vector, so users should correctly set each mask byte for the selected elements. /// </summary> public static Vector128<ulong> BlendVariable(Vector128<ulong> left, Vector128<ulong> right, Vector128<ulong> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128 _mm_blendv_ps (__m128 a, __m128 b, __m128 mask) /// BLENDVPS xmm, xmm/m128, xmm0 /// </summary> public static Vector128<float> BlendVariable(Vector128<float> left, Vector128<float> right, Vector128<float> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128d _mm_blendv_pd (__m128d a, __m128d b, __m128d mask) /// BLENDVPD xmm, xmm/m128, xmm0 /// </summary> public static Vector128<double> BlendVariable(Vector128<double> left, Vector128<double> right, Vector128<double> mask) => BlendVariable(left, right, mask); /// <summary> /// __m128 _mm_ceil_ps (__m128 a) /// ROUNDPS xmm, xmm/m128, imm8(10) /// </summary> public static Vector128<float> Ceiling(Vector128<float> value) => Ceiling(value); /// <summary> /// __m128d _mm_ceil_pd (__m128d a) /// ROUNDPD xmm, xmm/m128, imm8(10) /// </summary> public static Vector128<double> Ceiling(Vector128<double> value) => Ceiling(value); /// <summary> /// __m128d _mm_ceil_sd (__m128d a) /// ROUNDSD xmm, xmm/m128, imm8(10) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> CeilingScalar(Vector128<double> value) => CeilingScalar(value); /// <summary> /// __m128 _mm_ceil_ss (__m128 a) /// ROUNDSD xmm, xmm/m128, imm8(10) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<float> CeilingScalar(Vector128<float> value) => CeilingScalar(value); /// <summary> /// __m128d _mm_ceil_sd (__m128d a, __m128d b) /// ROUNDSD xmm, xmm/m128, imm8(10) /// </summary> public static Vector128<double> CeilingScalar(Vector128<double> upper, Vector128<double> value) => CeilingScalar(upper, value); /// <summary> /// __m128 _mm_ceil_ss (__m128 a, __m128 b) /// ROUNDSS xmm, xmm/m128, imm8(10) /// </summary> public static Vector128<float> CeilingScalar(Vector128<float> upper, Vector128<float> value) => CeilingScalar(upper, value); /// <summary> /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b) /// PCMPEQQ xmm, xmm/m128 /// </summary> public static Vector128<long> CompareEqual(Vector128<long> left, Vector128<long> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b) /// PCMPEQQ xmm, xmm/m128 /// </summary> public static Vector128<ulong> CompareEqual(Vector128<ulong> left, Vector128<ulong> right) => CompareEqual(left, right); /// <summary> /// __m128i _mm_cvtepi8_epi16 (__m128i a) /// PMOVSXBW xmm, xmm/m64 /// </summary> public static Vector128<short> ConvertToVector128Int16(Vector128<sbyte> value) => ConvertToVector128Int16(value); /// <summary> /// __m128i _mm_cvtepu8_epi16 (__m128i a) /// PMOVZXBW xmm, xmm/m64 /// </summary> public static Vector128<short> ConvertToVector128Int16(Vector128<byte> value) => ConvertToVector128Int16(value); /// <summary> /// __m128i _mm_cvtepi8_epi32 (__m128i a) /// PMOVSXBD xmm, xmm/m32 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector128<sbyte> value) => ConvertToVector128Int32(value); /// <summary> /// __m128i _mm_cvtepu8_epi32 (__m128i a) /// PMOVZXBD xmm, xmm/m32 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector128<byte> value) => ConvertToVector128Int32(value); /// <summary> /// __m128i _mm_cvtepi16_epi32 (__m128i a) /// PMOVSXWD xmm, xmm/m64 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector128<short> value) => ConvertToVector128Int32(value); /// <summary> /// __m128i _mm_cvtepu16_epi32 (__m128i a) /// PMOVZXWD xmm, xmm/m64 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector128<ushort> value) => ConvertToVector128Int32(value); /// <summary> /// __m128i _mm_cvtepi8_epi64 (__m128i a) /// PMOVSXBQ xmm, xmm/m16 /// </summary> public static Vector128<long> ConvertToVector128Int64(Vector128<sbyte> value) => ConvertToVector128Int64(value); /// <summary> /// __m128i _mm_cvtepu8_epi64 (__m128i a) /// PMOVZXBQ xmm, xmm/m16 /// </summary> public static Vector128<long> ConvertToVector128Int64(Vector128<byte> value) => ConvertToVector128Int64(value); /// <summary> /// __m128i _mm_cvtepi16_epi64 (__m128i a) /// PMOVSXWQ xmm, xmm/m32 /// </summary> public static Vector128<long> ConvertToVector128Int64(Vector128<short> value) => ConvertToVector128Int64(value); /// <summary> /// __m128i _mm_cvtepu16_epi64 (__m128i a) /// PMOVZXWQ xmm, xmm/m32 /// </summary> public static Vector128<long> ConvertToVector128Int64(Vector128<ushort> value) => ConvertToVector128Int64(value); /// <summary> /// __m128i _mm_cvtepi32_epi64 (__m128i a) /// PMOVSXDQ xmm, xmm/m64 /// </summary> public static Vector128<long> ConvertToVector128Int64(Vector128<int> value) => ConvertToVector128Int64(value); /// <summary> /// __m128i _mm_cvtepu32_epi64 (__m128i a) /// PMOVZXDQ xmm, xmm/m64 /// </summary> public static Vector128<long> ConvertToVector128Int64(Vector128<uint> value) => ConvertToVector128Int64(value); /// <summary> /// __m128 _mm_dp_ps (__m128 a, __m128 b, const int imm8) /// DPPS xmm, xmm/m128, imm8 /// </summary> public static Vector128<float> DotProduct(Vector128<float> left, Vector128<float> right, byte control) => DotProduct(left, right, control); /// <summary> /// __m128d _mm_dp_pd (__m128d a, __m128d b, const int imm8) /// DPPD xmm, xmm/m128, imm8 /// </summary> public static Vector128<double> DotProduct(Vector128<double> left, Vector128<double> right, byte control) => DotProduct(left, right, control); /// <summary> /// int _mm_extract_epi8 (__m128i a, const int imm8) /// PEXTRB reg/m8, xmm, imm8 /// </summary> public static byte Extract(Vector128<byte> value, byte index) => Extract(value, index); /// <summary> /// int _mm_extract_epi32 (__m128i a, const int imm8) /// PEXTRD reg/m32, xmm, imm8 /// </summary> public static int Extract(Vector128<int> value, byte index) => Extract(value, index); /// <summary> /// int _mm_extract_epi32 (__m128i a, const int imm8) /// PEXTRD reg/m32, xmm, imm8 /// </summary> public static uint Extract(Vector128<uint> value, byte index) => Extract(value, index); /// <summary> /// __int64 _mm_extract_epi64 (__m128i a, const int imm8) /// PEXTRQ reg/m64, xmm, imm8 /// </summary> public static long Extract(Vector128<long> value, byte index) => Extract(value, index); /// <summary> /// __int64 _mm_extract_epi64 (__m128i a, const int imm8) /// PEXTRQ reg/m64, xmm, imm8 /// </summary> public static ulong Extract(Vector128<ulong> value, byte index) => Extract(value, index); /// <summary> /// int _mm_extract_ps (__m128 a, const int imm8) /// EXTRACTPS xmm, xmm/m32, imm8 /// </summary> public static float Extract(Vector128<float> value, byte index) => Extract(value, index); /// <summary> /// __m128 _mm_floor_ps (__m128 a) /// ROUNDPS xmm, xmm/m128, imm8(9) /// </summary> public static Vector128<float> Floor(Vector128<float> value) => Floor(value); /// <summary> /// __m128d _mm_floor_pd (__m128d a) /// ROUNDPD xmm, xmm/m128, imm8(9) /// </summary> public static Vector128<double> Floor(Vector128<double> value) => Floor(value); /// <summary> /// __m128d _mm_floor_sd (__m128d a) /// ROUNDSD xmm, xmm/m128, imm8(9) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> FloorScalar(Vector128<double> value) => FloorScalar(value); /// <summary> /// __m128 _mm_floor_ss (__m128 a) /// ROUNDSS xmm, xmm/m128, imm8(9) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<float> FloorScalar(Vector128<float> value) => FloorScalar(value); /// <summary> /// __m128d _mm_floor_sd (__m128d a, __m128d b) /// ROUNDSD xmm, xmm/m128, imm8(9) /// </summary> public static Vector128<double> FloorScalar(Vector128<double> upper, Vector128<double> value) => FloorScalar(upper, value); /// <summary> /// __m128 _mm_floor_ss (__m128 a, __m128 b) /// ROUNDSS xmm, xmm/m128, imm8(9) /// </summary> public static Vector128<float> FloorScalar(Vector128<float> upper, Vector128<float> value) => FloorScalar(upper, value); /// <summary> /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8) /// PINSRB xmm, reg/m8, imm8 /// </summary> public static Vector128<sbyte> Insert(Vector128<sbyte> value, sbyte data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8) /// PINSRB xmm, reg/m8, imm8 /// </summary> public static Vector128<byte> Insert(Vector128<byte> value, byte data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) /// PINSRD xmm, reg/m32, imm8 /// </summary> public static Vector128<int> Insert(Vector128<int> value, int data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) /// PINSRD xmm, reg/m32, imm8 /// </summary> public static Vector128<uint> Insert(Vector128<uint> value, uint data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8) /// PINSRQ xmm, reg/m64, imm8 /// </summary> public static Vector128<long> Insert(Vector128<long> value, long data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8) /// PINSRQ xmm, reg/m64, imm8 /// </summary> public static Vector128<ulong> Insert(Vector128<ulong> value, ulong data, byte index) => Insert(value, data, index); /// <summary> /// __m128 _mm_insert_ps (__m128 a, __m128 b, const int imm8) /// INSERTPS xmm, xmm/m32, imm8 /// </summary> public static Vector128<float> Insert(Vector128<float> value, Vector128<float> data, byte index) => Insert(value, data, index); /// <summary> /// __m128i _mm_max_epi8 (__m128i a, __m128i b) /// PMAXSB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) => Max(left, right); /// <summary> /// __m128i _mm_max_epu16 (__m128i a, __m128i b) /// PMAXUW xmm, xmm/m128 /// </summary> public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) => Max(left, right); /// <summary> /// __m128i _mm_max_epi32 (__m128i a, __m128i b) /// PMAXSD xmm, xmm/m128 /// </summary> public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) => Max(left, right); /// <summary> /// __m128i _mm_max_epu32 (__m128i a, __m128i b) /// PMAXUD xmm, xmm/m128 /// </summary> public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) => Max(left, right); /// <summary> /// __m128i _mm_min_epi8 (__m128i a, __m128i b) /// PMINSB xmm, xmm/m128 /// </summary> public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) => Min(left, right); /// <summary> /// __m128i _mm_min_epu16 (__m128i a, __m128i b) /// PMINUW xmm, xmm/m128 /// </summary> public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) => Min(left, right); /// <summary> /// __m128i _mm_min_epi32 (__m128i a, __m128i b) /// PMINSD xmm, xmm/m128 /// </summary> public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) => Min(left, right); /// <summary> /// __m128i _mm_min_epu32 (__m128i a, __m128i b) /// PMINUD xmm, xmm/m128 /// </summary> public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) => Min(left, right); /// <summary> /// __m128i _mm_minpos_epu16 (__m128i a) /// PHMINPOSUW xmm, xmm/m128 /// </summary> public static Vector128<ushort> MinHorizontal(Vector128<ushort> value) => MinHorizontal(value); /// <summary> /// __m128i _mm_mpsadbw_epu8 (__m128i a, __m128i b, const int imm8) /// MPSADBW xmm, xmm/m128, imm8 /// </summary> public static Vector128<ushort> MultipleSumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right, byte mask) => MultipleSumAbsoluteDifferences(left, right, mask); /// <summary> /// __m128i _mm_mul_epi32 (__m128i a, __m128i b) /// PMULDQ xmm, xmm/m128 /// </summary> public static Vector128<long> Multiply(Vector128<int> left, Vector128<int> right) => Multiply(left, right); /// <summary> /// __m128i _mm_mullo_epi32 (__m128i a, __m128i b) /// PMULLD xmm, xmm/m128 /// </summary> public static Vector128<int> MultiplyLow(Vector128<int> left, Vector128<int> right) => MultiplyLow(left, right); /// <summary> /// __m128i _mm_mullo_epi32 (__m128i a, __m128i b) /// PMULLD xmm, xmm/m128 /// </summary> public static Vector128<uint> MultiplyLow(Vector128<uint> left, Vector128<uint> right) => MultiplyLow(left, right); /// <summary> /// __m128i _mm_packus_epi32 (__m128i a, __m128i b) /// PACKUSDW xmm, xmm/m128 /// </summary> public static Vector128<ushort> PackUnsignedSaturate(Vector128<int> left, Vector128<int> right) => PackUnsignedSaturate(left, right); /// <summary> /// __m128 _mm_round_ps (__m128 a, int rounding) /// ROUNDPS xmm, xmm/m128, imm8(8) /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC /// </summary> public static Vector128<float> RoundToNearestInteger(Vector128<float> value) => RoundToNearestInteger(value); /// <summary> /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(9) /// </summary> public static Vector128<float> RoundToNegativeInfinity(Vector128<float> value) => RoundToNegativeInfinity(value); /// <summary> /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(10) /// </summary> public static Vector128<float> RoundToPositiveInfinity(Vector128<float> value) => RoundToPositiveInfinity(value); /// <summary> /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPS xmm, xmm/m128, imm8(11) /// </summary> public static Vector128<float> RoundToZero(Vector128<float> value) => RoundToZero(value); /// <summary> /// _MM_FROUND_CUR_DIRECTION; ROUNDPS xmm, xmm/m128, imm8(4) /// </summary> public static Vector128<float> RoundCurrentDirection(Vector128<float> value) => RoundCurrentDirection(value); /// <summary> /// __m128d _mm_round_pd (__m128d a, int rounding) /// ROUNDPD xmm, xmm/m128, imm8(8) /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC /// </summary> public static Vector128<double> RoundToNearestInteger(Vector128<double> value) => RoundToNearestInteger(value); /// <summary> /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(9) /// </summary> public static Vector128<double> RoundToNegativeInfinity(Vector128<double> value) => RoundToNegativeInfinity(value); /// <summary> /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(10) /// </summary> public static Vector128<double> RoundToPositiveInfinity(Vector128<double> value) => RoundToPositiveInfinity(value); /// <summary> /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC; ROUNDPD xmm, xmm/m128, imm8(11) /// </summary> public static Vector128<double> RoundToZero(Vector128<double> value) => RoundToZero(value); /// <summary> /// _MM_FROUND_CUR_DIRECTION; ROUNDPD xmm, xmm/m128, imm8(4) /// </summary> public static Vector128<double> RoundCurrentDirection(Vector128<double> value) => RoundCurrentDirection(value); /// <summary> /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_CUR_DIRECTION) /// ROUNDSD xmm, xmm/m128, imm8(4) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> RoundCurrentDirectionScalar(Vector128<double> value) => RoundCurrentDirectionScalar(value); /// <summary> /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) /// ROUNDSD xmm, xmm/m128, imm8(8) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> RoundToNearestIntegerScalar(Vector128<double> value) => RoundToNearestIntegerScalar(value); /// <summary> /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) /// ROUNDSD xmm, xmm/m128, imm8(9) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> RoundToNegativeInfinityScalar(Vector128<double> value) => RoundToNegativeInfinityScalar(value); /// <summary> /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) /// ROUNDSD xmm, xmm/m128, imm8(10) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> RoundToPositiveInfinityScalar(Vector128<double> value) => RoundToPositiveInfinityScalar(value); /// <summary> /// __m128d _mm_round_sd (__m128d a, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) /// ROUNDSD xmm, xmm/m128, imm8(11) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<double> RoundToZeroScalar(Vector128<double> value) => RoundToZeroScalar(value); /// <summary> /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_CUR_DIRECTION) /// ROUNDSD xmm, xmm/m128, imm8(4) /// </summary> public static Vector128<double> RoundCurrentDirectionScalar(Vector128<double> upper, Vector128<double> value) => RoundCurrentDirectionScalar(upper, value); /// <summary> /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) /// ROUNDSD xmm, xmm/m128, imm8(8) /// </summary> public static Vector128<double> RoundToNearestIntegerScalar(Vector128<double> upper, Vector128<double> value) => RoundToNearestIntegerScalar(upper, value); /// <summary> /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) /// ROUNDSD xmm, xmm/m128, imm8(9) /// </summary> public static Vector128<double> RoundToNegativeInfinityScalar(Vector128<double> upper, Vector128<double> value) => RoundToNegativeInfinityScalar(upper, value); /// <summary> /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) /// ROUNDSD xmm, xmm/m128, imm8(10) /// </summary> public static Vector128<double> RoundToPositiveInfinityScalar(Vector128<double> upper, Vector128<double> value) => RoundToPositiveInfinityScalar(upper, value); /// <summary> /// __m128d _mm_round_sd (__m128d a, __m128d b, _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) /// ROUNDSD xmm, xmm/m128, imm8(11) /// </summary> public static Vector128<double> RoundToZeroScalar(Vector128<double> upper, Vector128<double> value) => RoundToZeroScalar(upper, value); /// <summary> /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_CUR_DIRECTION) /// ROUNDSS xmm, xmm/m128, imm8(4) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<float> RoundCurrentDirectionScalar(Vector128<float> value) => RoundCurrentDirectionScalar(value); /// <summary> /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) /// ROUNDSS xmm, xmm/m128, imm8(8) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<float> RoundToNearestIntegerScalar(Vector128<float> value) => RoundToNearestIntegerScalar(value); /// <summary> /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) /// ROUNDSS xmm, xmm/m128, imm8(9) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<float> RoundToNegativeInfinityScalar(Vector128<float> value) => RoundToNegativeInfinityScalar(value); /// <summary> /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) /// ROUNDSS xmm, xmm/m128, imm8(10) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<float> RoundToPositiveInfinityScalar(Vector128<float> value) => RoundToPositiveInfinityScalar(value); /// <summary> /// __m128 _mm_round_ss (__m128 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) /// ROUNDSS xmm, xmm/m128, imm8(11) /// The above native signature does not exist. We provide this additional overload for the recommended use case of this intrinsic. /// </summary> public static Vector128<float> RoundToZeroScalar(Vector128<float> value) => RoundToZeroScalar(value); /// <summary> /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_CUR_DIRECTION) /// ROUNDSS xmm, xmm/m128, imm8(4) /// </summary> public static Vector128<float> RoundCurrentDirectionScalar(Vector128<float> upper, Vector128<float> value) => RoundCurrentDirectionScalar(upper, value); /// <summary> /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) /// ROUNDSS xmm, xmm/m128, imm8(8) /// </summary> public static Vector128<float> RoundToNearestIntegerScalar(Vector128<float> upper, Vector128<float> value) => RoundToNearestIntegerScalar(upper, value); /// <summary> /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) /// ROUNDSS xmm, xmm/m128, imm8(9) /// </summary> public static Vector128<float> RoundToNegativeInfinityScalar(Vector128<float> upper, Vector128<float> value) => RoundToNegativeInfinityScalar(upper, value); /// <summary> /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) /// ROUNDSS xmm, xmm/m128, imm8(10) /// </summary> public static Vector128<float> RoundToPositiveInfinityScalar(Vector128<float> upper, Vector128<float> value) => RoundToPositiveInfinityScalar(upper, value); /// <summary> /// __m128 _mm_round_ss (__m128 a, __m128 b, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) /// ROUNDSS xmm, xmm/m128, imm8(11) /// </summary> public static Vector128<float> RoundToZeroScalar(Vector128<float> upper, Vector128<float> value) => RoundToZeroScalar(upper, value); /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// MOVNTDQA xmm, m128 /// </summary> public static unsafe Vector128<sbyte> LoadAlignedVector128NonTemporal(sbyte* address) => LoadAlignedVector128NonTemporal(address); /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// MOVNTDQA xmm, m128 /// </summary> public static unsafe Vector128<byte> LoadAlignedVector128NonTemporal(byte* address) => LoadAlignedVector128NonTemporal(address); /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// MOVNTDQA xmm, m128 /// </summary> public static unsafe Vector128<short> LoadAlignedVector128NonTemporal(short* address) => LoadAlignedVector128NonTemporal(address); /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// MOVNTDQA xmm, m128 /// </summary> public static unsafe Vector128<ushort> LoadAlignedVector128NonTemporal(ushort* address) => LoadAlignedVector128NonTemporal(address); /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// MOVNTDQA xmm, m128 /// </summary> public static unsafe Vector128<int> LoadAlignedVector128NonTemporal(int* address) => LoadAlignedVector128NonTemporal(address); /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// MOVNTDQA xmm, m128 /// </summary> public static unsafe Vector128<uint> LoadAlignedVector128NonTemporal(uint* address) => LoadAlignedVector128NonTemporal(address); /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// MOVNTDQA xmm, m128 /// </summary> public static unsafe Vector128<long> LoadAlignedVector128NonTemporal(long* address) => LoadAlignedVector128NonTemporal(address); /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// MOVNTDQA xmm, m128 /// </summary> public static unsafe Vector128<ulong> LoadAlignedVector128NonTemporal(ulong* address) => LoadAlignedVector128NonTemporal(address); /// <summary> /// int _mm_test_all_ones (__m128i a) /// HELPER /// </summary> public static bool TestAllOnes(Vector128<sbyte> value) => TestAllOnes(value); public static bool TestAllOnes(Vector128<byte> value) => TestAllOnes(value); public static bool TestAllOnes(Vector128<short> value) => TestAllOnes(value); public static bool TestAllOnes(Vector128<ushort> value) => TestAllOnes(value); public static bool TestAllOnes(Vector128<int> value) => TestAllOnes(value); public static bool TestAllOnes(Vector128<uint> value) => TestAllOnes(value); public static bool TestAllOnes(Vector128<long> value) => TestAllOnes(value); public static bool TestAllOnes(Vector128<ulong> value) => TestAllOnes(value); /// <summary> /// int _mm_test_all_zeros (__m128i a, __m128i mask) /// PTEST xmm, xmm/m128 /// </summary> public static bool TestAllZeros(Vector128<sbyte> left, Vector128<sbyte> right) => TestAllZeros(left, right); public static bool TestAllZeros(Vector128<byte> left, Vector128<byte> right) => TestAllZeros(left, right); public static bool TestAllZeros(Vector128<short> left, Vector128<short> right) => TestAllZeros(left, right); public static bool TestAllZeros(Vector128<ushort> left, Vector128<ushort> right) => TestAllZeros(left, right); public static bool TestAllZeros(Vector128<int> left, Vector128<int> right) => TestAllZeros(left, right); public static bool TestAllZeros(Vector128<uint> left, Vector128<uint> right) => TestAllZeros(left, right); public static bool TestAllZeros(Vector128<long> left, Vector128<long> right) => TestAllZeros(left, right); public static bool TestAllZeros(Vector128<ulong> left, Vector128<ulong> right) => TestAllZeros(left, right); /// <summary> /// int _mm_testc_si128 (__m128i a, __m128i b) /// PTEST xmm, xmm/m128 /// </summary> public static bool TestC(Vector128<sbyte> left, Vector128<sbyte> right) => TestC(left, right); public static bool TestC(Vector128<byte> left, Vector128<byte> right) => TestC(left, right); public static bool TestC(Vector128<short> left, Vector128<short> right) => TestC(left, right); public static bool TestC(Vector128<ushort> left, Vector128<ushort> right) => TestC(left, right); public static bool TestC(Vector128<int> left, Vector128<int> right) => TestC(left, right); public static bool TestC(Vector128<uint> left, Vector128<uint> right) => TestC(left, right); public static bool TestC(Vector128<long> left, Vector128<long> right) => TestC(left, right); public static bool TestC(Vector128<ulong> left, Vector128<ulong> right) => TestC(left, right); /// <summary> /// int _mm_test_mix_ones_zeros (__m128i a, __m128i mask) /// PTEST xmm, xmm/m128 /// </summary> public static bool TestMixOnesZeros(Vector128<sbyte> left, Vector128<sbyte> right) => TestMixOnesZeros(left, right); public static bool TestMixOnesZeros(Vector128<byte> left, Vector128<byte> right) => TestMixOnesZeros(left, right); public static bool TestMixOnesZeros(Vector128<short> left, Vector128<short> right) => TestMixOnesZeros(left, right); public static bool TestMixOnesZeros(Vector128<ushort> left, Vector128<ushort> right) => TestMixOnesZeros(left, right); public static bool TestMixOnesZeros(Vector128<int> left, Vector128<int> right) => TestMixOnesZeros(left, right); public static bool TestMixOnesZeros(Vector128<uint> left, Vector128<uint> right) => TestMixOnesZeros(left, right); public static bool TestMixOnesZeros(Vector128<long> left, Vector128<long> right) => TestMixOnesZeros(left, right); public static bool TestMixOnesZeros(Vector128<ulong> left, Vector128<ulong> right) => TestMixOnesZeros(left, right); /// <summary> /// int _mm_testnzc_si128 (__m128i a, __m128i b) /// PTEST xmm, xmm/m128 /// </summary> public static bool TestNotZAndNotC(Vector128<sbyte> left, Vector128<sbyte> right) => TestNotZAndNotC(left, right); public static bool TestNotZAndNotC(Vector128<byte> left, Vector128<byte> right) => TestNotZAndNotC(left, right); public static bool TestNotZAndNotC(Vector128<short> left, Vector128<short> right) => TestNotZAndNotC(left, right); public static bool TestNotZAndNotC(Vector128<ushort> left, Vector128<ushort> right) => TestNotZAndNotC(left, right); public static bool TestNotZAndNotC(Vector128<int> left, Vector128<int> right) => TestNotZAndNotC(left, right); public static bool TestNotZAndNotC(Vector128<uint> left, Vector128<uint> right) => TestNotZAndNotC(left, right); public static bool TestNotZAndNotC(Vector128<long> left, Vector128<long> right) => TestNotZAndNotC(left, right); public static bool TestNotZAndNotC(Vector128<ulong> left, Vector128<ulong> right) => TestNotZAndNotC(left, right); /// <summary> /// int _mm_testz_si128 (__m128i a, __m128i b) /// PTEST xmm, xmm/m128 /// </summary> public static bool TestZ(Vector128<sbyte> left, Vector128<sbyte> right) => TestZ(left, right); public static bool TestZ(Vector128<byte> left, Vector128<byte> right) => TestZ(left, right); public static bool TestZ(Vector128<short> left, Vector128<short> right) => TestZ(left, right); public static bool TestZ(Vector128<ushort> left, Vector128<ushort> right) => TestZ(left, right); public static bool TestZ(Vector128<int> left, Vector128<int> right) => TestZ(left, right); public static bool TestZ(Vector128<uint> left, Vector128<uint> right) => TestZ(left, right); public static bool TestZ(Vector128<long> left, Vector128<long> right) => TestZ(left, right); public static bool TestZ(Vector128<ulong> left, Vector128<ulong> right) => TestZ(left, right); } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext #if !NETCF using System; #if !NETSTANDARD1_3 using System.Runtime.Remoting.Messaging; #endif using System.Security; #if NETSTANDARD1_3 using System.Threading; #endif namespace log4net.Util { /// <summary> /// Implementation of Properties collection for the <see cref="log4net.LogicalThreadContext"/> /// </summary> /// <remarks> /// <para> /// Class implements a collection of properties that is specific to each thread. /// The class is not synchronized as each thread has its own <see cref="PropertiesDictionary"/>. /// </para> /// <para> /// This class stores its properties in a slot on the <see cref="CallContext"/> named /// <c>log4net.Util.LogicalThreadContextProperties</c>. /// </para> /// <para> /// For .NET Standard 1.3 this class uses /// System.Threading.AsyncLocal rather than <see /// cref="System.Runtime.Remoting.Messaging.CallContext"/>. /// </para> /// <para> /// The <see cref="CallContext"/> requires a link time /// <see cref="System.Security.Permissions.SecurityPermission"/> for the /// <see cref="System.Security.Permissions.SecurityPermissionFlag.Infrastructure"/>. /// If the calling code does not have this permission then this context will be disabled. /// It will not store any property values set on it. /// </para> /// </remarks> /// <author>Nicko Cadell</author> public sealed class LogicalThreadContextProperties : ContextPropertiesBase { #if NETSTANDARD1_3 private static readonly AsyncLocal<PropertiesDictionary> AsyncLocalDictionary = new AsyncLocal<PropertiesDictionary>(); #else private const string c_SlotName = "log4net.Util.LogicalThreadContextProperties"; #endif /// <summary> /// Flag used to disable this context if we don't have permission to access the CallContext. /// </summary> private bool m_disabled = false; #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LogicalThreadContextProperties" /> class. /// </para> /// </remarks> internal LogicalThreadContextProperties() { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the value of a property /// </summary> /// <value> /// The value for the property with the specified key /// </value> /// <remarks> /// <para> /// Get or set the property value for the <paramref name="key"/> specified. /// </para> /// </remarks> override public object this[string key] { get { // Don't create the dictionary if it does not already exist PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { return dictionary[key]; } return null; } set { // Force the dictionary to be created PropertiesDictionary props = GetProperties(true); // Reason for cloning the dictionary below: object instances set on the CallContext // need to be immutable to correctly flow through async/await PropertiesDictionary immutableProps = new PropertiesDictionary(props); immutableProps[key] = value; SetLogicalProperties(immutableProps); } } #endregion Public Instance Properties #region Public Instance Methods /// <summary> /// Remove a property /// </summary> /// <param name="key">the key for the entry to remove</param> /// <remarks> /// <para> /// Remove the value for the specified <paramref name="key"/> from the context. /// </para> /// </remarks> public void Remove(string key) { PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { PropertiesDictionary immutableProps = new PropertiesDictionary(dictionary); immutableProps.Remove(key); SetLogicalProperties(immutableProps); } } /// <summary> /// Clear all the context properties /// </summary> /// <remarks> /// <para> /// Clear all the context properties /// </para> /// </remarks> public void Clear() { PropertiesDictionary dictionary = GetProperties(false); if (dictionary != null) { PropertiesDictionary immutableProps = new PropertiesDictionary(); SetLogicalProperties(immutableProps); } } #endregion Public Instance Methods #region Internal Instance Methods /// <summary> /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread. /// </summary> /// <param name="create">create the dictionary if it does not exist, otherwise return null if is does not exist</param> /// <returns>the properties for this thread</returns> /// <remarks> /// <para> /// The collection returned is only to be used on the calling thread. If the /// caller needs to share the collection between different threads then the /// caller must clone the collection before doings so. /// </para> /// </remarks> internal PropertiesDictionary GetProperties(bool create) { if (!m_disabled) { try { PropertiesDictionary properties = GetLogicalProperties(); if (properties == null && create) { properties = new PropertiesDictionary(); SetLogicalProperties(properties); } return properties; } catch (SecurityException secEx) { m_disabled = true; // Thrown if we don't have permission to read or write the CallContext LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx); } } // Only get here is we are disabled because of a security exception if (create) { return new PropertiesDictionary(); } return null; } #endregion Internal Instance Methods #region Private Static Methods /// <summary> /// Gets the call context get data. /// </summary> /// <returns>The peroperties dictionary stored in the call context</returns> /// <remarks> /// The <see cref="CallContext"/> method <see cref="CallContext.GetData"/> has a /// security link demand, therfore we must put the method call in a seperate method /// that we can wrap in an exception handler. /// </remarks> #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif private static PropertiesDictionary GetLogicalProperties() { #if NETSTANDARD1_3 return AsyncLocalDictionary.Value; #elif NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 return CallContext.LogicalGetData(c_SlotName) as PropertiesDictionary; #else return CallContext.GetData(c_SlotName) as PropertiesDictionary; #endif } /// <summary> /// Sets the call context data. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// The <see cref="CallContext"/> method <see cref="CallContext.SetData"/> has a /// security link demand, therfore we must put the method call in a seperate method /// that we can wrap in an exception handler. /// </remarks> #if NET_4_0 || MONO_4_0 [System.Security.SecuritySafeCritical] #endif private static void SetLogicalProperties(PropertiesDictionary properties) { #if NETSTANDARD1_3 AsyncLocalDictionary.Value = properties; #elif NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 CallContext.LogicalSetData(c_SlotName, properties); #else CallContext.SetData(c_SlotName, properties); #endif } #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the LogicalThreadContextProperties class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LogicalThreadContextProperties); #endregion Private Static Fields } } #endif
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Windows.Forms; using Sce.Atf; using Sce.Atf.Adaptation; using Sce.Atf.Applications; using Sce.Atf.Controls; using Sce.Atf.Dom; using Sce.Sled.Resources; using Sce.Sled.Shared.Controls; using Sce.Sled.Shared.Dom; using Sce.Sled.Shared.Services; using Sce.Sled.Shared.Utilities; namespace Sce.Sled { [Export(typeof(SledBreakpointEditor))] [PartCreationPolicy(CreationPolicy.Shared)] class SledBreakpointEditor : SledTreeListViewEditor, IItemView, ITreeListView, IObservableContext { [ImportingConstructor] public SledBreakpointEditor() : base( Localization.BreakpointWindowName, SledIcon.ProjectToggleBreakpoint, SledProjectFilesBreakpointType.TheColumnNames, TreeListView.Style.List, StandardControlGroup.Right) { TreeListView.NodeSorter = new BreakpointComparer(TreeListView); } #region IInitializable Interface public override void Initialize() { base.Initialize(); m_projectService = SledServiceInstance.Get<ISledProjectService>(); m_projectService.Created += ProjectServiceCreated; m_projectService.Opened += ProjectServiceOpened; m_projectService.Closing += ProjectServiceClosing; KeyUp += ControlKeyUp; MouseDoubleClick += ControlMouseDoubleClick; } #endregion #region IItemView Interface public void GetInfo(object item, ItemInfo info) { var itemView = item.As<IItemView>(); if ((itemView == null) || (itemView == this)) return; itemView.GetInfo(item, info); } #endregion #region ITreeListView Interface public IEnumerable<object> GetChildren(object parent) { yield break; } public IEnumerable<object> Roots { get { if (!m_projectService.Active) yield break; // Convert the project tree to a flat list // of only breakpoints foreach (var file in m_projectService.AllFiles) { foreach (var bp in file.Breakpoints) yield return bp; } } } public string[] ColumnNames { get { return SledProjectFilesBreakpointType.TheColumnNames; } } #endregion #region IObservableContext Interface public event EventHandler<ItemInsertedEventArgs<object>> ItemInserted; public event EventHandler<ItemRemovedEventArgs<object>> ItemRemoved; public event EventHandler<ItemChangedEventArgs<object>> ItemChanged; public event EventHandler Reloaded; #endregion #region ISledProjectService Events private void ProjectServiceCreated(object sender, SledProjectServiceProjectEventArgs e) { View = this; SubscribeToEvents(e.Project.DomNode); } private void ProjectServiceOpened(object sender, SledProjectServiceProjectEventArgs e) { View = this; SubscribeToEvents(e.Project.DomNode); } private void ProjectServiceClosing(object sender, SledProjectServiceProjectEventArgs e) { UnsubscribeFromEvents(e.Project.DomNode); View = null; // Not actually used; just here to stop compiler warning Reloaded.Raise(this, EventArgs.Empty); } #endregion #region TreeListViewEditor Events private void ControlKeyUp(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Delete) return; foreach (object item in Selection) { var bp = item.As<SledProjectFilesBreakpointType>(); if (bp == null) continue; bp.File.Breakpoints.Remove(bp); } } private void ControlMouseDoubleClick(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; var lastHit = LastHit; if (lastHit == null) return; var bp = lastHit.As<SledProjectFilesBreakpointType>(); if (bp == null) return; // Jump to breakpoint in file m_gotoService.Get.GotoLine(bp.File.AbsolutePath, bp.Line, false); } #endregion #region DomNode Events private void DomNodeAttributeChanged(object sender, AttributeEventArgs e) { if (!e.DomNode.Is<SledProjectFilesBreakpointType>()) return; ItemChanged.Raise( this, new ItemChangedEventArgs<object>( e.DomNode.As<SledProjectFilesBreakpointType>())); } private void DomNodeChildInserted(object sender, ChildEventArgs e) { if (!e.Child.Is<SledProjectFilesBreakpointType>()) return; ItemInserted.Raise( this, new ItemInsertedEventArgs<object>( e.Index, e.Child.As<SledProjectFilesBreakpointType>())); } private void DomNodeChildRemoving(object sender, ChildEventArgs e) { if (!e.Child.Is<SledProjectFilesBreakpointType>()) return; ItemRemoved.Raise( this, new ItemRemovedEventArgs<object>( e.Index, e.Child.As<SledProjectFilesBreakpointType>())); } #endregion #region Member Methods private void SubscribeToEvents(DomNode root) { root.AttributeChanged += DomNodeAttributeChanged; root.ChildInserted += DomNodeChildInserted; root.ChildRemoving += DomNodeChildRemoving; } private void UnsubscribeFromEvents(DomNode root) { root.AttributeChanged -= DomNodeAttributeChanged; root.ChildInserted -= DomNodeChildInserted; root.ChildRemoving -= DomNodeChildRemoving; } #endregion #region Private Classes private class BreakpointComparer : IComparer<TreeListView.Node> { public BreakpointComparer(TreeListView owner) { Owner = owner; } public int Compare(TreeListView.Node x, TreeListView.Node y) { if ((x == null) && (y == null)) return 0; if (x == null) return 1; if (y == null) return -1; if (ReferenceEquals(x, y)) return 0; var bpX = x.Tag.As<SledProjectFilesBreakpointType>(); var bpY = y.Tag.As<SledProjectFilesBreakpointType>(); var result = 0; SortFunction[] sortFuncs; switch (Owner.SortColumn) { default: sortFuncs = s_sortColumn0; break; case 1: sortFuncs = s_sortColumn1; break; case 2: sortFuncs = s_sortColumn2; break; case 3: sortFuncs = s_sortColumn3; break; case 4: sortFuncs = s_sortColumn4; break; case 5: sortFuncs = s_sortColumn5; break; case 6: sortFuncs = s_sortColumn6; break; } for (var i = 0; i < sortFuncs.Length; i++) { result = sortFuncs[i](bpX, bpY); if (result != 0) break; } if (Owner.SortOrder == SortOrder.Descending) result *= -1; return result; } private TreeListView Owner { get; set; } } #endregion #region Breakpoint Sorting private delegate int SortFunction(SledProjectFilesBreakpointType x, SledProjectFilesBreakpointType y); private static int CompareEnabled(SledProjectFilesBreakpointType x, SledProjectFilesBreakpointType y) { if (x.Enabled && y.Enabled) return 0; return x.Enabled ? -1 : 1; } private static int CompareFile(SledProjectFilesBreakpointType x, SledProjectFilesBreakpointType y) { return string.Compare(x.File.Path, y.File.Path, StringComparison.CurrentCultureIgnoreCase); } private static int CompareLine(SledProjectFilesBreakpointType x, SledProjectFilesBreakpointType y) { if (x.Line == y.Line) return 0; return x.Line < y.Line ? -1 : 1; } private static int CompareCondition(SledProjectFilesBreakpointType x, SledProjectFilesBreakpointType y) { return string.Compare(x.Condition, y.Condition, StringComparison.CurrentCultureIgnoreCase); } private static int CompareConditionEnabled(SledProjectFilesBreakpointType x, SledProjectFilesBreakpointType y) { if (x.ConditionEnabled && y.ConditionEnabled) return 0; return x.ConditionEnabled ? -1 : 1; } private static int CompareConditionResult(SledProjectFilesBreakpointType x, SledProjectFilesBreakpointType y) { if (x.ConditionResult == y.ConditionResult) return 0; return x.ConditionResult ? -1 : 1; } private static int CompareEnvironment(SledProjectFilesBreakpointType x, SledProjectFilesBreakpointType y) { if (x.UseFunctionEnvironment == y.UseFunctionEnvironment) return 0; return x.UseFunctionEnvironment ? -1 : 1; } private static readonly SortFunction[] s_sortColumn0 = new SortFunction[] { CompareEnabled, CompareFile, CompareLine, }; private static readonly SortFunction[] s_sortColumn1 = new SortFunction[] { CompareFile, CompareLine, }; private static readonly SortFunction[] s_sortColumn2 = new SortFunction[] { CompareLine, CompareFile, }; private static readonly SortFunction[] s_sortColumn3 = new SortFunction[] { CompareCondition, CompareFile, CompareLine, }; private static readonly SortFunction[] s_sortColumn4 = new SortFunction[] { CompareConditionEnabled, CompareFile, CompareLine, }; private static readonly SortFunction[] s_sortColumn5 = new SortFunction[] { CompareConditionResult, CompareFile, CompareLine, }; private static readonly SortFunction[] s_sortColumn6 = new SortFunction[] { CompareEnvironment, CompareFile, CompareLine, }; #endregion private ISledProjectService m_projectService; private readonly SledServiceReference<ISledGotoService> m_gotoService = new SledServiceReference<ISledGotoService>(); } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using UnityEngine; using System; using System.Collections.Generic; using UnityEditor; namespace AmplifyShaderEditor { [Serializable] [NodeAttributes( "If", "Logical Operators", "Conditional comparison between A with B.", null, KeyCode.None, true, false, null, null, true )] public sealed class ConditionalIfNode : ParentNode { private const string UseUnityBranchesStr = "Dynamic Branching"; private const string UnityBranchStr = "UNITY_BRANCH "; private readonly string[] IfOps = { "if( {0} > {1} )", "if( {0} == {1} )", "if( {0} < {1} )" }; private WirePortDataType m_inputMainDataType = WirePortDataType.FLOAT; private WirePortDataType m_outputMainDataType = WirePortDataType.FLOAT; private string[] m_results = { string.Empty, string.Empty, string.Empty }; [SerializeField] private bool m_useUnityBranch = false; protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); AddInputPort( WirePortDataType.FLOAT, false, "A" ); AddInputPort( WirePortDataType.FLOAT, false, "B" ); AddInputPort( WirePortDataType.FLOAT, false, "A > B" ); AddInputPort( WirePortDataType.FLOAT, false, "A == B" ); AddInputPort( WirePortDataType.FLOAT, false, "A < B" ); AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue ); m_textLabelWidth = 131; m_useInternalPortData = true; m_autoWrapProperties = true; } public override void OnConnectedOutputNodeChanges( int inputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type ) { base.OnConnectedOutputNodeChanges( inputPortId, otherNodeId, otherPortId, name, type ); UpdateConnection( inputPortId ); } public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true ) { base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode ); UpdateConnection( portId ); } public override void DrawProperties() { base.DrawProperties(); m_useUnityBranch = EditorGUILayoutToggle( UseUnityBranchesStr, m_useUnityBranch ); } public override void OnInputPortDisconnected( int portId ) { UpdateConnection( portId ); } void TestMainInputDataType() { WirePortDataType newType = WirePortDataType.FLOAT; if ( m_inputPorts[ 0 ].IsConnected && UIUtils.GetPriority( m_inputPorts[ 0 ].DataType ) > UIUtils.GetPriority( newType ) ) { newType = m_inputPorts[ 0 ].DataType; } if ( m_inputPorts[ 1 ].IsConnected && ( UIUtils.GetPriority( m_inputPorts[ 1 ].DataType ) > UIUtils.GetPriority( newType ) ) ) { newType = m_inputPorts[ 1 ].DataType; } m_inputMainDataType = newType; } void TestMainOutputDataType() { WirePortDataType newType = WirePortDataType.FLOAT; for ( int i = 2; i < 5; i++ ) { if ( m_inputPorts[ i ].IsConnected && ( UIUtils.GetPriority( m_inputPorts[ i ].DataType ) > UIUtils.GetPriority( newType ) ) ) { newType = m_inputPorts[ i ].DataType; } } if ( newType != m_outputMainDataType ) { m_outputMainDataType = newType; m_outputPorts[ 0 ].ChangeType( m_outputMainDataType, false ); } } public void UpdateConnection( int portId ) { m_inputPorts[ portId ].MatchPortToConnection(); switch ( portId ) { case 0: case 1: { TestMainInputDataType(); } break; case 2: case 3: case 4: { TestMainOutputDataType(); } break; } } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar ) { if ( m_outputPorts[ 0 ].IsLocalValue ) return m_outputPorts[ 0 ].LocalValue; string AValue = m_inputPorts[ 0 ].GenerateShaderForOutput( ref dataCollector, m_inputMainDataType, ignoreLocalvar, true ); string BValue = m_inputPorts[ 1 ].GenerateShaderForOutput( ref dataCollector, m_inputMainDataType, ignoreLocalvar, true ); m_results[ 0 ] = m_inputPorts[ 2 ].GenerateShaderForOutput( ref dataCollector, m_outputMainDataType, ignoreLocalvar, true ); m_results[ 1 ] = m_inputPorts[ 3 ].GenerateShaderForOutput( ref dataCollector, m_outputMainDataType, ignoreLocalvar, true ); m_results[ 2 ] = m_inputPorts[ 4 ].GenerateShaderForOutput( ref dataCollector, m_outputMainDataType, ignoreLocalvar, true ); string localVarName = "ifLocalVar" + m_uniqueId; string localVarDec = string.Format( "{0} {1} = 0;", UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ), localVarName ); bool firstIf = true; List<string> instructions = new List<string>(); instructions.Add( localVarDec ); for ( int i = 2; i < 5; i++ ) { if ( m_inputPorts[ i ].IsConnected ) { int idx = i - 2; string ifOp = string.Format( IfOps[ idx ], AValue, BValue ); if ( m_useUnityBranch ) { ifOp = UnityBranchStr + ifOp; } instructions.Add( firstIf ? ifOp : "else " + ifOp ); instructions.Add( string.Format( "\t{0} = {1};", localVarName, m_results[ idx ] ) ); firstIf = false; } } if ( firstIf ) { UIUtils.ShowMessage( "No result inputs connectect on If Node. Using node internal data." ); // no input nodes connected ... use port default values for ( int i = 2; i < 5; i++ ) { int idx = i - 2; string ifOp = string.Format( IfOps[ idx ], AValue, BValue ); if ( m_useUnityBranch ) { ifOp = UnityBranchStr + ifOp; } instructions.Add( firstIf ? ifOp : "else " + ifOp ); instructions.Add( string.Format( "\t{0} = {1};", localVarName, m_results[ idx ] ) ); firstIf = false; } } for ( int i = 0; i < instructions.Count; i++ ) { dataCollector.AddToLocalVariables( dataCollector.PortCategory, m_uniqueId, instructions[ i ] , true ); } //dataCollector.AddInstructions( true, true, instructions.ToArray() ); instructions.Clear(); instructions = null; m_outputPorts[ 0 ].SetLocalValue( localVarName ); return localVarName; } public override void ReadFromString( ref string[] nodeParams ) { base.ReadFromString( ref nodeParams ); if ( UIUtils.CurrentShaderVersion() > 4103 ) { m_useUnityBranch = Convert.ToBoolean( GetCurrentParam( ref nodeParams )); } } public override void WriteToString( ref string nodeInfo, ref string connectionsInfo ) { base.WriteToString( ref nodeInfo, ref connectionsInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, m_useUnityBranch ); } } }
namespace WebApplication.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.Categories", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Comments", c => new { Id = c.Int(nullable: false, identity: true), AuthorId = c.String(maxLength: 128), Karma = c.Int(nullable: false), Text = c.String(), ParentId = c.Int(), RequestId = c.Int(), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), ApplicationUser_Id = c.String(maxLength: 128), ApplicationUser_Id1 = c.String(maxLength: 128), ApplicationUser_Id2 = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id1) .ForeignKey("dbo.Requests", t => t.RequestId) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id2) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .Index(t => t.AuthorId) .Index(t => t.RequestId) .Index(t => t.ApplicationUser_Id) .Index(t => t.ApplicationUser_Id1) .Index(t => t.ApplicationUser_Id2); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false), Password = c.String(nullable: false, maxLength: 100), Karma = c.Int(nullable: false), LastVisition = c.DateTime(nullable: false), RegistrationDate = c.DateTime(nullable: false), UserInfo = c.String(), IsBlocked = c.Boolean(nullable: false), BlockForDate = c.DateTime(nullable: false), BlockReason = c.String(), DateOfBlocking = c.DateTime(nullable: false), Balance = c.Decimal(nullable: false, precision: 18, scale: 2), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), Request_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Requests", t => t.Request_Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex") .Index(t => t.Request_Id); CreateTable( "dbo.Documents", c => new { Id = c.Int(nullable: false, identity: true), Url = c.String(), Size = c.Int(nullable: false), Type = c.String(), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), ApplicationUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id) .Index(t => t.ApplicationUser_Id); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.Contacts", c => new { Id = c.Int(nullable: false, identity: true), ContactAdress = c.String(nullable: false, maxLength: 200), AuthorId = c.String(maxLength: 128), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .Index(t => t.AuthorId); CreateTable( "dbo.RecallMessages", c => new { Id = c.Int(nullable: false, identity: true), Text = c.String(nullable: false), AuthorId = c.String(maxLength: 128), Karma = c.Int(nullable: false), ParentId = c.Int(), AboutSite = c.Boolean(nullable: false), UserId = c.String(maxLength: 128), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), ApplicationUser_Id = c.String(maxLength: 128), ApplicationUser_Id1 = c.String(maxLength: 128), ApplicationUser_Id2 = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id1) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id2) .Index(t => t.AuthorId) .Index(t => t.UserId) .Index(t => t.ApplicationUser_Id) .Index(t => t.ApplicationUser_Id1) .Index(t => t.ApplicationUser_Id2); CreateTable( "dbo.ErrorMessages", c => new { Id = c.Int(nullable: false, identity: true), Text = c.String(nullable: false), AuthorId = c.String(maxLength: 128), ErrorStatus = c.Int(nullable: false), ForAdministration = c.Boolean(nullable: false), Email = c.String(), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), Document_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Documents", t => t.Document_Id) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .Index(t => t.AuthorId) .Index(t => t.Document_Id); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.Payments", c => new { Id = c.Int(nullable: false, identity: true), RequestSolutionId = c.Int(), RequestId = c.Int(), Description = c.String(nullable: false), DocumentId = c.Int(), Checked = c.Boolean(nullable: false), Closed = c.Boolean(nullable: false), AddingFunds = c.Boolean(nullable: false), AuthorId = c.String(maxLength: 128), Price = c.Decimal(nullable: false, precision: 18, scale: 2), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Documents", t => t.DocumentId) .ForeignKey("dbo.Requests", t => t.RequestId) .ForeignKey("dbo.RequestSolutions", t => t.RequestSolutionId) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .Index(t => t.RequestSolutionId) .Index(t => t.RequestId) .Index(t => t.DocumentId) .Index(t => t.AuthorId); CreateTable( "dbo.Requests", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), Description = c.String(nullable: false, maxLength: 200), DocumentId = c.Int(), AuthorId = c.String(maxLength: 128), ExecutorId = c.String(maxLength: 128), Deadline = c.DateTime(nullable: false), Status = c.Int(nullable: false), Priority = c.Int(nullable: false), CategoryId = c.Int(), SubjectId = c.Int(), LifecycleId = c.Int(), Price = c.Decimal(nullable: false, precision: 18, scale: 2), IsPaid = c.Boolean(nullable: false), Checked = c.Boolean(nullable: false), CanDownload = c.Boolean(nullable: false), IsOnline = c.Boolean(nullable: false), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), ApplicationUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .ForeignKey("dbo.Categories", t => t.CategoryId) .ForeignKey("dbo.Documents", t => t.DocumentId) .ForeignKey("dbo.AspNetUsers", t => t.ExecutorId) .ForeignKey("dbo.Lifecycles", t => t.LifecycleId) .ForeignKey("dbo.Subjects", t => t.SubjectId) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id) .Index(t => t.DocumentId) .Index(t => t.AuthorId) .Index(t => t.ExecutorId) .Index(t => t.CategoryId) .Index(t => t.SubjectId) .Index(t => t.LifecycleId) .Index(t => t.ApplicationUser_Id); CreateTable( "dbo.Lifecycles", c => new { Id = c.Int(nullable: false, identity: true), Opened = c.DateTime(nullable: false), Distributed = c.DateTime(), Proccesing = c.DateTime(), Checking = c.DateTime(), Closed = c.DateTime(), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RequestSolutions", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(maxLength: 50), RequestId = c.Int(), DocumentId = c.Int(), AuthorId = c.String(maxLength: 128), Description = c.String(), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Documents", t => t.DocumentId) .ForeignKey("dbo.Requests", t => t.RequestId) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .Index(t => t.RequestId) .Index(t => t.DocumentId) .Index(t => t.AuthorId); CreateTable( "dbo.Subjects", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Props", c => new { Id = c.Int(nullable: false, identity: true), PropsCategoryId = c.Int(), Number = c.String(nullable: false, maxLength: 200), AuthorId = c.String(maxLength: 128), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.PropsCategories", t => t.PropsCategoryId) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .Index(t => t.PropsCategoryId) .Index(t => t.AuthorId); CreateTable( "dbo.PropsCategories", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), Info = c.String(nullable: false, maxLength: 200), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RequirementConfirmations", c => new { Id = c.Int(nullable: false, identity: true), Description = c.String(nullable: false, maxLength: 200), DocumentId = c.Int(), AuthorId = c.String(maxLength: 128), RequirementId = c.Int(), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Documents", t => t.DocumentId) .ForeignKey("dbo.Requirements", t => t.RequirementId) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .Index(t => t.DocumentId) .Index(t => t.AuthorId) .Index(t => t.RequirementId); CreateTable( "dbo.Requirements", c => new { Id = c.Int(nullable: false, identity: true), Description = c.String(nullable: false, maxLength: 200), AuthorId = c.String(maxLength: 128), Checked = c.Boolean(nullable: false), CanDownload = c.Boolean(nullable: false), Closed = c.Boolean(nullable: false), IsBlocked = c.Boolean(nullable: false), BlockForDate = c.DateTime(nullable: false), BlockReason = c.String(), DateOfBlocking = c.DateTime(nullable: false), Price = c.Decimal(nullable: false, precision: 18, scale: 2), CreateDateTime = c.DateTime(nullable: false), IsDeleted = c.Boolean(nullable: false), DateOfDeleting = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.AuthorId) .Index(t => t.AuthorId); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.Comments", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.RecallMessages", "ApplicationUser_Id2", "dbo.AspNetUsers"); DropForeignKey("dbo.Comments", "ApplicationUser_Id2", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Requirements", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.RequirementConfirmations", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.RequirementConfirmations", "RequirementId", "dbo.Requirements"); DropForeignKey("dbo.RequirementConfirmations", "DocumentId", "dbo.Documents"); DropForeignKey("dbo.RequestSolutions", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.Requests", "ApplicationUser_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.RecallMessages", "ApplicationUser_Id1", "dbo.AspNetUsers"); DropForeignKey("dbo.Props", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.Props", "PropsCategoryId", "dbo.PropsCategories"); DropForeignKey("dbo.Payments", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.Payments", "RequestSolutionId", "dbo.RequestSolutions"); DropForeignKey("dbo.Payments", "RequestId", "dbo.Requests"); DropForeignKey("dbo.Requests", "SubjectId", "dbo.Subjects"); DropForeignKey("dbo.AspNetUsers", "Request_Id", "dbo.Requests"); DropForeignKey("dbo.RequestSolutions", "RequestId", "dbo.Requests"); DropForeignKey("dbo.RequestSolutions", "DocumentId", "dbo.Documents"); DropForeignKey("dbo.Requests", "LifecycleId", "dbo.Lifecycles"); DropForeignKey("dbo.Requests", "ExecutorId", "dbo.AspNetUsers"); DropForeignKey("dbo.Requests", "DocumentId", "dbo.Documents"); DropForeignKey("dbo.Comments", "RequestId", "dbo.Requests"); DropForeignKey("dbo.Requests", "CategoryId", "dbo.Categories"); DropForeignKey("dbo.Requests", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.Payments", "DocumentId", "dbo.Documents"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.ErrorMessages", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.ErrorMessages", "Document_Id", "dbo.Documents"); DropForeignKey("dbo.RecallMessages", "ApplicationUser_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.RecallMessages", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.RecallMessages", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.Comments", "ApplicationUser_Id1", "dbo.AspNetUsers"); DropForeignKey("dbo.Contacts", "AuthorId", "dbo.AspNetUsers"); DropForeignKey("dbo.Comments", "ApplicationUser_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Documents", "ApplicationUser_Id", "dbo.AspNetUsers"); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.Requirements", new[] { "AuthorId" }); DropIndex("dbo.RequirementConfirmations", new[] { "RequirementId" }); DropIndex("dbo.RequirementConfirmations", new[] { "AuthorId" }); DropIndex("dbo.RequirementConfirmations", new[] { "DocumentId" }); DropIndex("dbo.Props", new[] { "AuthorId" }); DropIndex("dbo.Props", new[] { "PropsCategoryId" }); DropIndex("dbo.RequestSolutions", new[] { "AuthorId" }); DropIndex("dbo.RequestSolutions", new[] { "DocumentId" }); DropIndex("dbo.RequestSolutions", new[] { "RequestId" }); DropIndex("dbo.Requests", new[] { "ApplicationUser_Id" }); DropIndex("dbo.Requests", new[] { "LifecycleId" }); DropIndex("dbo.Requests", new[] { "SubjectId" }); DropIndex("dbo.Requests", new[] { "CategoryId" }); DropIndex("dbo.Requests", new[] { "ExecutorId" }); DropIndex("dbo.Requests", new[] { "AuthorId" }); DropIndex("dbo.Requests", new[] { "DocumentId" }); DropIndex("dbo.Payments", new[] { "AuthorId" }); DropIndex("dbo.Payments", new[] { "DocumentId" }); DropIndex("dbo.Payments", new[] { "RequestId" }); DropIndex("dbo.Payments", new[] { "RequestSolutionId" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.ErrorMessages", new[] { "Document_Id" }); DropIndex("dbo.ErrorMessages", new[] { "AuthorId" }); DropIndex("dbo.RecallMessages", new[] { "ApplicationUser_Id2" }); DropIndex("dbo.RecallMessages", new[] { "ApplicationUser_Id1" }); DropIndex("dbo.RecallMessages", new[] { "ApplicationUser_Id" }); DropIndex("dbo.RecallMessages", new[] { "UserId" }); DropIndex("dbo.RecallMessages", new[] { "AuthorId" }); DropIndex("dbo.Contacts", new[] { "AuthorId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.Documents", new[] { "ApplicationUser_Id" }); DropIndex("dbo.AspNetUsers", new[] { "Request_Id" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.Comments", new[] { "ApplicationUser_Id2" }); DropIndex("dbo.Comments", new[] { "ApplicationUser_Id1" }); DropIndex("dbo.Comments", new[] { "ApplicationUser_Id" }); DropIndex("dbo.Comments", new[] { "RequestId" }); DropIndex("dbo.Comments", new[] { "AuthorId" }); DropTable("dbo.AspNetRoles"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.Requirements"); DropTable("dbo.RequirementConfirmations"); DropTable("dbo.PropsCategories"); DropTable("dbo.Props"); DropTable("dbo.Subjects"); DropTable("dbo.RequestSolutions"); DropTable("dbo.Lifecycles"); DropTable("dbo.Requests"); DropTable("dbo.Payments"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.ErrorMessages"); DropTable("dbo.RecallMessages"); DropTable("dbo.Contacts"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.Documents"); DropTable("dbo.AspNetUsers"); DropTable("dbo.Comments"); DropTable("dbo.Categories"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace System.IO { internal sealed partial class Win32FileSystem : FileSystem { internal const int GENERIC_READ = unchecked((int)0x80000000); public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); int errorCode = Interop.Kernel32.CopyFile(sourceFullPath, destFullPath, !overwrite); if (errorCode != Interop.Errors.ERROR_SUCCESS) { string fileName = destFullPath; if (errorCode != Interop.Errors.ERROR_FILE_EXISTS) { // For a number of error codes (sharing violation, path // not found, etc) we don't know if the problem was with // the source or dest file. Try reading the source file. using (SafeFileHandle handle = Interop.Kernel32.UnsafeCreateFile(sourceFullPath, GENERIC_READ, FileShare.Read, ref secAttrs, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) fileName = sourceFullPath; } if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { if (DirectoryExists(destFullPath)) throw new IOException(SR.Format(SR.Arg_FileIsDirectory_Name, destFullPath), Interop.Errors.ERROR_ACCESS_DENIED); } } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors) { int flags = Interop.Kernel32.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) { flags |= Interop.Kernel32.REPLACEFILE_IGNORE_MERGE_ERRORS; } if (!Interop.Kernel32.ReplaceFile(destFullPath, sourceFullPath, destBackupFullPath, flags, IntPtr.Zero, IntPtr.Zero)) { throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } [System.Security.SecuritySafeCritical] public override void CreateDirectory(string fullPath) { // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessible and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (DirectoryExists(fullPath)) return; List<string> stackDir = new List<string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) length--; int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing stackDir.Add(dir); else somepathexists = true; while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) i--; i--; } } int count = stackDir.Count; // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); bool r = true; int firstError = 0; string errorString = fullPath; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { string name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); r = Interop.Kernel32.CreateDirectory(name, ref secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Interop.Errors.ERROR_ALREADY_EXISTS) firstError = currentError; else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (File.InternalExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.Errors.ERROR_ACCESS_DENIED)) { firstError = currentError; errorString = name; } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, root); return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) throw Win32Marshal.GetExceptionForWin32Error(firstError, errorString); } public override void DeleteFile(string fullPath) { bool r = Interop.Kernel32.DeleteFile(fullPath); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) return; else throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override bool DirectoryExists(string fullPath) { int lastError = Interop.Errors.ERROR_SUCCESS; return DirectoryExists(fullPath, out lastError); } private bool DirectoryExists(string path, out int lastError) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); lastError = FillAttributeInfo(path, ref data, returnErrorOnNotFound: true); return (lastError == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0); } public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern, (searchTarget & SearchTarget.Files) == SearchTarget.Files, (searchTarget & SearchTarget.Directories) == SearchTarget.Directories, searchOption); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Directories: return Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Files: return Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Both: return Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption); default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget)); } } /// <summary> /// Returns 0 on success, otherwise a Win32 error code. Note that /// classes should use -1 as the uninitialized state for dataInitialized. /// </summary> /// <param name="returnErrorOnNotFound">Return the error code for not found errors?</param> [System.Security.SecurityCritical] internal static int FillAttributeInfo(string path, ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data, bool returnErrorOnNotFound) { int errorCode = Interop.Errors.ERROR_SUCCESS; // Neither GetFileAttributes or FindFirstFile like trailing separators path = path.TrimEnd(PathHelpers.DirectorySeparatorChars); using (new DisableMediaInsertionPrompt()) { if (!Interop.Kernel32.GetFileAttributesEx(path, Interop.Kernel32.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { // Files that are marked for deletion will not let you GetFileAttributes, // ERROR_ACCESS_DENIED is given back without filling out the data struct. // FindFirstFile, however, will. Historically we always gave back attributes // for marked-for-deletion files. var findData = new Interop.Kernel32.WIN32_FIND_DATA(); using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(path, ref findData)) { if (handle.IsInvalid) { errorCode = Marshal.GetLastWin32Error(); } else { errorCode = Interop.Errors.ERROR_SUCCESS; data.PopulateFrom(ref findData); } } } } } if (errorCode != Interop.Errors.ERROR_SUCCESS && !returnErrorOnNotFound) { switch (errorCode) { case Interop.Errors.ERROR_FILE_NOT_FOUND: case Interop.Errors.ERROR_PATH_NOT_FOUND: case Interop.Errors.ERROR_NOT_READY: // Removable media not ready // Return default value for backward compatibility data.fileAttributes = -1; return Interop.Errors.ERROR_SUCCESS; } } return errorCode; } public override bool FileExists(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); return (errorCode == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0); } public override FileAttributes GetAttributes(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); return (FileAttributes)data.fileAttributes; } public override string GetCurrentDirectory() { StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH + 1); if (Interop.Kernel32.GetCurrentDirectory(sb.Capacity, sb) == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); string currentDirectory = sb.ToString(); // Note that if we have somehow put our command prompt into short // file name mode (i.e. by running edlin or a DOS grep, etc), then // this will return a short file name. if (currentDirectory.IndexOf('~') >= 0) { int r = Interop.Kernel32.GetLongPathName(currentDirectory, sb, sb.Capacity); if (r == 0 || r >= Interop.Kernel32.MAX_PATH) { int errorCode = Marshal.GetLastWin32Error(); if (r >= Interop.Kernel32.MAX_PATH) errorCode = Interop.Errors.ERROR_FILENAME_EXCED_RANGE; if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND && errorCode != Interop.Errors.ERROR_INVALID_FUNCTION && // by design - enough said. errorCode != Interop.Errors.ERROR_ACCESS_DENIED) throw Win32Marshal.GetExceptionForWin32Error(errorCode); } currentDirectory = sb.ToString(); } StringBuilderCache.Release(sb); return currentDirectory; } public override DateTimeOffset GetCreationTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow); return DateTimeOffset.FromFileTime(dt); } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } public override DateTimeOffset GetLastAccessTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow); return DateTimeOffset.FromFileTime(dt); } public override DateTimeOffset GetLastWriteTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return DateTimeOffset.FromFileTime(dt); } public override void MoveDirectory(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, sourceFullPath); // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp. throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), Win32Marshal.MakeHRFromErrorCode(errorCode)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public override void MoveFile(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } [System.Security.SecurityCritical] private static SafeFileHandle OpenHandle(string fullPath, bool asDirectory) { string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); if (root == fullPath && root[1] == Path.VolumeSeparatorChar) { // intentionally not fullpath, most upstack public APIs expose this as path. throw new ArgumentException(SR.Arg_PathIsVolume, "path"); } Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); SafeFileHandle handle = Interop.Kernel32.SafeCreateFile( fullPath, Interop.Kernel32.GenericOperations.GENERIC_WRITE, FileShare.ReadWrite | FileShare.Delete, ref secAttrs, FileMode.Open, asDirectory ? Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : (int)FileOptions.None, IntPtr.Zero ); if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // NT5 oddity - when trying to open "C:\" as a File, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. if (!asDirectory && errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath))) errorCode = Interop.Errors.ERROR_ACCESS_DENIED; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } return handle; } public override void RemoveDirectory(string fullPath, bool recursive) { // Do not recursively delete through reparse points. if (!recursive || IsReparsePoint(fullPath)) { RemoveDirectoryInternal(fullPath, topLevel: true); return; } // We want extended syntax so we can delete "extended" subdirectories and files // (most notably ones with trailing whitespace or periods) fullPath = PathInternal.EnsureExtendedPrefix(fullPath); Interop.Kernel32.WIN32_FIND_DATA findData = new Interop.Kernel32.WIN32_FIND_DATA(); RemoveDirectoryRecursive(fullPath, ref findData, topLevel: true); } private static bool IsReparsePoint(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); if (errorCode != Interop.Errors.ERROR_SUCCESS) { // File not found doesn't make much sense coming from a directory delete. if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } return (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0); } private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel32.WIN32_FIND_DATA findData, bool topLevel) { int errorCode; Exception exception = null; using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(Directory.EnsureTrailingDirectorySeparator(fullPath) + "*", ref findData)) { if (handle.IsInvalid) throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); do { if ((findData.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0) { // File string fileName = findData.cFileName.GetStringFromFixedBuffer(); if (!Interop.Kernel32.DeleteFile(Path.Combine(fullPath, fileName)) && exception == null) { errorCode = Marshal.GetLastWin32Error(); // We don't care if something else deleted the file first if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } else { // Directory, skip ".", "..". if (findData.cFileName.FixedBufferEqualsString(".") || findData.cFileName.FixedBufferEqualsString("..")) continue; string fileName = findData.cFileName.GetStringFromFixedBuffer(); if ((findData.dwFileAttributes & (int)FileAttributes.ReparsePoint) == 0) { // Not a reparse point, recurse. try { RemoveDirectoryRecursive( Path.Combine(fullPath, fileName), findData: ref findData, topLevel: false); } catch (Exception e) { if (exception == null) exception = e; } } else { // Reparse point, don't recurse, just remove. (dwReserved0 is documented for this flag) if (findData.dwReserved0 == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT) { // Mount point. Unmount using full path plus a trailing '\'. // (Note: This doesn't remove the underlying directory) string mountPoint = Path.Combine(fullPath, fileName + PathHelpers.DirectorySeparatorCharAsString); if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint) && exception == null) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } // Note that RemoveDirectory on a symbolic link will remove the link itself. if (!Interop.Kernel32.RemoveDirectory(Path.Combine(fullPath, fileName)) && exception == null) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } } } while (Interop.Kernel32.FindNextFile(handle, ref findData)); if (exception != null) throw exception; errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_NO_MORE_FILES) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } RemoveDirectoryInternal(fullPath, topLevel: topLevel); } private static void RemoveDirectoryInternal(string fullPath, bool topLevel) { if (!Interop.Kernel32.RemoveDirectory(fullPath)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Interop.Errors.ERROR_FILE_NOT_FOUND: // File not found doesn't make much sense coming from a directory delete. errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; goto case Interop.Errors.ERROR_PATH_NOT_FOUND; case Interop.Errors.ERROR_PATH_NOT_FOUND: // We only throw for the top level directory not found, not for any contents. if (!topLevel) return; break; case Interop.Errors.ERROR_ACCESS_DENIED: // This conversion was originally put in for Win9x. Keeping for compatibility. throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetAttributes(string fullPath, FileAttributes attributes) { SetAttributesInternal(fullPath, attributes); } private static void SetAttributesInternal(string fullPath, FileAttributes attributes) { bool r = Interop.Kernel32.SetFileAttributes(fullPath, (int)attributes); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(attributes)); throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetCreationTimeInternal(fullPath, time, asDirectory); } private static void SetCreationTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, creationTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetCurrentDirectory(string fullPath) { if (!Interop.Kernel32.SetCurrentDirectory(fullPath)) { // If path doesn't exist, this sets last error to 2 (File // not Found). LEGACY: This may potentially have worked correctly // on Win9x, maybe. int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastAccessTimeInternal(fullPath, time, asDirectory); } private static void SetLastAccessTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastAccessTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastWriteTimeInternal(fullPath, time, asDirectory); } private static void SetLastWriteTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastWriteTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override string[] GetLogicalDrives() { return DriveInfoInternal.GetLogicalDrives(); } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Linq; using System.Threading; using MbUnit.Framework; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Data; using Subtext.Framework.Providers; using Subtext.Framework.Web.HttpModules; namespace UnitTests.Subtext.Framework.Components.EntryTests { [TestFixture] public class EntriesGetTests { [SetUp] public void Setup() { string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, ""); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, "", ""); BlogRequest.Current.Blog = Config.GetBlog(hostname, string.Empty); } [Test] [RollBack2] public void GetRecentPostsIncludesEnclosure() { int blogId = Config.CurrentBlog.Id; for(int i = 0; i < 10; i++) { UnitTestHelper.CreateCategory(blogId, "cat" + i); } //Create some entries. Entry entryZero = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero"); Thread.Sleep(100); Entry entryOne = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one"); Thread.Sleep(100); Entry entryTwo = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-two", "body-two"); //Associate categories. for(int i = 0; i < 5; i++) { entryZero.Categories.Add("cat" + (i + 1)); entryOne.Categories.Add("cat" + i); } entryTwo.Categories.Add("cat8"); //Persist entries. UnitTestHelper.Create(entryZero); UnitTestHelper.Create(entryOne); UnitTestHelper.Create(entryTwo); Enclosure enc = UnitTestHelper.BuildEnclosure("Nothing to see here.", "httP://blablabla.com", "audio/mp3", entryZero.Id, 12345678, true, true); Enclosures.Create(enc); //Get Entries ICollection<Entry> entries = ObjectProvider.Instance().GetEntries(3, PostType.BlogPost, PostConfig.IsActive, true); //Test outcome Assert.AreEqual(3, entries.Count, "Expected to find three entries."); Assert.AreEqual(entries.First().Id, entryTwo.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(1).Id, entryOne.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(2).Id, entryZero.Id, "Ordering is off."); Assert.AreEqual(1, entries.First().Categories.Count); Assert.AreEqual(5, entries.ElementAt(1).Categories.Count); Assert.AreEqual(5, entries.ElementAt(2).Categories.Count); Assert.IsNull(entries.First().Enclosure, "Entry should not have enclosure."); Assert.IsNull(entries.ElementAt(1).Enclosure, "Entry should not have enclosure."); Assert.IsNotNull(entries.ElementAt(2).Enclosure, "Entry should have enclosure."); UnitTestHelper.AssertEnclosures(enc, entries.ElementAt(2).Enclosure); } [Test] [RollBack2] public void GetEntriesByTagIncludesEnclosure() { Entry entryZero = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero"); Thread.Sleep(100); Entry entryOne = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one"); UnitTestHelper.Create(entryZero); UnitTestHelper.Create(entryOne); Enclosure enc = UnitTestHelper.BuildEnclosure("Nothing to see here.", "httP://blablabla.com", "audio/mp3", entryZero.Id, 12345678, true, true); Enclosures.Create(enc); var tags = new List<string>(new[] {"Tag1", "Tag2"}); new DatabaseObjectProvider().SetEntryTagList(entryZero.Id, tags); new DatabaseObjectProvider().SetEntryTagList(entryOne.Id, tags); ICollection<Entry> entries = ObjectProvider.Instance().GetEntriesByTag(3, "Tag1"); //Test outcome Assert.AreEqual(2, entries.Count, "Should have retrieved two entries."); Assert.AreEqual(entries.First().Id, entryOne.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(1).Id, entryZero.Id, "Ordering is off."); Assert.IsNull(entries.First().Enclosure, "Entry should not have enclosure."); Assert.IsNotNull(entries.ElementAt(1).Enclosure, "Entry should have enclosure."); UnitTestHelper.AssertEnclosures(enc, entries.ElementAt(1).Enclosure); } [Test] [RollBack2] public void GetEntriesByCategoryIncludesEnclosure() { //Create Category int blogId = Config.CurrentBlog.Id; int categoryId = UnitTestHelper.CreateCategory(blogId, "Test Category"); //Create some entries. Entry entryZero = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero"); Thread.Sleep(100); Entry entryOne = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one"); Thread.Sleep(100); Entry entryTwo = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-two", "body-two"); //Associate Category entryZero.Categories.Add("Test Category"); entryOne.Categories.Add("Test Category"); entryTwo.Categories.Add("Test Category"); //Persist entries. UnitTestHelper.Create(entryZero); UnitTestHelper.Create(entryOne); UnitTestHelper.Create(entryTwo); //Add Enclosure Enclosure enc = UnitTestHelper.BuildEnclosure("Nothing to see here.", "httP://blablabla.com", "audio/mp3", entryZero.Id, 12345678, true, true); Enclosures.Create(enc); //Get Entries ICollection<Entry> entries = ObjectProvider.Instance().GetEntriesByCategory(3, categoryId, true); //Test outcome Assert.AreEqual(3, entries.Count, "Expected to find three entries."); Assert.AreEqual(entries.First().Id, entryTwo.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(1).Id, entryOne.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(2).Id, entryZero.Id, "Ordering is off."); Assert.IsNull(entries.First().Enclosure, "Entry should not have enclosure."); Assert.IsNull(entries.ElementAt(1).Enclosure, "Entry should not have enclosure."); Assert.IsNotNull(entries.ElementAt(2).Enclosure, "Entry should have enclosure."); UnitTestHelper.AssertEnclosures(enc, entries.ElementAt(2).Enclosure); } [Test] [RollBack2] public void GetPostsByDayRangeIncludesEnclosure() { //Create some entries. Entry entryZero = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero"); Thread.Sleep(100); Entry entryOne = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one"); Thread.Sleep(100); Entry entryTwo = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-two", "body-two"); //Persist entries. UnitTestHelper.Create(entryZero); UnitTestHelper.Create(entryOne); UnitTestHelper.Create(entryTwo); //Add Enclosure Enclosure enc = UnitTestHelper.BuildEnclosure("Nothing to see here.", "httP://blablabla.com", "audio/mp3", entryZero.Id, 12345678, true, true); Enclosures.Create(enc); //Get Entries var beginningOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); ICollection<Entry> entries = ObjectProvider.Instance().GetPostsByDayRange(beginningOfMonth, beginningOfMonth.AddMonths(1), PostType.BlogPost, true); //Test outcome Assert.AreEqual(3, entries.Count, "Expected to find three entries."); Assert.AreEqual(entries.First().Id, entryTwo.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(1).Id, entryOne.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(2).Id, entryZero.Id, "Ordering is off."); Assert.IsNull(entries.First().Enclosure, "Entry should not have enclosure."); Assert.IsNull(entries.ElementAt(1).Enclosure, "Entry should not have enclosure."); Assert.IsNotNull(entries.ElementAt(2).Enclosure, "Entry should have enclosure."); UnitTestHelper.AssertEnclosures(enc, entries.ElementAt(2).Enclosure); } [Test] [RollBack2] public void GetPostCollectionByMonthIncludesEnclosure() { //Create some entries. Entry entryZero = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero"); Thread.Sleep(100); Entry entryOne = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one"); Thread.Sleep(100); Entry entryTwo = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-two", "body-two"); //Persist entries. UnitTestHelper.Create(entryZero); UnitTestHelper.Create(entryOne); UnitTestHelper.Create(entryTwo); //Add Enclosure Enclosure enc = UnitTestHelper.BuildEnclosure("Nothing to see here.", "httP://blablabla.com", "audio/mp3", entryZero.Id, 12345678, true, true); Enclosures.Create(enc); //Get Entries ICollection<Entry> entries = ObjectProvider.Instance().GetPostsByMonth(DateTime.Now.Month, DateTime.Now.Year); //Test outcome Assert.AreEqual(3, entries.Count, "Expected to find three entries."); Assert.AreEqual(entries.First().Id, entryTwo.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(1).Id, entryOne.Id, "Ordering is off."); Assert.AreEqual(entries.ElementAt(2).Id, entryZero.Id, "Ordering is off."); Assert.IsNull(entries.First().Enclosure, "Entry should not have enclosure."); Assert.IsNull(entries.ElementAt(1).Enclosure, "Entry should not have enclosure."); Assert.IsNotNull(entries.ElementAt(2).Enclosure, "Entry should have enclosure."); UnitTestHelper.AssertEnclosures(enc, entries.ElementAt(2).Enclosure); } } }
//--------------------------------------------------------------------- // <copyright file="Error.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // static error utility functions // </summary> //--------------------------------------------------------------------- namespace System.Data.Services.Client { using System; /// <summary> /// Strongly-typed and parameterized exception factory. /// </summary> internal static partial class Error { /// <summary> /// create and trace new ArgumentException /// </summary> /// <param name="message">exception message</param> /// <param name="parameterName">parameter name in error</param> /// <returns>ArgumentException</returns> internal static ArgumentException Argument(string message, string parameterName) { return Trace(new ArgumentException(message, parameterName)); } /// <summary> /// create and trace new InvalidOperationException /// </summary> /// <param name="message">exception message</param> /// <returns>InvalidOperationException</returns> internal static InvalidOperationException InvalidOperation(string message) { return Trace(new InvalidOperationException(message)); } /// <summary> /// create and trace new InvalidOperationException /// </summary> /// <param name="message">exception message</param> /// <param name="innerException">innerException</param> /// <returns>InvalidOperationException</returns> internal static InvalidOperationException InvalidOperation(string message, Exception innerException) { return Trace(new InvalidOperationException(message, innerException)); } /// <summary> /// Create and trace a NotSupportedException with a message /// </summary> /// <param name="message">Message for the exception</param> /// <returns>NotSupportedException</returns> internal static NotSupportedException NotSupported(string message) { return Trace(new NotSupportedException(message)); } /// <summary> /// create and throw a ThrowObjectDisposed with a type name /// </summary> /// <param name="type">type being thrown on</param> internal static void ThrowObjectDisposed(Type type) { throw Trace(new ObjectDisposedException(type.ToString())); } /// <summary> /// create and trace a /// </summary> /// <param name="errorCode">errorCode</param> /// <param name="message">message</param> /// <returns>InvalidOperationException</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801", Justification = "errorCode ignored for code sharing")] internal static InvalidOperationException HttpHeaderFailure(int errorCode, string message) { return Trace(new InvalidOperationException(message)); } /// <summary>create exception when missing an expected batch boundary</summary> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamMissingBoundary() { return InvalidOperation(Strings.BatchStream_MissingBoundary); } /// <summary>create exception when the expected content is missing</summary> /// <param name="state">http method operation</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamContentExpected(BatchStreamState state) { return InvalidOperation(Strings.BatchStream_ContentExpected(state.ToString())); } /// <summary>create exception when unexpected content is discovered</summary> /// <param name="state">http method operation</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamContentUnexpected(BatchStreamState state) { return InvalidOperation(Strings.BatchStream_ContentUnexpected(state.ToString())); } /// <summary>create exception when Get operation is specified in changeset</summary> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamGetMethodNotSupportInChangeset() { return InvalidOperation(Strings.BatchStream_GetMethodNotSupportedInChangeset); } /// <summary>create exception when invalid batch request is specified</summary> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidBatchFormat() { return InvalidOperation(Strings.BatchStream_InvalidBatchFormat); } /// <summary>create exception when boundary delimiter is not valid</summary> /// <param name="delimiter">boundary delimiter</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidDelimiter(string delimiter) { return InvalidOperation(Strings.BatchStream_InvalidDelimiter(delimiter)); } /// <summary>create exception when end changeset boundary delimiter is missing</summary> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamMissingEndChangesetDelimiter() { return InvalidOperation(Strings.BatchStream_MissingEndChangesetDelimiter); } /// <summary>create exception when header value specified is not valid</summary> /// <param name="headerValue">headerValue</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidHeaderValueSpecified(string headerValue) { return InvalidOperation(Strings.BatchStream_InvalidHeaderValueSpecified(headerValue)); } /// <summary>create exception when content length is not valid</summary> /// <param name="contentLength">contentLength</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidContentLengthSpecified(string contentLength) { return InvalidOperation(Strings.BatchStream_InvalidContentLengthSpecified(contentLength)); } /// <summary>create exception when CUD operation is specified in batch</summary> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamOnlyGETOperationsCanBeSpecifiedInBatch() { return InvalidOperation(Strings.BatchStream_OnlyGETOperationsCanBeSpecifiedInBatch); } /// <summary>create exception when operation header is specified in start of changeset</summary> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidOperationHeaderSpecified() { return InvalidOperation(Strings.BatchStream_InvalidOperationHeaderSpecified); } /// <summary>create exception when http method name is not valid</summary> /// <param name="methodName">methodName</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidHttpMethodName(string methodName) { return InvalidOperation(Strings.BatchStream_InvalidHttpMethodName(methodName)); } /// <summary>create exception when more data is specified after end of batch delimiter.</summary> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamMoreDataAfterEndOfBatch() { return InvalidOperation(Strings.BatchStream_MoreDataAfterEndOfBatch); } /// <summary>internal error where batch stream does do look ahead when read request is smaller than boundary delimiter</summary> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInternalBufferRequestTooSmall() { return InvalidOperation(Strings.BatchStream_InternalBufferRequestTooSmall); } /// <summary>method not supported</summary> /// <param name="m">method</param> /// <returns>exception to throw</returns> internal static NotSupportedException MethodNotSupported(System.Linq.Expressions.MethodCallExpression m) { return Error.NotSupported(Strings.ALinq_MethodNotSupported(m.Method.Name)); } /// <summary>throw an exception because unexpected batch content was encounted</summary> /// <param name="value">internal error</param> internal static void ThrowBatchUnexpectedContent(InternalError value) { throw InvalidOperation(Strings.Batch_UnexpectedContent((int)value)); } /// <summary>throw an exception because expected batch content was not encountered</summary> /// <param name="value">internal error</param> internal static void ThrowBatchExpectedResponse(InternalError value) { throw InvalidOperation(Strings.Batch_ExpectedResponse((int)value)); } /// <summary>internal error where the first request header is not of the form: 'MethodName' 'Url' 'Version'</summary> /// <param name="header">actual header value specified in the payload.</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidMethodHeaderSpecified(string header) { return InvalidOperation(Strings.BatchStream_InvalidMethodHeaderSpecified(header)); } /// <summary>internal error when http version in batching request is not valid</summary> /// <param name="actualVersion">actual version as specified in the payload.</param> /// <param name="expectedVersion">expected version value.</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidHttpVersionSpecified(string actualVersion, string expectedVersion) { return InvalidOperation(Strings.BatchStream_InvalidHttpVersionSpecified(actualVersion, expectedVersion)); } /// <summary>internal error when number of headers at the start of each operation is not 2</summary> /// <param name="header1">valid header name</param> /// <param name="header2">valid header name</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidNumberOfHeadersAtOperationStart(string header1, string header2) { return InvalidOperation(Strings.BatchStream_InvalidNumberOfHeadersAtOperationStart(header1, header2)); } /// <summary>internal error Content-Transfer-Encoding is not specified or its value is not 'binary'</summary> /// <param name="headerName">name of the header</param> /// <param name="headerValue">expected value of the header</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamMissingOrInvalidContentEncodingHeader(string headerName, string headerValue) { return InvalidOperation(Strings.BatchStream_MissingOrInvalidContentEncodingHeader(headerName, headerValue)); } /// <summary>internal error number of headers at the start of changeset is not correct</summary> /// <param name="header1">valid header name</param> /// <param name="header2">valid header name</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidNumberOfHeadersAtChangeSetStart(string header1, string header2) { return InvalidOperation(Strings.BatchStream_InvalidNumberOfHeadersAtChangeSetStart(header1, header2)); } /// <summary>internal error when content type header is missing</summary> /// <param name="headerName">name of the missing header</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamMissingContentTypeHeader(string headerName) { return InvalidOperation(Strings.BatchStream_MissingContentTypeHeader(headerName)); } /// <summary>internal error when content type header value is invalid.</summary> /// <param name="headerName">name of the header whose value is not correct.</param> /// <param name="headerValue">actual value as specified in the payload</param> /// <param name="mime1">expected value 1</param> /// <param name="mime2">expected value 2</param> /// <returns>exception to throw</returns> internal static InvalidOperationException BatchStreamInvalidContentTypeSpecified(string headerName, string headerValue, string mime1, string mime2) { return InvalidOperation(Strings.BatchStream_InvalidContentTypeSpecified(headerName, headerValue, mime1, mime2)); } /// <summary>unexpected xml when reading web responses</summary> /// <param name="value">internal error</param> /// <returns>exception to throw</returns> internal static InvalidOperationException InternalError(InternalError value) { return InvalidOperation(Strings.Context_InternalError((int)value)); } /// <summary>throw exception for unexpected xml when reading web responses</summary> /// <param name="value">internal error</param> internal static void ThrowInternalError(InternalError value) { throw InternalError(value); } /// <summary> /// Trace the exception /// </summary> /// <typeparam name="T">type of the exception</typeparam> /// <param name="exception">exception object to trace</param> /// <returns>the exception parameter</returns> private static T Trace<T>(T exception) where T : Exception { return exception; } } /// <summary>unique numbers for repeated error messages for unlikely, unactionable exceptions</summary> internal enum InternalError { UnexpectedXmlNodeTypeWhenReading = 1, UnexpectedXmlNodeTypeWhenSkipping = 2, UnexpectedEndWhenSkipping = 3, UnexpectedReadState = 4, UnexpectedRequestBufferSizeTooSmall = 5, UnvalidatedEntityState = 6, NullResponseStream = 7, EntityNotDeleted = 8, EntityNotAddedState = 9, LinkNotAddedState = 10, EntryNotModified = 11, LinkBadState = 12, UnexpectedBeginChangeSet = 13, UnexpectedBatchState = 14, ChangeResponseMissingContentID = 15, ChangeResponseUnknownContentID = 16, TooManyBatchResponse = 17, InvalidEndGetRequestStream = 20, InvalidEndGetRequestCompleted = 21, InvalidEndGetRequestStreamRequest = 22, InvalidEndGetRequestStreamStream = 23, InvalidEndGetRequestStreamContent = 24, InvalidEndGetRequestStreamContentLength = 25, InvalidEndWrite = 30, InvalidEndWriteCompleted = 31, InvalidEndWriteRequest = 32, InvalidEndWriteStream = 33, InvalidEndGetResponse = 40, InvalidEndGetResponseCompleted = 41, InvalidEndGetResponseRequest = 42, InvalidEndGetResponseResponse = 43, InvalidAsyncResponseStreamCopy = 44, InvalidAsyncResponseStreamCopyBuffer = 45, InvalidEndRead = 50, InvalidEndReadCompleted = 51, InvalidEndReadStream = 52, InvalidEndReadCopy = 53, InvalidEndReadBuffer = 54, InvalidSaveNextChange = 60, InvalidBeginNextChange = 61, SaveNextChangeIncomplete = 62, InvalidGetRequestStream = 70, InvalidGetResponse = 71, } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Lucene.Net.Support; namespace Lucene.Net.Search { /// <summary> Filter caching singleton. It can be used /// to save filters locally for reuse. /// This class makes it possble to cache Filters even when using RMI, as it /// keeps the cache on the seaercher side of the RMI connection. /// /// Also could be used as a persistent storage for any filter as long as the /// filter provides a proper hashCode(), as that is used as the key in the cache. /// /// The cache is periodically cleaned up from a separate thread to ensure the /// cache doesn't exceed the maximum size. /// </summary> public class FilterManager { protected internal static FilterManager manager; /// <summary>The default maximum number of Filters in the cache </summary> protected internal const int DEFAULT_CACHE_CLEAN_SIZE = 100; /// <summary>The default frequency of cache clenup </summary> protected internal const long DEFAULT_CACHE_SLEEP_TIME = 1000 * 60 * 10; /// <summary>The cache itself </summary> protected internal IDictionary<int, FilterItem> cache; /// <summary>Maximum allowed cache size </summary> protected internal int cacheCleanSize; /// <summary>Cache cleaning frequency </summary> protected internal long cleanSleepTime; /// <summary>Cache cleaner that runs in a separate thread </summary> protected internal FilterCleaner internalFilterCleaner; private static readonly object _staticSyncObj = new object(); public static FilterManager Instance { get { lock (_staticSyncObj) { return manager ?? (manager = new FilterManager()); } } } /// <summary> Sets up the FilterManager singleton.</summary> protected internal FilterManager() { cache = new HashMap<int, FilterItem>(); cacheCleanSize = DEFAULT_CACHE_CLEAN_SIZE; // Let the cache get to 100 items cleanSleepTime = DEFAULT_CACHE_SLEEP_TIME; // 10 minutes between cleanings internalFilterCleaner = new FilterCleaner(this); ThreadClass fcThread = new ThreadClass(new System.Threading.ThreadStart(internalFilterCleaner.Run)); // setto be a Daemon so it doesn't have to be stopped fcThread.IsBackground = true; fcThread.Start(); } /// <summary> Sets the max size that cache should reach before it is cleaned up</summary> /// <param name="value"> maximum allowed cache size </param> public virtual void SetCacheSize(int value) { this.cacheCleanSize = value; } /// <summary> Sets the cache cleaning frequency in milliseconds.</summary> /// <param name="value"> cleaning frequency in millioseconds </param> public virtual void SetCleanThreadSleepTime(long value) { this.cleanSleepTime = value; } /// <summary> Returns the cached version of the filter. Allows the caller to pass up /// a small filter but this will keep a persistent version around and allow /// the caching filter to do its job. /// /// </summary> /// <param name="filter">The input filter /// </param> /// <returns> The cached version of the filter /// </returns> public virtual Filter GetFilter(Filter filter) { lock (cache) { FilterItem fi = null; fi = cache[filter.GetHashCode()]; if (fi != null) { fi.timestamp = System.DateTime.UtcNow.Ticks; return fi.filter; } cache[filter.GetHashCode()] = new FilterItem(filter); return filter; } } /// <summary> Holds the filter and the last time the filter was used, to make LRU-based /// cache cleaning possible. /// TODO: Clean this up when we switch to Java 1.5 /// </summary> protected internal class FilterItem { public Filter filter; public long timestamp; public FilterItem(Filter filter) { this.filter = filter; this.timestamp = System.DateTime.UtcNow.Ticks; } } /// <summary> Keeps the cache from getting too big. /// If we were using Java 1.5, we could use LinkedHashMap and we would not need this thread /// to clean out the cache. /// /// The SortedSet sortedFilterItems is used only to sort the items from the cache, /// so when it's time to clean up we have the TreeSet sort the FilterItems by /// timestamp. /// /// Removes 1.5 * the numbers of items to make the cache smaller. /// For example: /// If cache clean size is 10, and the cache is at 15, we would remove (15 - 10) * 1.5 = 7.5 round up to 8. /// This way we clean the cache a bit more, and avoid having the cache cleaner having to do it frequently. /// </summary> protected internal class FilterCleaner : IThreadRunnable { private class FilterItemComparer : IComparer<KeyValuePair<int, FilterItem>> { #region IComparer<FilterItem> Members public int Compare(KeyValuePair<int, FilterItem> x, KeyValuePair<int, FilterItem> y) { return x.Value.timestamp.CompareTo(y.Value.timestamp); } #endregion } private bool running = true; private FilterManager manager; private ISet<KeyValuePair<int, FilterItem>> sortedFilterItems; public FilterCleaner(FilterManager enclosingInstance) { this.manager = enclosingInstance; sortedFilterItems = new SortedSet<KeyValuePair<int, FilterItem>>(new FilterItemComparer()); } public virtual void Run() { while (running) { // sort items from oldest to newest // we delete the oldest filters if (this.manager.cache.Count > this.manager.cacheCleanSize) { // empty the temporary set sortedFilterItems.Clear(); lock (this.manager.cache) { sortedFilterItems.UnionWith(this.manager.cache); int numToDelete = (int)((this.manager.cache.Count - this.manager.cacheCleanSize) * 1.5); //delete all of the cache entries not used in a while sortedFilterItems.ExceptWith(sortedFilterItems.Take(numToDelete).ToArray()); } // empty the set so we don't tie up the memory sortedFilterItems.Clear(); } // take a nap System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64)10000 * this.manager.cleanSleepTime)); } } } } }
//------------------------------------------------------------------------------ // <copyright file="StateRuntime.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * StateWebRuntime * * Copyright (c) 1998-1999, Microsoft Corporation * */ namespace System.Web.SessionState { using System.Configuration; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Threading; using System.Web; using System.Web.Caching; using System.Web.Configuration; using System.Web.Util; /// <internalonly/> /// <devdoc> /// </devdoc> [ComImport, Guid("7297744b-e188-40bf-b7e9-56698d25cf44"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public interface IStateRuntime { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] [SecurityPermission(SecurityAction.InheritanceDemand, Unrestricted = true)] void StopProcessing(); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] [SecurityPermission(SecurityAction.InheritanceDemand, Unrestricted = true)] void ProcessRequest( [In, MarshalAs(UnmanagedType.SysInt)] IntPtr tracker, [In, MarshalAs(UnmanagedType.I4)] int verb, [In, MarshalAs(UnmanagedType.LPWStr)] string uri, [In, MarshalAs(UnmanagedType.I4)] int exclusive, [In, MarshalAs(UnmanagedType.I4)] int timeout, [In, MarshalAs(UnmanagedType.I4)] int lockCookieExists, [In, MarshalAs(UnmanagedType.I4)] int lockCookie, [In, MarshalAs(UnmanagedType.I4)] int contentLength, [In, MarshalAs(UnmanagedType.SysInt)] IntPtr content); [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] [SecurityPermission(SecurityAction.InheritanceDemand, Unrestricted = true)] void ProcessRequest( [In, MarshalAs(UnmanagedType.SysInt)] IntPtr tracker, [In, MarshalAs(UnmanagedType.I4)] int verb, [In, MarshalAs(UnmanagedType.LPWStr)] string uri, [In, MarshalAs(UnmanagedType.I4)] int exclusive, [In, MarshalAs(UnmanagedType.I4)] int extraFlags, [In, MarshalAs(UnmanagedType.I4)] int timeout, [In, MarshalAs(UnmanagedType.I4)] int lockCookieExists, [In, MarshalAs(UnmanagedType.I4)] int lockCookie, [In, MarshalAs(UnmanagedType.I4)] int contentLength, [In, MarshalAs(UnmanagedType.SysInt)] IntPtr content); } /// <internalonly/> /// <devdoc> /// </devdoc> [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] public sealed class StateRuntime : IStateRuntime { static StateRuntime() { WebConfigurationFileMap webFileMap = new WebConfigurationFileMap(); UserMapPath mapPath = new UserMapPath(webFileMap); HttpConfigurationSystem.EnsureInit(mapPath, false, true); StateApplication app = new StateApplication(); HttpApplicationFactory.SetCustomApplication(app); PerfCounters.OpenStateCounters(); ResetStateServerCounters(); } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Web.State.StateRuntime'/> /// class. /// </para> /// </devdoc> public StateRuntime() { } /* * Shutdown runtime */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void StopProcessing() { ResetStateServerCounters(); HttpRuntime.Close(); } static void ResetStateServerCounters() { PerfCounters.SetStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_TOTAL, 0); PerfCounters.SetStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ACTIVE, 0); PerfCounters.SetStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_TIMED_OUT, 0); PerfCounters.SetStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ABANDONED, 0); } public void ProcessRequest( IntPtr tracker, int verb, string uri, int exclusive, int timeout, int lockCookieExists, int lockCookie, int contentLength, IntPtr content ) { ProcessRequest( tracker, verb, uri, exclusive, 0, timeout, lockCookieExists, lockCookie, contentLength, content); } /* * Process one ISAPI request * * @param ecb ECB */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ProcessRequest( IntPtr tracker, int verb, string uri, int exclusive, int extraFlags, int timeout, int lockCookieExists, int lockCookie, int contentLength, IntPtr content ) { StateHttpWorkerRequest wr; wr = new StateHttpWorkerRequest( tracker, (UnsafeNativeMethods.StateProtocolVerb) verb, uri, (UnsafeNativeMethods.StateProtocolExclusive) exclusive, extraFlags, timeout, lockCookieExists, lockCookie, contentLength, content); HttpRuntime.ProcessRequest(wr); } } internal static class StateHeaders { internal const String EXCLUSIVE_NAME = "Http_Exclusive"; internal const String EXCLUSIVE_VALUE_ACQUIRE = "acquire"; internal const String EXCLUSIVE_VALUE_RELEASE = "release"; internal const String TIMEOUT_NAME = "Http_Timeout"; internal const String TIMEOUT_NAME_RAW = "Timeout"; internal const String LOCKCOOKIE_NAME = "Http_LockCookie"; internal const String LOCKCOOKIE_NAME_RAW = "LockCookie"; internal const String LOCKDATE_NAME = "Http_LockDate"; internal const String LOCKDATE_NAME_RAW = "LockDate"; internal const String LOCKAGE_NAME = "Http_LockAge"; internal const String LOCKAGE_NAME_RAW = "LockAge"; internal const String EXTRAFLAGS_NAME = "Http_ExtraFlags"; internal const String EXTRAFLAGS_NAME_RAW = "ExtraFlags"; internal const String ACTIONFLAGS_NAME = "Http_ActionFlags"; internal const String ACTIONFLAGS_NAME_RAW = "ActionFlags"; }; internal sealed class CachedContent { internal byte[] _content; internal IntPtr _stateItem; // The pointer to the native memory that points to the psi internal bool _locked; internal DateTime _utcLockDate; internal int _lockCookie; internal int _extraFlags; #pragma warning disable 0649 internal ReadWriteSpinLock _spinLock; #pragma warning restore 0649 internal CachedContent( byte [] content, IntPtr stateItem, bool locked, DateTime utcLockDate, int lockCookie, int extraFlags) { _content = content; _stateItem = stateItem; _locked = locked; _utcLockDate = utcLockDate; _lockCookie = lockCookie; _extraFlags = extraFlags; } } internal class StateApplication : IHttpHandler { CacheItemRemovedCallback _removedHandler; internal StateApplication() { if (!HttpRuntime.IsFullTrust) { // DevDiv #89021: This type passes user-supplied data to unmanaged code, so we need // to ensure that it can only be used from within a FullTrust environment. throw new InvalidOperationException(SR.GetString(SR.StateApplication_FullTrustOnly)); } _removedHandler = new CacheItemRemovedCallback(this.OnCacheItemRemoved); } public void ProcessRequest(HttpContext context) { // Don't send content-type header. context.Response.ContentType = null; switch (context.Request.HttpVerb) { case HttpVerb.GET: DoGet(context); break; case HttpVerb.PUT: DoPut(context); break; case HttpVerb.HEAD: DoHead(context); break; case HttpVerb.DELETE: DoDelete(context); break; default: DoUnknown(context); break; } } public bool IsReusable { get { return true; } } private string CreateKey(HttpRequest request) { return CacheInternal.PrefixStateApplication + HttpUtility.UrlDecode(request.RawUrl); } private void ReportInvalidHeader(HttpContext context, String header) { HttpResponse response; response = context.Response; response.StatusCode = 400; response.Write("<html><head><title>Bad Request</title></head>\r\n"); response.Write("<body><h1>Http/1.1 400 Bad Request</h1>"); response.Write("Invalid header <b>" + header + "</b></body></html>"); } private void ReportLocked(HttpContext context, CachedContent content) { HttpResponse response; DateTime localLockDate; long lockAge; // Note that due to a bug in the RTM state server client, // we cannot add to body of the response when sending this // message, otherwise the client will leak memory. response = context.Response; response.StatusCode = 423; localLockDate = DateTimeUtil.ConvertToLocalTime(content._utcLockDate); lockAge = (DateTime.UtcNow - content._utcLockDate).Ticks / TimeSpan.TicksPerSecond; response.AppendHeader(StateHeaders.LOCKDATE_NAME_RAW, localLockDate.Ticks.ToString(CultureInfo.InvariantCulture)); response.AppendHeader(StateHeaders.LOCKAGE_NAME_RAW, lockAge.ToString(CultureInfo.InvariantCulture)); response.AppendHeader(StateHeaders.LOCKCOOKIE_NAME_RAW, content._lockCookie.ToString(CultureInfo.InvariantCulture)); } private void ReportActionFlags(HttpContext context, int flags) { HttpResponse response; // Note that due to a bug in the RTM state server client, // we cannot add to body of the response when sending this // message, otherwise the client will leak memory. response = context.Response; response.AppendHeader(StateHeaders.ACTIONFLAGS_NAME_RAW, flags.ToString(CultureInfo.InvariantCulture)); } private void ReportNotFound(HttpContext context) { context.Response.StatusCode = 404; } bool GetOptionalNonNegativeInt32HeaderValue(HttpContext context, string header, out int value) { bool headerValid; string valueAsString; value = -1; valueAsString = context.Request.Headers[header]; if (valueAsString == null) { headerValid = true; } else { headerValid = false; try { value = Int32.Parse(valueAsString, CultureInfo.InvariantCulture); if (value >= 0) { headerValid = true; } } catch { } } if (!headerValid) { ReportInvalidHeader(context, header); } return headerValid; } bool GetRequiredNonNegativeInt32HeaderValue(HttpContext context, string header, out int value) { bool headerValid = GetOptionalNonNegativeInt32HeaderValue(context, header, out value); if (headerValid && value == -1) { headerValid = false; ReportInvalidHeader(context, header); } return headerValid; } bool GetOptionalInt32HeaderValue(HttpContext context, string header, out int value, out bool found) { bool headerValid; string valueAsString; found = false; value = 0; valueAsString = context.Request.Headers[header]; if (valueAsString == null) { headerValid = true; } else { headerValid = false; try { value = Int32.Parse(valueAsString, CultureInfo.InvariantCulture); headerValid = true; found = true; } catch { } } if (!headerValid) { ReportInvalidHeader(context, header); } return headerValid; } /* * Check Exclusive header for get, getexlusive, releaseexclusive * use the path as the id * Create the cache key * follow inproc. */ internal /*public*/ void DoGet(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; Stream responseStream; byte[] buf; string exclusiveAccess; string key; CachedContent content; CacheEntry entry; int lockCookie; int timeout; key = CreateKey(request); entry = (CacheEntry) HttpRuntime.CacheInternal.Get(key, CacheGetOptions.ReturnCacheEntry); if (entry == null) { ReportNotFound(context); return; } exclusiveAccess = request.Headers[StateHeaders.EXCLUSIVE_NAME]; content = (CachedContent) entry.Value; content._spinLock.AcquireWriterLock(); try { if (content._content == null) { ReportNotFound(context); return; } int initialFlags; initialFlags = content._extraFlags; if ((initialFlags & (int)SessionStateItemFlags.Uninitialized) != 0) { // It is an uninitialized item. We have to remove that flag. // We only allow one request to do that. // For details, see inline doc for SessionStateItemFlags.Uninitialized flag. // If initialFlags != return value of CompareExchange, it means another request has // removed the flag. if (initialFlags == Interlocked.CompareExchange( ref content._extraFlags, initialFlags & (~((int)SessionStateItemFlags.Uninitialized)), initialFlags)) { ReportActionFlags(context, (int)SessionStateActions.InitializeItem); } } if (exclusiveAccess == StateHeaders.EXCLUSIVE_VALUE_RELEASE) { if (!GetRequiredNonNegativeInt32HeaderValue(context, StateHeaders.LOCKCOOKIE_NAME, out lockCookie)) return; if (content._locked) { if (lockCookie == content._lockCookie) { content._locked = false; } else { ReportLocked(context, content); } } else { // should be locked but isn't. context.Response.StatusCode = 200; } } else { if (content._locked) { ReportLocked(context, content); return; } if (exclusiveAccess == StateHeaders.EXCLUSIVE_VALUE_ACQUIRE) { content._locked = true; content._utcLockDate = DateTime.UtcNow; content._lockCookie++; response.AppendHeader(StateHeaders.LOCKCOOKIE_NAME_RAW, (content._lockCookie).ToString(CultureInfo.InvariantCulture)); } timeout = (int) (entry.SlidingExpiration.Ticks / TimeSpan.TicksPerMinute); response.AppendHeader(StateHeaders.TIMEOUT_NAME_RAW, (timeout).ToString(CultureInfo.InvariantCulture)); responseStream = response.OutputStream; buf = content._content; responseStream.Write(buf, 0, buf.Length); response.Flush(); } } finally { content._spinLock.ReleaseWriterLock(); } } internal /*public*/ void DoPut(HttpContext context) { IntPtr stateItemDelete; stateItemDelete = FinishPut(context); if (stateItemDelete != IntPtr.Zero) { UnsafeNativeMethods.STWNDDeleteStateItem(stateItemDelete); } } unsafe IntPtr FinishPut(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; Stream requestStream; byte[] buf; int timeoutMinutes; TimeSpan timeout; int extraFlags; string key; CachedContent content; CachedContent contentCurrent; int lockCookie; int lockCookieNew = 1; IntPtr stateItem; CacheInternal cacheInternal = HttpRuntime.CacheInternal; /* create the content */ requestStream = request.InputStream; int bufferSize = (int)(requestStream.Length - requestStream.Position); buf = new byte[bufferSize]; requestStream.Read(buf, 0 , buf.Length); fixed (byte * pBuf = buf) { // The ctor of StateHttpWorkerRequest convert the native pointer address // into an array of bytes, and in our we revert it back to an IntPtr stateItem = (IntPtr)(*((void **)pBuf)); } /* get headers */ if (!GetOptionalNonNegativeInt32HeaderValue(context, StateHeaders.TIMEOUT_NAME, out timeoutMinutes)) { return stateItem; } if (timeoutMinutes == -1) { timeoutMinutes = SessionStateModule.TIMEOUT_DEFAULT; } if (timeoutMinutes > SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES) { ReportInvalidHeader(context, StateHeaders.TIMEOUT_NAME); return stateItem; } timeout = new TimeSpan(0, timeoutMinutes, 0); bool found; if (!GetOptionalInt32HeaderValue(context, StateHeaders.EXTRAFLAGS_NAME, out extraFlags, out found)) { return stateItem; } if (!found) { extraFlags = 0; } /* lookup current value */ key = CreateKey(request); CacheEntry entry = (CacheEntry) cacheInternal.Get(key, CacheGetOptions.ReturnCacheEntry); if (entry != null) { // DevDivBugs 146875: Expired Session State race condition // We make sure we do not overwrite an already existing item with an uninitialized item. if (((int)SessionStateItemFlags.Uninitialized & extraFlags) == 1) { return stateItem; } if (!GetOptionalNonNegativeInt32HeaderValue(context, StateHeaders.LOCKCOOKIE_NAME, out lockCookie)) { return stateItem; } contentCurrent = (CachedContent) entry.Value; contentCurrent._spinLock.AcquireWriterLock(); try { if (contentCurrent._content == null) { ReportNotFound(context); return stateItem; } /* Only set the item if we are the owner */ if (contentCurrent._locked && (lockCookie == -1 || lockCookie != contentCurrent._lockCookie)) { ReportLocked(context, contentCurrent); return stateItem; } if (entry.SlidingExpiration == timeout && contentCurrent._content != null) { /* delete the old state item */ IntPtr stateItemOld = contentCurrent._stateItem; /* change the item in place */ contentCurrent._content = buf; contentCurrent._stateItem = stateItem; contentCurrent._locked = false; return stateItemOld; } /* The timeout has changed. In this case, we are removing the old item and inserting a new one. Update _extraFlags to ignore the cache item removed callback (this way, we will not decrease the number of active sessions). */ contentCurrent._extraFlags |= (int)SessionStateItemFlags.IgnoreCacheItemRemoved; /* * If not locked, keep it locked until it is completely replaced. * Prevent overwriting when we drop the lock. */ contentCurrent._locked = true; contentCurrent._lockCookie = 0; lockCookieNew = lockCookie; } finally { contentCurrent._spinLock.ReleaseWriterLock(); } } content = new CachedContent(buf, stateItem, false, DateTime.MinValue, lockCookieNew, extraFlags); cacheInternal.UtcInsert( key, content, null, Cache.NoAbsoluteExpiration, timeout, CacheItemPriority.NotRemovable, _removedHandler); if (entry == null) { IncrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_TOTAL); IncrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ACTIVE); } return IntPtr.Zero; } internal /*public*/ void DoDelete(HttpContext context) { string key = CreateKey(context.Request); CacheInternal cacheInternal = HttpRuntime.CacheInternal; CachedContent content = (CachedContent) cacheInternal.Get(key); /* If the item isn't there, we probably took too long to run. */ if (content == null) { ReportNotFound(context); return; } int lockCookie; if (!GetOptionalNonNegativeInt32HeaderValue(context, StateHeaders.LOCKCOOKIE_NAME, out lockCookie)) return; content._spinLock.AcquireWriterLock(); try { if (content._content == null) { ReportNotFound(context); return; } /* Only remove the item if we are the owner */ if (content._locked && (lockCookie == -1 || content._lockCookie != lockCookie)) { ReportLocked(context, content); return; } /* * If not locked, keep it locked until it is completely removed. * Prevent overwriting when we drop the lock. */ content._locked = true; content._lockCookie = 0; } finally { content._spinLock.ReleaseWriterLock(); } cacheInternal.Remove(key); } internal /*public*/ void DoHead(HttpContext context) { string key; Object item; key = CreateKey(context.Request); item = HttpRuntime.CacheInternal.Get(key); if (item == null) { ReportNotFound(context); } } /* * Unknown Http verb. Responds with "400 Bad Request". * Override this method to report different Http code. */ internal /*public*/ void DoUnknown(HttpContext context) { context.Response.StatusCode = 400; } unsafe void OnCacheItemRemoved(String key, Object value, CacheItemRemovedReason reason) { CachedContent content; IntPtr stateItem; content = (CachedContent) value; content._spinLock.AcquireWriterLock(); try { stateItem = content._stateItem; content._content = null; content._stateItem = IntPtr.Zero; } finally { content._spinLock.ReleaseWriterLock(); } UnsafeNativeMethods.STWNDDeleteStateItem(stateItem); /* If _extraFlags have IgnoreCacheItemRemoved specified, don't update the counters. */ if ((content._extraFlags & (int)SessionStateItemFlags.IgnoreCacheItemRemoved) != 0) { Debug.Trace("OnCacheItemRemoved", "OnCacheItemRemoved ignored (item removed, but counters not updated)"); return; } switch (reason) { case CacheItemRemovedReason.Expired: IncrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_TIMED_OUT); break; case CacheItemRemovedReason.Removed: IncrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ABANDONED); break; default: break; } DecrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ACTIVE); } private void DecrementStateServiceCounter(StateServicePerfCounter counter) { if (HttpRuntime.ShutdownInProgress) { return; } PerfCounters.DecrementStateServiceCounter(counter); } private void IncrementStateServiceCounter(StateServicePerfCounter counter) { if (HttpRuntime.ShutdownInProgress) { return; } PerfCounters.IncrementStateServiceCounter(counter); } } }
// Copyright (c) Morten Nielsen. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using Windows.Devices.Input; using Windows.Foundation.Metadata; using Windows.UI.Xaml; using Windows.UI.Xaml.Markup; namespace WindowsStateTriggers { /// <summary> /// Enables a state based on a collection of other triggers. /// </summary> /// <remarks> /// The CompositeTrigger ONLY supports <see cref="StateTrigger"/> and /// custom triggers implementing <see cref="ITriggerValue"/>. /// </remarks> [ContentProperty(Name = "StateTriggers")] public class CompositeStateTrigger : StateTriggerBase, ITriggerValue { /// <summary> /// Initializes a new instance of the <see cref="CompositeStateTrigger"/> class. /// </summary> public CompositeStateTrigger() { StateTriggers = new StateTriggerCollection(); } private void EvaluateTriggers() { if (!StateTriggers.Any()) { IsActive = false; } else if (Operator == LogicalOperator.Or) { bool result = GetValues().Where(t => t).Any(); IsActive = (result); } else if (Operator == LogicalOperator.And) { bool result = !GetValues().Where(t => !t).Any(); IsActive = (result); } else if (Operator == LogicalOperator.Xor) { bool result = GetValues().Where(t => t).Count() == 1; IsActive = (result); } } private IEnumerable<bool> GetValues() { foreach (var trigger in StateTriggers) { if (trigger is ITriggerValue) { yield return ((ITriggerValue)trigger).IsActive; } else if (trigger is StateTrigger) { yield return ((StateTrigger)trigger).IsActive; //bool? value = null; //try //{ // value = ((StateTrigger)trigger).IsActive; //} //catch { } //if (value.HasValue) // yield return value.Value; } } } private void CompositeTrigger_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { OnTriggerCollectionChanged(e.OldItems == null ? null : e.OldItems.OfType<StateTriggerBase>(), e.OldItems == null ? null : e.NewItems.OfType<StateTriggerBase>()); //TODO: handle reset } private void CompositeStateTrigger_VectorChanged(Windows.Foundation.Collections.IObservableVector<DependencyObject> sender, Windows.Foundation.Collections.IVectorChangedEventArgs e) { if (e.CollectionChange == Windows.Foundation.Collections.CollectionChange.ItemInserted) { var item = sender[(int)e.Index] as StateTriggerBase; if (item != null) { OnTriggerCollectionChanged(null, new StateTriggerBase[] { item }); } } //else: Handle remove and reset } private void OnTriggerCollectionChanged(IEnumerable<StateTriggerBase> oldItems, IEnumerable<StateTriggerBase> newItems) { if (newItems != null) { foreach (var item in newItems) { if (item is StateTrigger) { long id = item.RegisterPropertyChangedCallback( StateTrigger.IsActiveProperty, TriggerIsActivePropertyChanged); item.SetValue(RegistrationTokenProperty, id); } else if (item is ITriggerValue) { ((ITriggerValue)item).IsActiveChanged += CompositeTrigger_IsActiveChanged; } else { throw new NotSupportedException("Only StateTrigger or triggers implementing ITriggerValue are supported in a Composite trigger"); } } } if (oldItems != null) { foreach (var item in oldItems) { if (item is StateTrigger) { var value = item.GetValue(RegistrationTokenProperty); if (value is long) { if (((long)value) > 0) { item.ClearValue(RegistrationTokenProperty); item.UnregisterPropertyChangedCallback(StateTrigger.IsActiveProperty, (long)value); } } } else if (item is ITriggerValue) { ((ITriggerValue)item).IsActiveChanged -= CompositeTrigger_IsActiveChanged; } } } EvaluateTriggers(); } private void CompositeTrigger_IsActiveChanged(object sender, EventArgs e) { EvaluateTriggers(); } private void TriggerIsActivePropertyChanged(DependencyObject sender, DependencyProperty dp) { EvaluateTriggers(); } /// <summary> /// Gets or sets the state trigger collection. /// </summary> public StateTriggerCollection StateTriggers { get { return (StateTriggerCollection)GetValue(StateTriggersProperty); } set { SetValue(StateTriggersProperty, value); } } /// <summary> /// Identifies the <see cref="StateTriggers"/> dependency property /// </summary> private static readonly DependencyProperty StateTriggersProperty = DependencyProperty.Register("StateTriggers", typeof(StateTriggerCollection), typeof(CompositeStateTrigger), new PropertyMetadata(null, OnStateTriggersPropertyChanged)); private static void OnStateTriggersPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CompositeStateTrigger trigger = (CompositeStateTrigger)d; if (e.OldValue is INotifyCollectionChanged) { (e.OldValue as INotifyCollectionChanged).CollectionChanged -= trigger.CompositeTrigger_CollectionChanged; } else if (e.OldValue is Windows.Foundation.Collections.IObservableVector<DependencyObject>) { (e.OldValue as Windows.Foundation.Collections.IObservableVector<DependencyObject>).VectorChanged += trigger.CompositeStateTrigger_VectorChanged; trigger.OnTriggerCollectionChanged((e.NewValue as Windows.Foundation.Collections.IObservableVector<DependencyObject>).OfType<StateTriggerBase>(), null); } if (e.NewValue is INotifyCollectionChanged) { //TODO: Should be weak reference just in case (e.NewValue as INotifyCollectionChanged).CollectionChanged += trigger.CompositeTrigger_CollectionChanged; } else if (e.NewValue is Windows.Foundation.Collections.IObservableVector<DependencyObject>) { (e.NewValue as Windows.Foundation.Collections.IObservableVector<DependencyObject>).VectorChanged += trigger.CompositeStateTrigger_VectorChanged; trigger.OnTriggerCollectionChanged(null, (e.NewValue as Windows.Foundation.Collections.IObservableVector<DependencyObject>).OfType<StateTriggerBase>()); } if (e.NewValue is IEnumerable<StateTriggerBase>) { foreach (var item in e.NewValue as IEnumerable<StateTriggerBase>) { if (!(item is StateTrigger || !(item is ITriggerValue))) { try { throw new NotSupportedException("Only StateTrigger or triggers implementing ITriggerValue are supported in a Composite trigger"); } finally { trigger.SetValue(StateTriggersProperty, e.OldValue); //Undo change } } } trigger.CompositeTrigger_CollectionChanged(e.NewValue, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, (e.NewValue as IEnumerable<StateTriggerBase>).ToList())); } trigger.EvaluateTriggers(); } /// <summary> /// Used for remembering what token was used for event listening /// </summary> private static readonly DependencyProperty RegistrationTokenProperty = DependencyProperty.RegisterAttached("RegistrationToken", typeof(long), typeof(CompositeStateTrigger), new PropertyMetadata(0)); /// <summary> /// Gets or sets the logical operation to apply to the triggers. /// </summary> /// <value>The evaluation.</value> public LogicalOperator Operator { get { return (LogicalOperator)GetValue(OperatorProperty); } set { SetValue(OperatorProperty, value); } } /// <summary> /// Identifies the <see cref="Operator"/> dependency property /// </summary> public static readonly DependencyProperty OperatorProperty = DependencyProperty.Register("Operator", typeof(LogicalOperator), typeof(CompositeStateTrigger), new PropertyMetadata(LogicalOperator.And, OnEvaluatePropertyChanged)); private static void OnEvaluatePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CompositeStateTrigger trigger = (CompositeStateTrigger)d; trigger.EvaluateTriggers(); } #region ITriggerValue private bool m_IsActive; /// <summary> /// Gets a value indicating whether this trigger is active. /// </summary> /// <value><c>true</c> if this trigger is active; otherwise, <c>false</c>.</value> public bool IsActive { get { return m_IsActive; } private set { if (m_IsActive != value) { m_IsActive = value; base.SetActive(value); if (IsActiveChanged != null) IsActiveChanged(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the <see cref="IsActive" /> property has changed. /// </summary> public event EventHandler IsActiveChanged; #endregion ITriggerValue } /// <summary> /// Logical operations /// </summary> public enum LogicalOperator { /// <summary> /// And (All must be active) /// </summary> And, /// <summary> /// Or (Any can be active) /// </summary> Or, /// <summary> /// Exclusive-Or (only one can be active) /// </summary> Xor } /// <summary> /// Collection for the <see cref="CompositeStateTrigger"/>. /// </summary> public sealed class StateTriggerCollection : DependencyObjectCollection { } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// PaymentsWepayEnroll /// </summary> [DataContract] public partial class PaymentsWepayEnroll : IEquatable<PaymentsWepayEnroll>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PaymentsWepayEnroll" /> class. /// </summary> /// <param name="address1">address1.</param> /// <param name="address2">address2.</param> /// <param name="canadaAcceptDebitCards">canadaAcceptDebitCards.</param> /// <param name="city">city.</param> /// <param name="company">company.</param> /// <param name="companyDescription">companyDescription.</param> /// <param name="country">country.</param> /// <param name="expectedRevenue">expectedRevenue.</param> /// <param name="industry">industry.</param> /// <param name="ownerEmail">ownerEmail.</param> /// <param name="ownerName">ownerName.</param> /// <param name="ownerPhone">ownerPhone.</param> /// <param name="state">state.</param> /// <param name="webisteUrl">webisteUrl.</param> /// <param name="zip">zip.</param> public PaymentsWepayEnroll(string address1 = default(string), string address2 = default(string), bool? canadaAcceptDebitCards = default(bool?), string city = default(string), string company = default(string), string companyDescription = default(string), string country = default(string), string expectedRevenue = default(string), string industry = default(string), string ownerEmail = default(string), string ownerName = default(string), string ownerPhone = default(string), string state = default(string), string webisteUrl = default(string), string zip = default(string)) { this.Address1 = address1; this.Address2 = address2; this.CanadaAcceptDebitCards = canadaAcceptDebitCards; this.City = city; this.Company = company; this.CompanyDescription = companyDescription; this.Country = country; this.ExpectedRevenue = expectedRevenue; this.Industry = industry; this.OwnerEmail = ownerEmail; this.OwnerName = ownerName; this.OwnerPhone = ownerPhone; this.State = state; this.WebisteUrl = webisteUrl; this.Zip = zip; } /// <summary> /// Gets or Sets Address1 /// </summary> [DataMember(Name="address1", EmitDefaultValue=false)] public string Address1 { get; set; } /// <summary> /// Gets or Sets Address2 /// </summary> [DataMember(Name="address2", EmitDefaultValue=false)] public string Address2 { get; set; } /// <summary> /// Gets or Sets CanadaAcceptDebitCards /// </summary> [DataMember(Name="canada_accept_debit_cards", EmitDefaultValue=false)] public bool? CanadaAcceptDebitCards { get; set; } /// <summary> /// Gets or Sets City /// </summary> [DataMember(Name="city", EmitDefaultValue=false)] public string City { get; set; } /// <summary> /// Gets or Sets Company /// </summary> [DataMember(Name="company", EmitDefaultValue=false)] public string Company { get; set; } /// <summary> /// Gets or Sets CompanyDescription /// </summary> [DataMember(Name="company_description", EmitDefaultValue=false)] public string CompanyDescription { get; set; } /// <summary> /// Gets or Sets Country /// </summary> [DataMember(Name="country", EmitDefaultValue=false)] public string Country { get; set; } /// <summary> /// Gets or Sets ExpectedRevenue /// </summary> [DataMember(Name="expected_revenue", EmitDefaultValue=false)] public string ExpectedRevenue { get; set; } /// <summary> /// Gets or Sets Industry /// </summary> [DataMember(Name="industry", EmitDefaultValue=false)] public string Industry { get; set; } /// <summary> /// Gets or Sets OwnerEmail /// </summary> [DataMember(Name="owner_email", EmitDefaultValue=false)] public string OwnerEmail { get; set; } /// <summary> /// Gets or Sets OwnerName /// </summary> [DataMember(Name="owner_name", EmitDefaultValue=false)] public string OwnerName { get; set; } /// <summary> /// Gets or Sets OwnerPhone /// </summary> [DataMember(Name="owner_phone", EmitDefaultValue=false)] public string OwnerPhone { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name="state", EmitDefaultValue=false)] public string State { get; set; } /// <summary> /// Gets or Sets WebisteUrl /// </summary> [DataMember(Name="webiste_url", EmitDefaultValue=false)] public string WebisteUrl { get; set; } /// <summary> /// Gets or Sets Zip /// </summary> [DataMember(Name="zip", EmitDefaultValue=false)] public string Zip { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PaymentsWepayEnroll {\n"); sb.Append(" Address1: ").Append(Address1).Append("\n"); sb.Append(" Address2: ").Append(Address2).Append("\n"); sb.Append(" CanadaAcceptDebitCards: ").Append(CanadaAcceptDebitCards).Append("\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" Company: ").Append(Company).Append("\n"); sb.Append(" CompanyDescription: ").Append(CompanyDescription).Append("\n"); sb.Append(" Country: ").Append(Country).Append("\n"); sb.Append(" ExpectedRevenue: ").Append(ExpectedRevenue).Append("\n"); sb.Append(" Industry: ").Append(Industry).Append("\n"); sb.Append(" OwnerEmail: ").Append(OwnerEmail).Append("\n"); sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); sb.Append(" OwnerPhone: ").Append(OwnerPhone).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" WebisteUrl: ").Append(WebisteUrl).Append("\n"); sb.Append(" Zip: ").Append(Zip).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PaymentsWepayEnroll); } /// <summary> /// Returns true if PaymentsWepayEnroll instances are equal /// </summary> /// <param name="input">Instance of PaymentsWepayEnroll to be compared</param> /// <returns>Boolean</returns> public bool Equals(PaymentsWepayEnroll input) { if (input == null) return false; return ( this.Address1 == input.Address1 || (this.Address1 != null && this.Address1.Equals(input.Address1)) ) && ( this.Address2 == input.Address2 || (this.Address2 != null && this.Address2.Equals(input.Address2)) ) && ( this.CanadaAcceptDebitCards == input.CanadaAcceptDebitCards || (this.CanadaAcceptDebitCards != null && this.CanadaAcceptDebitCards.Equals(input.CanadaAcceptDebitCards)) ) && ( this.City == input.City || (this.City != null && this.City.Equals(input.City)) ) && ( this.Company == input.Company || (this.Company != null && this.Company.Equals(input.Company)) ) && ( this.CompanyDescription == input.CompanyDescription || (this.CompanyDescription != null && this.CompanyDescription.Equals(input.CompanyDescription)) ) && ( this.Country == input.Country || (this.Country != null && this.Country.Equals(input.Country)) ) && ( this.ExpectedRevenue == input.ExpectedRevenue || (this.ExpectedRevenue != null && this.ExpectedRevenue.Equals(input.ExpectedRevenue)) ) && ( this.Industry == input.Industry || (this.Industry != null && this.Industry.Equals(input.Industry)) ) && ( this.OwnerEmail == input.OwnerEmail || (this.OwnerEmail != null && this.OwnerEmail.Equals(input.OwnerEmail)) ) && ( this.OwnerName == input.OwnerName || (this.OwnerName != null && this.OwnerName.Equals(input.OwnerName)) ) && ( this.OwnerPhone == input.OwnerPhone || (this.OwnerPhone != null && this.OwnerPhone.Equals(input.OwnerPhone)) ) && ( this.State == input.State || (this.State != null && this.State.Equals(input.State)) ) && ( this.WebisteUrl == input.WebisteUrl || (this.WebisteUrl != null && this.WebisteUrl.Equals(input.WebisteUrl)) ) && ( this.Zip == input.Zip || (this.Zip != null && this.Zip.Equals(input.Zip)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Address1 != null) hashCode = hashCode * 59 + this.Address1.GetHashCode(); if (this.Address2 != null) hashCode = hashCode * 59 + this.Address2.GetHashCode(); if (this.CanadaAcceptDebitCards != null) hashCode = hashCode * 59 + this.CanadaAcceptDebitCards.GetHashCode(); if (this.City != null) hashCode = hashCode * 59 + this.City.GetHashCode(); if (this.Company != null) hashCode = hashCode * 59 + this.Company.GetHashCode(); if (this.CompanyDescription != null) hashCode = hashCode * 59 + this.CompanyDescription.GetHashCode(); if (this.Country != null) hashCode = hashCode * 59 + this.Country.GetHashCode(); if (this.ExpectedRevenue != null) hashCode = hashCode * 59 + this.ExpectedRevenue.GetHashCode(); if (this.Industry != null) hashCode = hashCode * 59 + this.Industry.GetHashCode(); if (this.OwnerEmail != null) hashCode = hashCode * 59 + this.OwnerEmail.GetHashCode(); if (this.OwnerName != null) hashCode = hashCode * 59 + this.OwnerName.GetHashCode(); if (this.OwnerPhone != null) hashCode = hashCode * 59 + this.OwnerPhone.GetHashCode(); if (this.State != null) hashCode = hashCode * 59 + this.State.GetHashCode(); if (this.WebisteUrl != null) hashCode = hashCode * 59 + this.WebisteUrl.GetHashCode(); if (this.Zip != null) hashCode = hashCode * 59 + this.Zip.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using Android.Content; using Android.Graphics; using Android.Runtime; using Android.Util; using Android.Views; using System; using System.Collections.Immutable; using System.Linq; using Toggl.Droid.Extensions; using Toggl.Droid.ViewHelpers; using Toggl.Shared; using Color = Android.Graphics.Color; using static Toggl.Core.UI.ViewModels.Reports.ReportBarChartElement; using Math = System.Math; namespace Toggl.Droid.Views { [Register("toggl.droid.views.BarChartView")] public class BarChartView : View { private const float barDrawingYTranslationAdjustmentInPixels = 1f; private const float defaultBarSpacingRatio = 0.2f; private const float minHeightForBarsWithPercentages = 1f; private readonly Paint filledValuePaint = new Paint(); private readonly Paint regularValuePaint = new Paint(); private readonly Paint filledValuePlaceholderPaint = new Paint(); private readonly Paint regularValuePlaceholderPaint = new Paint(); private readonly Paint othersPaint = new Paint(); private readonly Rect bounds = new Rect(); private float maxWidth; private float barsRightMargin; private float barsLeftMargin; private float barsBottomMargin; private float barsTopMargin; private float textSize; private float textLeftMargin; private float textBottomMargin; private float bottomLabelMarginTop; private float dateTopPadding; private int barsCount; private bool willDrawBarChart; private float barsWidth; private float barsHeight; private float actualBarWidth; private int spaces; private float totalWidth; private float remainingWidth; private float spacing; private float requiredWidth; private float middleHorizontalLineY; private float barsBottom; private float hoursLabelsX; private float hoursBottomMargin; private bool willDrawIndividualLabels; private float startEndDatesY; private float barsStartingLeft; private bool shouldDrawEmptyState; private IImmutableList<Bar> bars; private IImmutableList<string> xLabels; private YAxisLabels yLabels; private double maxValue; private string startDate; private string endDate; private float dayLabelsY; private IImmutableList<Bar> placeholderBars = generatePlaceholderBars(); private static YAxisLabels placeholderYLabels = new YAxisLabels("10 h", "5 h", "0 h"); private static IImmutableList<string> placeholderXLabels = new string[] { "", "" }.ToImmutableList(); private bool isDrawingPlaceholders() => bars == placeholderBars; public BarChartView(Context context) : base(context) { initialize(context); } public BarChartView(Context context, IAttributeSet attrs) : base(context, attrs) { initialize(context); var customAttrs = Context.ObtainStyledAttributes(attrs, Resource.Styleable.BarChartView, 0, 0); try { shouldDrawEmptyState = customAttrs.GetBoolean(Resource.Styleable.BarChartView_drawEmptyState, false); if (shouldDrawEmptyState) { bars = placeholderBars = generateEmptyStateBars(); xLabels = new[] {"01/04", "30/04"}.ToImmutableList(); yLabels = YAxisLabels.Empty; updateBarChartDrawingData(); } } finally { customAttrs.Recycle(); } } protected BarChartView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } private Color horizontalLineColor; private Color hoursTextColor; private Color emptyBarColor; private Color xAxisLegendColor; private void initialize(Context context) { maxWidth = 48.DpToPixels(context); barsRightMargin = 40.DpToPixels(context); barsLeftMargin = 12.DpToPixels(context); barsBottomMargin = 40.DpToPixels(context); barsTopMargin = 18.DpToPixels(context); textSize = 12.SpToPixels(context); textLeftMargin = 12.DpToPixels(context); textBottomMargin = 4.DpToPixels(context); bottomLabelMarginTop = 12.DpToPixels(context); dateTopPadding = 4.DpToPixels(context); othersPaint.TextSize = textSize; filledValuePaint.Color = context.SafeGetColor(Resource.Color.filledChartBar); regularValuePaint.Color = context.SafeGetColor(Resource.Color.regularChartBar); filledValuePlaceholderPaint.Color = context.SafeGetColor(Resource.Color.placeholderBarFilled); regularValuePlaceholderPaint.Color = context.SafeGetColor(Resource.Color.placeholderBarRegular); regularValuePaint.SetStyle(Paint.Style.FillAndStroke); filledValuePaint.SetStyle(Paint.Style.FillAndStroke); regularValuePlaceholderPaint.SetStyle(Paint.Style.FillAndStroke); filledValuePlaceholderPaint.SetStyle(Paint.Style.FillAndStroke); emptyBarColor = context.SafeGetColor(Resource.Color.placeholderText); horizontalLineColor = context.SafeGetColor(Resource.Color.separator); hoursTextColor = context.SafeGetColor(Resource.Color.placeholderText); xAxisLegendColor = context.SafeGetColor(Resource.Color.secondaryText); } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); updateBarChartDrawingData(); PostInvalidate(); } public void updateBars(IImmutableList<Bar> newBars, double maxValue, IImmutableList<string> xLabels, YAxisLabels yLabels) { this.maxValue = maxValue; bars = newBars; this.yLabels = yLabels; this.xLabels = xLabels; updateBarChartDrawingData(); PostInvalidate(); } private void updateBarChartDrawingData() { if (shouldDrawEmptyState) { barsRightMargin = barsLeftMargin; } if (bars == null) { willDrawBarChart = false; return; } barsCount = bars.Count; willDrawBarChart = barsCount > 0; if (!willDrawBarChart) return; startDate = xLabels[0]; endDate = xLabels[xLabels.Count - 1]; barsWidth = MeasuredWidth - barsLeftMargin - barsRightMargin; barsHeight = MeasuredHeight - barsTopMargin - barsBottomMargin; var idealBarWidth = Math.Min(barsWidth / barsCount, maxWidth); spaces = barsCount - 1; totalWidth = idealBarWidth * barsCount; remainingWidth = barsWidth - totalWidth; spacing = Math.Max(remainingWidth / barsCount, idealBarWidth * defaultBarSpacingRatio); requiredWidth = totalWidth + spaces * spacing; actualBarWidth = requiredWidth > barsWidth ? idealBarWidth * (1 - defaultBarSpacingRatio) : idealBarWidth; middleHorizontalLineY = barsHeight / 2f + barsTopMargin; barsBottom = MeasuredHeight - barsBottomMargin; hoursLabelsX = MeasuredWidth - barsRightMargin + textLeftMargin; hoursBottomMargin = textBottomMargin * 2f; willDrawIndividualLabels = xLabels.Count > 2; startEndDatesY = barsBottom + bottomLabelMarginTop * 2f; dayLabelsY = barsBottom + bottomLabelMarginTop * 1.25f; barsStartingLeft = barsLeftMargin + (barsWidth - (actualBarWidth * barsCount + spaces * spacing)) / 2f; } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); if (!willDrawBarChart) { bars = placeholderBars; xLabels = placeholderXLabels; yLabels = placeholderYLabels; maxValue = placeholderBars.Max(bar => bar.TotalValue); updateBarChartDrawingData(); } drawHorizontalLines(canvas); drawYAxisLegend(canvas); drawXAxisLegendIfNotDrawingIndividualLabels(canvas); drawBarsAndXAxisLegend(canvas); } private void drawHorizontalLines(Canvas canvas) { if (shouldDrawEmptyState) { //We do need the bottom one though canvas.DrawLine(0f, barsBottom, Width, barsBottom, othersPaint); return; } othersPaint.Color = horizontalLineColor; canvas.DrawLine(0f, barsTopMargin, Width, barsTopMargin, othersPaint); canvas.DrawLine(0f, middleHorizontalLineY, Width, middleHorizontalLineY, othersPaint); canvas.DrawLine(0f, barsBottom, Width, barsBottom, othersPaint); } private void drawYAxisLegend(Canvas canvas) { othersPaint.Color = hoursTextColor; canvas.DrawText(yLabels.BottomLabel, hoursLabelsX, barsBottom - hoursBottomMargin, othersPaint); canvas.DrawText(yLabels.MiddleLabel, hoursLabelsX, middleHorizontalLineY - hoursBottomMargin, othersPaint); canvas.DrawText(yLabels.TopLabel, hoursLabelsX, barsTopMargin - hoursBottomMargin, othersPaint); } private void drawXAxisLegendIfNotDrawingIndividualLabels(Canvas canvas) { if (!willDrawIndividualLabels && (!isDrawingPlaceholders() || shouldDrawEmptyState)) { othersPaint.Color = xAxisLegendColor; othersPaint.TextAlign = Paint.Align.Left; canvas.DrawText(startDate, barsLeftMargin, startEndDatesY, othersPaint); othersPaint.TextAlign = Paint.Align.Right; canvas.DrawText(endDate, Width - barsRightMargin, startEndDatesY, othersPaint); } } private void drawBarsAndXAxisLegend(Canvas canvas) { var left = barsStartingLeft; othersPaint.TextAlign = Paint.Align.Center; var originalTextSize = othersPaint.TextSize; var barsToRender = bars; var labelsToRender = xLabels; var numberOfLabels = xLabels.Count; var filledPaintToUse = isDrawingPlaceholders() ? filledValuePlaceholderPaint : filledValuePaint; var regularPaintToUse = isDrawingPlaceholders() ? regularValuePlaceholderPaint : regularValuePaint; for (var i = 0; i < barsToRender.Count; i++) { var bar = barsToRender[i]; var barRight = left + actualBarWidth; var barHasFilledPercentage = bar.FilledValue > 0; var barHasTransparentPercentage = bar.TotalValue > bar.FilledValue; if (!barHasFilledPercentage && !barHasTransparentPercentage) { othersPaint.Color = emptyBarColor; canvas.DrawLine(left, barsBottom, barRight, barsBottom, othersPaint); } else { var filledBarHeight = (float)(barsHeight * bar.FilledValue); var filledTop = calculateFilledTop(filledBarHeight, barHasFilledPercentage); canvas.DrawRect(left, filledTop, barRight, barsBottom + barDrawingYTranslationAdjustmentInPixels, filledPaintToUse); var regularBarHeight = (float)(barsHeight * (bar.TotalValue - bar.FilledValue)); var regularTop = calculateRegularTop(filledTop, regularBarHeight, barHasTransparentPercentage); canvas.DrawRect(left, regularTop, barRight, filledTop, regularPaintToUse); } if (willDrawIndividualLabels && i < numberOfLabels) { var horizontalLabelElements = labelsToRender[i].Split("\n"); if (horizontalLabelElements.Length == 2) { othersPaint.Color = xAxisLegendColor; var middleOfTheBar = left + (barRight - left) / 2f; var dayOfWeekText = horizontalLabelElements[1]; othersPaint.TextSize = originalTextSize; canvas.DrawText(dayOfWeekText, middleOfTheBar, dayLabelsY, othersPaint); var dateText = horizontalLabelElements[0]; othersPaint.UpdatePaintForTextToFitWidth(dateText, actualBarWidth, bounds); othersPaint.GetTextBounds(dateText, 0, dateText.Length, bounds); canvas.DrawText(dateText, middleOfTheBar, dayLabelsY + bounds.Height() + dateTopPadding, othersPaint); } } left += actualBarWidth + spacing; } } private float calculateFilledTop(float filledBarHeight, bool barHasFilledPercentage) { var filledTop = barsBottom - filledBarHeight + barDrawingYTranslationAdjustmentInPixels; var barHasAtLeast1PixelInHeight = filledBarHeight >= minHeightForBarsWithPercentages; return barHasFilledPercentage && !barHasAtLeast1PixelInHeight ? filledTop - minHeightForBarsWithPercentages : filledTop; } private float calculateRegularTop(float filledTop, float regularBarHeight, bool barHasRegularPercentage) { //Regular top doesn't need the extra Y translation because the filledTop accounts for it. var regularTop = filledTop - regularBarHeight; var barHasAtLeast1PixelInHeight = regularBarHeight >= minHeightForBarsWithPercentages; return barHasRegularPercentage && !barHasAtLeast1PixelInHeight ? regularTop - minHeightForBarsWithPercentages : regularTop; } private static IImmutableList<Bar> generatePlaceholderBars() { var maxTotal = 78.2 + 67.3; return new (double Filled, double Regular)[] { (12.4, 6.9), (7.6, 13.5), (12.4, 6.9), (15.1, 18.9), (15.1, 20.1), (14.6, 24.5), (9.5, 28.2), (11.3, 23.9), (11.5, 32.9), (10.5, 22.8), (35.5, 24.5), (36.1, 24.2), (41.5, 31.2), (40, 33.3), (8.3, 43), (39.9, 35.6), (10, 50.9), (14.2, 46.7), (39.7, 50.2), (40.8, 44), (7.6, 43.9), (56.1, 55.7), (52.7, 53.2), (66.5, 50.7), (53.3, 54.6), (59, 64), (73, 61), (71.1, 70), (73.8, 72), (64.5, 79.8), (78.2, 67.3), } .Select(tuple => new Bar(tuple.Filled / maxTotal, (tuple.Filled + tuple.Regular) / maxTotal)) .ToImmutableList(); } private static IImmutableList<Bar> generateEmptyStateBars() => new[] { 3, 10, 3, 9, 10, 9, 14, 8, 11, 13, 14, 16, 20, 20, 41, 44, 37, 21, 39, 43, 32, 39, 31, 28, 36, 36, 41, 38, 37, 38 } .Select(height => new Bar( height, height).Scaled(100)) .ToImmutableList(); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias WORKSPACES; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { using RelativePathResolver = WORKSPACES::Microsoft.CodeAnalysis.RelativePathResolver; public partial class TestWorkspace { /// <summary> /// This place-holder value is used to set a project's file path to be null. It was explicitly chosen to be /// convoluted to avoid any accidental usage (e.g., what if I really wanted FilePath to be the string "null"?), /// obvious to anybody debugging that it is a special value, and invalid as an actual file path. /// </summary> public const string NullFilePath = "NullFilePath::{AFA13775-BB7D-4020-9E58-C68CF43D8A68}"; private class TestDocumentationProvider : DocumentationProvider { protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken)) { return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID); } public override bool Equals(object obj) { return (object)this == obj; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } public static TestWorkspace Create(string xmlDefinition, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null) { return Create(XElement.Parse(xmlDefinition), completed, openDocuments, exportProvider); } public static TestWorkspace CreateWorkspace( XElement workspaceElement, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null, string workspaceKind = null) { return Create(workspaceElement, completed, openDocuments, exportProvider, workspaceKind); } public static TestWorkspace Create( XElement workspaceElement, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null, string workspaceKind = null) { if (workspaceElement.Name != WorkspaceElementName) { throw new ArgumentException(); } exportProvider = exportProvider ?? TestExportProvider.ExportProviderWithCSharpAndVisualBasic; var workspace = new TestWorkspace(exportProvider, workspaceKind); var projectNameToTestHostProject = new Dictionary<string, TestHostProject>(); var documentElementToFilePath = new Dictionary<XElement, string>(); var projectElementToProjectName = new Dictionary<XElement, string>(); var filePathToTextBufferMap = new Dictionary<string, ITextBuffer>(); int projectIdentifier = 0; int documentIdentifier = 0; foreach (var projectElement in workspaceElement.Elements(ProjectElementName)) { var project = CreateProject( workspaceElement, projectElement, exportProvider, workspace, documentElementToFilePath, filePathToTextBufferMap, ref projectIdentifier, ref documentIdentifier); Assert.False(projectNameToTestHostProject.ContainsKey(project.Name), $"The workspace XML already contains a project with name {project.Name}"); projectNameToTestHostProject.Add(project.Name, project); projectElementToProjectName.Add(projectElement, project.Name); workspace.Projects.Add(project); } var documentFilePaths = new HashSet<string>(); foreach (var project in projectNameToTestHostProject.Values) { foreach (var document in project.Documents) { Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath)); } } var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider); foreach (var submission in submissions) { projectNameToTestHostProject.Add(submission.Name, submission); } var solution = new TestHostSolution(projectNameToTestHostProject.Values.ToArray()); workspace.AddTestSolution(solution); foreach (var projectElement in workspaceElement.Elements(ProjectElementName)) { foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName)) { var fromName = projectElementToProjectName[projectElement]; var toName = projectReference.Value; var fromProject = projectNameToTestHostProject[fromName]; var toProject = projectNameToTestHostProject[toName]; var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray(); workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default(ImmutableArray<string>))); } } for (int i = 1; i < submissions.Count; i++) { if (submissions[i].CompilationOptions == null) { continue; } for (int j = i - 1; j >= 0; j--) { if (submissions[j].CompilationOptions != null) { workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[j].Id)); break; } } } foreach (var project in projectNameToTestHostProject.Values) { foreach (var document in project.Documents) { if (openDocuments) { workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile); } workspace.Documents.Add(document); } } return workspace; } private static IList<TestHostProject> CreateSubmissions( TestWorkspace workspace, IEnumerable<XElement> submissionElements, ExportProvider exportProvider) { var submissions = new List<TestHostProject>(); var submissionIndex = 0; foreach (var submissionElement in submissionElements) { var submissionName = "Submission" + (submissionIndex++); var languageName = GetLanguage(workspace, submissionElement); // The document var markupCode = submissionElement.NormalizedValue(); MarkupTestFile.GetPositionAndSpans(markupCode, out var code, out var cursorPosition, out IDictionary<string, ImmutableArray<TextSpan>> spans); var languageServices = workspace.Services.GetLanguageServices(languageName); var contentTypeLanguageService = languageServices.GetService<IContentTypeLanguageService>(); var contentType = contentTypeLanguageService.GetDefaultContentType(); var textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code); // The project var document = new TestHostDocument(exportProvider, languageServices, textBuffer, submissionName, cursorPosition, spans, SourceCodeKind.Script); var documents = new List<TestHostDocument> { document }; if (languageName == NoCompilationConstants.LanguageName) { submissions.Add( new TestHostProject( languageServices, compilationOptions: null, parseOptions: null, assemblyName: submissionName, projectName: submissionName, references: null, documents: documents, isSubmission: true)); continue; } var syntaxFactory = languageServices.GetService<ISyntaxTreeFactoryService>(); var compilationFactory = languageServices.GetService<ICompilationFactoryService>(); var compilationOptions = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var parseOptions = syntaxFactory.GetDefaultParseOptions().WithKind(SourceCodeKind.Script); var references = CreateCommonReferences(workspace, submissionElement); var project = new TestHostProject( languageServices, compilationOptions, parseOptions, submissionName, submissionName, references, documents, isSubmission: true); submissions.Add(project); } return submissions; } private static TestHostProject CreateProject( XElement workspaceElement, XElement projectElement, ExportProvider exportProvider, TestWorkspace workspace, Dictionary<XElement, string> documentElementToFilePath, Dictionary<string, ITextBuffer> filePathToTextBufferMap, ref int projectId, ref int documentId) { var language = GetLanguage(workspace, projectElement); var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId); string filePath; string projectName = projectElement.Attribute(ProjectNameAttribute)?.Value ?? assemblyName; if (projectElement.Attribute(FilePathAttributeName) != null) { filePath = projectElement.Attribute(FilePathAttributeName).Value; if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0) { // allow explicit null file path filePath = null; } } else { filePath = projectName + (language == LanguageNames.CSharp ? ".csproj" : language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language)); } var contentTypeRegistryService = exportProvider.GetExportedValue<IContentTypeRegistryService>(); var languageServices = workspace.Services.GetLanguageServices(language); var parseOptions = GetParseOptions(projectElement, language, languageServices); var compilationOptions = CreateCompilationOptions(workspace, projectElement, language, parseOptions); var references = CreateReferenceList(workspace, projectElement); var analyzers = CreateAnalyzerList(workspace, projectElement); var documents = new List<TestHostDocument>(); var documentElements = projectElement.Elements(DocumentElementName).ToList(); foreach (var documentElement in documentElements) { var document = CreateDocument( workspace, workspaceElement, documentElement, language, exportProvider, languageServices, filePathToTextBufferMap, ref documentId); documents.Add(document); documentElementToFilePath.Add(documentElement, document.FilePath); } return new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, projectName, references, documents, filePath: filePath, analyzerReferences: analyzers); } private static ParseOptions GetParseOptions(XElement projectElement, string language, HostLanguageServices languageServices) { return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic ? GetParseOptionsWorker(projectElement, language, languageServices) : null; } private static ParseOptions GetParseOptionsWorker(XElement projectElement, string language, HostLanguageServices languageServices) { ParseOptions parseOptions; var preprocessorSymbolsAttribute = projectElement.Attribute(PreprocessorSymbolsAttributeName); if (preprocessorSymbolsAttribute != null) { parseOptions = GetPreProcessorParseOptions(language, preprocessorSymbolsAttribute); } else { parseOptions = languageServices.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions(); } var languageVersionAttribute = projectElement.Attribute(LanguageVersionAttributeName); if (languageVersionAttribute != null) { parseOptions = GetParseOptionsWithLanguageVersion(language, parseOptions, languageVersionAttribute); } var featuresAttribute = projectElement.Attribute(FeaturesAttributeName); if (featuresAttribute != null) { parseOptions = GetParseOptionsWithFeatures(parseOptions, featuresAttribute); } var documentationMode = GetDocumentationMode(projectElement); if (documentationMode != null) { parseOptions = parseOptions.WithDocumentationMode(documentationMode.Value); } return parseOptions; } private static ParseOptions GetPreProcessorParseOptions(string language, XAttribute preprocessorSymbolsAttribute) { if (language == LanguageNames.CSharp) { return new CSharpParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value.Split(',')); } else if (language == LanguageNames.VisualBasic) { return new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value .Split(',').Select(v => KeyValuePair.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray()); } else { throw new ArgumentException("Unexpected language '{0}' for generating custom parse options.", language); } } private static ParseOptions GetParseOptionsWithFeatures(ParseOptions parseOptions, XAttribute featuresAttribute) { var entries = featuresAttribute.Value.Split(';'); var features = entries.Select(x => { var split = x.Split('='); var key = split[0]; var value = split.Length == 2 ? split[1] : "true"; return new KeyValuePair<string, string>(key, value); }); return parseOptions.WithFeatures(features); } private static ParseOptions GetParseOptionsWithLanguageVersion(string language, ParseOptions parseOptions, XAttribute languageVersionAttribute) { if (language == LanguageNames.CSharp) { var languageVersion = (CodeAnalysis.CSharp.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.CSharp.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion); } else if (language == LanguageNames.VisualBasic) { var languageVersion = (CodeAnalysis.VisualBasic.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.VisualBasic.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((VisualBasicParseOptions)parseOptions).WithLanguageVersion(languageVersion); } return parseOptions; } private static DocumentationMode? GetDocumentationMode(XElement projectElement) { var documentationModeAttribute = projectElement.Attribute(DocumentationModeAttributeName); if (documentationModeAttribute != null) { return (DocumentationMode)Enum.Parse(typeof(DocumentationMode), documentationModeAttribute.Value); } else { return null; } } private static string GetAssemblyName(TestWorkspace workspace, XElement projectElement, ref int projectId) { var assemblyNameAttribute = projectElement.Attribute(AssemblyNameAttributeName); if (assemblyNameAttribute != null) { return assemblyNameAttribute.Value; } var language = GetLanguage(workspace, projectElement); projectId++; return language == LanguageNames.CSharp ? "CSharpAssembly" + projectId : language == LanguageNames.VisualBasic ? "VisualBasicAssembly" + projectId : language + "Assembly" + projectId; } private static string GetLanguage(TestWorkspace workspace, XElement projectElement) { string languageName = projectElement.Attribute(LanguageAttributeName).Value; if (!workspace.Services.SupportedLanguages.Contains(languageName)) { throw new ArgumentException(string.Format("Language should be one of '{0}' and it is {1}", string.Join(", ", workspace.Services.SupportedLanguages), languageName)); } return languageName; } private static CompilationOptions CreateCompilationOptions( TestWorkspace workspace, XElement projectElement, string language, ParseOptions parseOptions) { var compilationOptionsElement = projectElement.Element(CompilationOptionsElementName); return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic ? CreateCompilationOptions(workspace, language, compilationOptionsElement, parseOptions) : null; } private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement, ParseOptions parseOptions) { var rootNamespace = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace; var globalImports = new List<GlobalImport>(); var reportDiagnostic = ReportDiagnostic.Default; if (compilationOptionsElement != null) { globalImports = compilationOptionsElement.Elements(GlobalImportElementName) .Select(x => GlobalImport.Parse(x.Value)).ToList(); var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName); if (rootNamespaceAttribute != null) { rootNamespace = rootNamespaceAttribute.Value; } var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName); if (reportDiagnosticAttribute != null) { reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute); } var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName); if (outputTypeAttribute != null && outputTypeAttribute.Value == "WindowsRuntimeMetadata") { if (rootNamespaceAttribute == null) { rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace; } // VB needs Compilation.ParseOptions set (we do the same at the VS layer) return language == LanguageNames.CSharp ? (CompilationOptions)new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata) : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports).WithRootNamespace(rootNamespace) .WithParseOptions((VisualBasicParseOptions)parseOptions ?? VisualBasicParseOptions.Default); } } else { // Add some common global imports by default for VB globalImports.Add(GlobalImport.Parse("System")); globalImports.Add(GlobalImport.Parse("System.Collections.Generic")); globalImports.Add(GlobalImport.Parse("System.Linq")); } // TODO: Allow these to be specified. var languageServices = workspace.Services.GetLanguageServices(language); var metadataService = workspace.Services.GetService<IMetadataService>(); var compilationOptions = languageServices.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions(); compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary) .WithGeneralDiagnosticOption(reportDiagnostic) .WithSourceReferenceResolver(SourceFileResolver.Default) .WithXmlReferenceResolver(XmlFileResolver.Default) .WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray<string>.Empty, null))) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); if (language == LanguageNames.VisualBasic) { // VB needs Compilation.ParseOptions set (we do the same at the VS layer) compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace) .WithGlobalImports(globalImports) .WithParseOptions((VisualBasicParseOptions)parseOptions ?? VisualBasicParseOptions.Default); } return compilationOptions; } private static TestHostDocument CreateDocument( TestWorkspace workspace, XElement workspaceElement, XElement documentElement, string language, ExportProvider exportProvider, HostLanguageServices languageServiceProvider, Dictionary<string, ITextBuffer> filePathToTextBufferMap, ref int documentId) { string markupCode; string filePath; var isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName); bool isLinkFile = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value; if (isLinkFile) { // This is a linked file. Use the filePath and markup from the referenced document. var originalAssemblyName = documentElement.Attribute(LinkAssemblyNameAttributeName)?.Value; var originalProjectName = documentElement.Attribute(LinkProjectNameAttributeName)?.Value; if (originalAssemblyName == null && originalProjectName == null) { throw new ArgumentException($"Linked files must specify either a {LinkAssemblyNameAttributeName} or {LinkProjectNameAttributeName}"); } var originalProject = workspaceElement.Elements(ProjectElementName).FirstOrDefault(p => { if (originalAssemblyName != null) { return p.Attribute(AssemblyNameAttributeName)?.Value == originalAssemblyName; } else { return p.Attribute(ProjectNameAttribute)?.Value == originalProjectName; } }); if (originalProject == null) { if (originalProjectName != null) { throw new ArgumentException($"Linked file's {LinkProjectNameAttributeName} '{originalProjectName}' project not found."); } else { throw new ArgumentException($"Linked file's {LinkAssemblyNameAttributeName} '{originalAssemblyName}' project not found."); } } var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName)?.Value; if (originalDocumentPath == null) { throw new ArgumentException($"Linked files must specify a {LinkFilePathAttributeName}"); } documentElement = originalProject.Elements(DocumentElementName).FirstOrDefault(d => { return d.Attribute(FilePathAttributeName)?.Value == originalDocumentPath; }); if (documentElement == null) { throw new ArgumentException($"Linked file's LinkFilePath '{originalDocumentPath}' file not found."); } } markupCode = documentElement.NormalizedValue(); filePath = GetFilePath(workspace, documentElement, ref documentId); var folders = GetFolders(documentElement); var optionsElement = documentElement.Element(ParseOptionsElementName); // TODO: Allow these to be specified. var codeKind = SourceCodeKind.Regular; if (optionsElement != null) { var attr = optionsElement.Attribute(KindAttributeName); codeKind = attr == null ? SourceCodeKind.Regular : (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value); } var contentTypeLanguageService = languageServiceProvider.GetService<IContentTypeLanguageService>(); var contentType = contentTypeLanguageService.GetDefaultContentType(); MarkupTestFile.GetPositionAndSpans(markupCode, out var code, out var cursorPosition, out IDictionary<string, ImmutableArray<TextSpan>> spans); // For linked files, use the same ITextBuffer for all linked documents ITextBuffer textBuffer; if (!filePathToTextBufferMap.TryGetValue(filePath, out textBuffer)) { textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code); filePathToTextBufferMap.Add(filePath, textBuffer); } return new TestHostDocument(exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile); } private static string GetFilePath( TestWorkspace workspace, XElement documentElement, ref int documentId) { var filePathAttribute = documentElement.Attribute(FilePathAttributeName); if (filePathAttribute != null) { return filePathAttribute.Value; } var language = GetLanguage(workspace, documentElement.Ancestors(ProjectElementName).Single()); documentId++; var name = "Test" + documentId; return language == LanguageNames.CSharp ? name + ".cs" : name + ".vb"; } private static IReadOnlyList<string> GetFolders(XElement documentElement) { var folderAttribute = documentElement.Attribute(FoldersAttributeName); if (folderAttribute == null) { return null; } var folderContainers = folderAttribute.Value.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); return new ReadOnlyCollection<string>(folderContainers.ToList()); } /// <summary> /// Takes completely valid code, compiles it, and emits it to a MetadataReference without using /// the file system /// </summary> private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace workspace, XElement referencedSource) { var compilation = CreateCompilation(workspace, referencedSource); var aliasElement = referencedSource.Attribute("Aliases")?.Value; var aliases = aliasElement != null ? aliasElement.Split(',').Select(s => s.Trim()).ToImmutableArray() : default(ImmutableArray<string>); bool includeXmlDocComments = false; var includeXmlDocCommentsAttribute = referencedSource.Attribute(IncludeXmlDocCommentsAttributeName); if (includeXmlDocCommentsAttribute != null && ((bool?)includeXmlDocCommentsAttribute).HasValue && ((bool?)includeXmlDocCommentsAttribute).Value) { includeXmlDocComments = true; } return MetadataReference.CreateFromImage(compilation.EmitToArray(), new MetadataReferenceProperties(aliases: aliases), includeXmlDocComments ? new DeferredDocumentationProvider(compilation) : null); } private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource) { string languageName = GetLanguage(workspace, referencedSource); string assemblyName = "ReferencedAssembly"; var assemblyNameAttribute = referencedSource.Attribute(AssemblyNameAttributeName); if (assemblyNameAttribute != null) { assemblyName = assemblyNameAttribute.Value; } var languageServices = workspace.Services.GetLanguageServices(languageName); var compilationFactory = languageServices.GetService<ICompilationFactoryService>(); var options = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary); var compilation = compilationFactory.CreateCompilation(assemblyName, options); var documentElements = referencedSource.Elements(DocumentElementName).ToList(); foreach (var documentElement in documentElements) { compilation = compilation.AddSyntaxTrees(CreateSyntaxTree(languageName, documentElement.Value)); } foreach (var reference in CreateReferenceList(workspace, referencedSource)) { compilation = compilation.AddReferences(reference); } return compilation; } private static SyntaxTree CreateSyntaxTree(string languageName, string referencedCode) { if (LanguageNames.CSharp == languageName) { return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(referencedCode); } else { return Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(referencedCode); } } private static IList<MetadataReference> CreateReferenceList(TestWorkspace workspace, XElement element) { var references = CreateCommonReferences(workspace, element); foreach (var reference in element.Elements(MetadataReferenceElementName)) { references.Add(MetadataReference.CreateFromFile(reference.Value)); } foreach (var metadataReferenceFromSource in element.Elements(MetadataReferenceFromSourceElementName)) { references.Add(CreateMetadataReferenceFromSource(workspace, metadataReferenceFromSource)); } return references; } private static IList<AnalyzerReference> CreateAnalyzerList(TestWorkspace workspace, XElement projectElement) { var analyzers = new List<AnalyzerReference>(); foreach (var analyzer in projectElement.Elements(AnalyzerElementName)) { analyzers.Add( new AnalyzerImageReference( ImmutableArray<DiagnosticAnalyzer>.Empty, display: (string)analyzer.Attribute(AnalyzerDisplayAttributeName), fullPath: (string)analyzer.Attribute(AnalyzerFullPathAttributeName))); } return analyzers; } private static IList<MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element) { var references = new List<MetadataReference>(); var net45 = element.Attribute(CommonReferencesNet45AttributeName); if (net45 != null && ((bool?)net45).HasValue && ((bool?)net45).Value) { references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName); if (commonReferencesAttribute != null && ((bool?)commonReferencesAttribute).HasValue && ((bool?)commonReferencesAttribute).Value) { references = new List<MetadataReference> { TestBase.MscorlibRef_v46, TestBase.SystemRef_v46, TestBase.SystemCoreRef_v46 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var winRT = element.Attribute(CommonReferencesWinRTAttributeName); if (winRT != null && ((bool?)winRT).HasValue && ((bool?)winRT).Value) { references = new List<MetadataReference>(TestBase.WinRtRefs.Length); references.AddRange(TestBase.WinRtRefs); if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var portable = element.Attribute(CommonReferencesPortableAttributeName); if (portable != null && ((bool?)portable).HasValue && ((bool?)portable).Value) { references = new List<MetadataReference>(TestBase.PortableRefsMinimal.Length); references.AddRange(TestBase.PortableRefsMinimal); } var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName); if (systemRuntimeFacade != null && ((bool?)systemRuntimeFacade).HasValue && ((bool?)systemRuntimeFacade).Value) { references.Add(TestBase.SystemRuntimeFacadeRef); } return references; } public static bool IsWorkspaceElement(string text) { return text.TrimStart('\r', '\n', ' ').StartsWith("<Workspace>", StringComparison.Ordinal); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Management.Automation.Help; using System.Collections.Generic; namespace System.Management.Automation { /// <summary> /// The MamlUtil class. /// </summary> internal class MamlUtil { /// <summary> /// Takes Name value from maml2 and overrides it in maml1. /// </summary> /// <param name="maml1"></param> /// <param name="maml2"></param> internal static void OverrideName(PSObject maml1, PSObject maml2) { PrependPropertyValue(maml1, maml2, new string[] { "Name" }, true); PrependPropertyValue(maml1, maml2, new string[] { "Details", "Name" }, true); } /// <summary> /// Takes Name value from maml2 and overrides it in maml1. /// </summary> /// <param name="maml1"></param> /// <param name="maml2"></param> internal static void OverridePSTypeNames(PSObject maml1, PSObject maml2) { foreach (var typename in maml2.TypeNames) { if (typename.StartsWith(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, StringComparison.OrdinalIgnoreCase)) { //Win8: 638494 if the original help is auto-generated, let the Provider help decide the format. return; } } maml1.TypeNames.Clear(); // User request at the top.. foreach (string typeName in maml2.TypeNames) { maml1.TypeNames.Add(typeName); } } /// <summary> /// Adds common properties like PSSnapIn,ModuleName from maml2 to maml1 /// </summary> /// <param name="maml1"></param> /// <param name="maml2"></param> internal static void AddCommonProperties(PSObject maml1, PSObject maml2) { if (maml1.Properties["PSSnapIn"] == null) { PSPropertyInfo snapInProperty = maml2.Properties["PSSnapIn"]; if (null != snapInProperty) { maml1.Properties.Add(new PSNoteProperty("PSSnapIn", snapInProperty.Value)); } } if (maml1.Properties["ModuleName"] == null) { PSPropertyInfo moduleNameProperty = maml2.Properties["ModuleName"]; if (null != moduleNameProperty) { maml1.Properties.Add(new PSNoteProperty("ModuleName", moduleNameProperty.Value)); } } } /// <summary> /// Prepend - Modify Syntax element in maml1 using the Syntax element from maml2. /// </summary> internal static void PrependSyntax(PSObject maml1, PSObject maml2) { PrependPropertyValue(maml1, maml2, new string[] { "Syntax", "SyntaxItem" }, false); } /// <summary> /// Prepend - Modify DetailedDescription element in maml1 using the DetailedDescription element from maml2. /// </summary> internal static void PrependDetailedDescription(PSObject maml1, PSObject maml2) { PrependPropertyValue(maml1, maml2, new string[] { "Description" }, false); } /// <summary> /// Override - Modify Parameters element in maml1 using the Parameters element from maml2. /// This will copy parameters from maml2 that are not present in maml1. /// </summary> internal static void OverrideParameters(PSObject maml1, PSObject maml2) { string[] parametersPath = new string[] { "Parameters", "Parameter" }; // Final collection of PSObjects. List<object> maml2items = new List<object>(); // Add maml2 first since we are prepending. // For maml2: Add as collection or single item. No-op if PSPropertyInfo propertyInfo2 = GetProperyInfo(maml2, parametersPath); var array = propertyInfo2.Value as Array; if (array != null) { maml2items.AddRange(array as IEnumerable<object>); } else { maml2items.Add(PSObject.AsPSObject(propertyInfo2.Value)); } // Extend maml1 to make sure the property-path exists - since we'll be modifying it soon. EnsurePropertyInfoPathExists(maml1, parametersPath); // For maml1: Add as collection or single item. Do nothing if null or some other type. PSPropertyInfo propertyInfo1 = GetProperyInfo(maml1, parametersPath); List<object> maml1items = new List<object>(); array = propertyInfo1.Value as Array; if (array != null) { maml1items.AddRange(array as IEnumerable<object>); } else { maml1items.Add(PSObject.AsPSObject(propertyInfo1.Value)); } // copy parameters from maml2 that are not present in maml1 for (int index = 0; index < maml2items.Count; index++) { PSObject m2paramObj = PSObject.AsPSObject(maml2items[index]); string param2Name = ""; PSPropertyInfo m2propertyInfo = m2paramObj.Properties["Name"]; if (null != m2propertyInfo) { if (!LanguagePrimitives.TryConvertTo<string>(m2propertyInfo.Value, out param2Name)) { continue; } } bool isParamFoundInMaml1 = false; foreach (PSObject m1ParamObj in maml1items) { string param1Name = ""; PSPropertyInfo m1PropertyInfo = m1ParamObj.Properties["Name"]; if (null != m1PropertyInfo) { if (!LanguagePrimitives.TryConvertTo<string>(m1PropertyInfo.Value, out param1Name)) { continue; } } if (param1Name.Equals(param2Name, StringComparison.OrdinalIgnoreCase)) { isParamFoundInMaml1 = true; } } if (!isParamFoundInMaml1) { maml1items.Add(maml2items[index]); } } // Now replace in maml1. If items.Count == 0 do nothing since Value is already null. if (maml1items.Count == 1) { propertyInfo1.Value = maml1items[0]; } else if (maml1items.Count >= 2) { propertyInfo1.Value = maml1items.ToArray(); } } /// <summary> /// Prepend - Modify Notes element in maml1 using the Notes element from maml2. /// </summary> internal static void PrependNotes(PSObject maml1, PSObject maml2) { PrependPropertyValue(maml1, maml2, new string[] { "AlertSet", "Alert" }, false); } /// <summary> /// Get propery info. /// </summary> internal static PSPropertyInfo GetProperyInfo(PSObject psObject, string[] path) { if (path.Length <= 0) { return null; } for (int i = 0; i < path.Length; ++i) { string propertyName = path[i]; PSPropertyInfo propertyInfo = psObject.Properties[propertyName]; if (i == path.Length - 1) { return propertyInfo; } if (propertyInfo == null || !(propertyInfo.Value is PSObject)) { return null; } psObject = (PSObject)propertyInfo.Value; } // We will never reach this line but the compiler needs some reassurance. return null; } /// <summary> /// Prepend property value. /// </summary> /// <param name="maml1"> /// </param> /// <param name="maml2"> /// </param> /// <param name="path"> /// </param> /// <param name="shouldOverride"> /// Should Override the maml1 value from maml2 instead of prepend. /// </param> internal static void PrependPropertyValue(PSObject maml1, PSObject maml2, string[] path, bool shouldOverride) { // Final collection of PSObjects. List<object> items = new List<object>(); // Add maml2 first since we are prepending. // For maml2: Add as collection or single item. No-op if PSPropertyInfo propertyInfo2 = GetProperyInfo(maml2, path); if (null != propertyInfo2) { var array = propertyInfo2.Value as Array; if (array != null) { items.AddRange(propertyInfo2.Value as IEnumerable<object>); } else { items.Add(propertyInfo2.Value); } } // Extend maml1 to make sure the property-path exists - since we'll be modifying it soon. EnsurePropertyInfoPathExists(maml1, path); // For maml1: Add as collection or single item. Do nothing if null or some other type. PSPropertyInfo propertyInfo1 = GetProperyInfo(maml1, path); if (null != propertyInfo1) { if (!shouldOverride) { var array = propertyInfo1.Value as Array; if (array != null) { items.AddRange(propertyInfo1.Value as IEnumerable<object>); } else { items.Add(propertyInfo1.Value); } } // Now replace in maml1. If items.Count == 0 do nothing since Value is already null. if (items.Count == 1) { propertyInfo1.Value = items[0]; } else if (items.Count >= 2) { propertyInfo1.Value = items.ToArray(); } } } /// <summary> /// Ensure property info path exists. /// </summary> internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] path) { if (path.Length <= 0) { return; } // Walk the path and extend it if necessary. for (int i = 0; i < path.Length; ++i) { string propertyName = path[i]; PSPropertyInfo propertyInfo = psObject.Properties[propertyName]; // Add a property info here if none was found. if (propertyInfo == null) { // Add null on the last one, since we don't need to extend path further. object propertyValue = (i < path.Length - 1) ? new PSObject() : null; propertyInfo = new PSNoteProperty(propertyName, propertyValue); psObject.Properties.Add(propertyInfo); } // If we are on the last path element, we are done. Let's not mess with modifying Value. if (i == path.Length - 1) { return; } // If we are not on the last path element, let's make sure we can extend the path. if (propertyInfo.Value == null || !(propertyInfo.Value is PSObject)) { propertyInfo.Value = new PSObject(); } // Now move one step further along the path. psObject = (PSObject)propertyInfo.Value; } } } }
using System; using System.Collections; using System.Text; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Utilities; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Date; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.X509.Extension; namespace Org.BouncyCastle.X509 { /** * The following extensions are listed in RFC 2459 as relevant to CRLs * * Authority Key Identifier * Issuer Alternative Name * CRL Number * Delta CRL Indicator (critical) * Issuing Distribution Point (critical) */ public class X509Crl : X509ExtensionBase // TODO Add interface Crl? { private readonly CertificateList c; private readonly string sigAlgName; private readonly byte[] sigAlgParams; private readonly bool isIndirect; public X509Crl( CertificateList c) { this.c = c; try { this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm); if (c.SignatureAlgorithm.Parameters != null) { this.sigAlgParams = ((Asn1Encodable)c.SignatureAlgorithm.Parameters).GetDerEncoded(); } else { this.sigAlgParams = null; } this.isIndirect = IsIndirectCrl; } catch (Exception e) { throw new CrlException("CRL contents invalid: " + e); } } protected override X509Extensions GetX509Extensions() { return Version == 2 ? c.TbsCertList.Extensions : null; } public virtual byte[] GetEncoded() { try { return c.GetDerEncoded(); } catch (Exception e) { throw new CrlException(e.ToString()); } } public virtual void Verify( IAsymmetricKeyParameter publicKey) { if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature)) { throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList."); } ISigner sig = SignerUtilities.GetSigner(SigAlgName); sig.Init(false, publicKey); byte[] encoded = this.GetTbsCertList(); sig.BlockUpdate(encoded, 0, encoded.Length); if (!sig.VerifySignature(this.GetSignature())) { throw new SignatureException("CRL does not verify with supplied public key."); } } public virtual int Version { get { return c.Version; } } public virtual X509Name IssuerDN { get { return c.Issuer; } } public virtual DateTime ThisUpdate { get { return c.ThisUpdate.ToDateTime(); } } public virtual DateTimeObject NextUpdate { get { return c.NextUpdate == null ? null : new DateTimeObject(c.NextUpdate.ToDateTime()); } } private ISet LoadCrlEntries() { ISet entrySet = new HashSet(); IEnumerable certs = c.GetRevokedCertificateEnumeration(); X509Name previousCertificateIssuer = IssuerDN; foreach (CrlEntry entry in certs) { X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer); entrySet.Add(crlEntry); previousCertificateIssuer = crlEntry.GetCertificateIssuer(); } return entrySet; } public virtual X509CrlEntry GetRevokedCertificate( IBigInteger serialNumber) { IEnumerable certs = c.GetRevokedCertificateEnumeration(); X509Name previousCertificateIssuer = IssuerDN; foreach (CrlEntry entry in certs) { X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer); if (serialNumber.Equals(entry.UserCertificate.Value)) { return crlEntry; } previousCertificateIssuer = crlEntry.GetCertificateIssuer(); } return null; } public virtual ISet GetRevokedCertificates() { ISet entrySet = LoadCrlEntries(); if (entrySet.Count > 0) { return entrySet; // TODO? Collections.unmodifiableSet(entrySet); } return null; } public virtual byte[] GetTbsCertList() { try { return c.TbsCertList.GetDerEncoded(); } catch (Exception e) { throw new CrlException(e.ToString()); } } public virtual byte[] GetSignature() { return c.Signature.GetBytes(); } public virtual string SigAlgName { get { return sigAlgName; } } public virtual string SigAlgOid { get { return c.SignatureAlgorithm.ObjectID.Id; } } public virtual byte[] GetSigAlgParams() { return Arrays.Clone(sigAlgParams); } public override bool Equals( object obj) { if (obj == this) return true; X509Crl other = obj as X509Crl; if (other == null) return false; return c.Equals(other.c); // NB: May prefer this implementation of Equals if more than one certificate implementation in play //return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded()); } public override int GetHashCode() { return c.GetHashCode(); } /** * Returns a string representation of this CRL. * * @return a string representation of this CRL. */ public override string ToString() { StringBuilder buf = new StringBuilder(); string nl = Platform.NewLine; buf.Append(" Version: ").Append(this.Version).Append(nl); buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl); buf.Append(" This update: ").Append(this.ThisUpdate).Append(nl); buf.Append(" Next update: ").Append(this.NextUpdate).Append(nl); buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl); byte[] sig = this.GetSignature(); buf.Append(" Signature: "); buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl); for (int i = 20; i < sig.Length; i += 20) { int count = System.Math.Min(20, sig.Length - i); buf.Append(" "); buf.Append(Hex.ToHexString(sig, i, count)).Append(nl); } X509Extensions extensions = c.TbsCertList.Extensions; if (extensions != null) { IEnumerator e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { buf.Append(" Extensions: ").Append(nl); } do { DerObjectIdentifier oid = (DerObjectIdentifier) e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) { Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value); buf.Append(" critical(").Append(ext.IsCritical).Append(") "); try { if (oid.Equals(X509Extensions.CrlNumber)) { buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl); } else if (oid.Equals(X509Extensions.DeltaCrlIndicator)) { buf.Append( "Base CRL: " + new CrlNumber(DerInteger.GetInstance( asn1Value).PositiveValue)) .Append(nl); } else if (oid.Equals(X509Extensions.IssuingDistributionPoint)) { buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl); } else if (oid.Equals(X509Extensions.CrlDistributionPoints)) { buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl); } else if (oid.Equals(X509Extensions.FreshestCrl)) { buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl); } else { buf.Append(oid.Id); buf.Append(" value = ").Append( Asn1Dump.DumpAsString(asn1Value)) .Append(nl); } } catch (Exception) { buf.Append(oid.Id); buf.Append(" value = ").Append("*****").Append(nl); } } else { buf.Append(nl); } } while (e.MoveNext()); } ISet certSet = GetRevokedCertificates(); if (certSet != null) { foreach (X509CrlEntry entry in certSet) { buf.Append(entry); buf.Append(nl); } } return buf.ToString(); } /** * Checks whether the given certificate is on this CRL. * * @param cert the certificate to check for. * @return true if the given certificate is on this CRL, * false otherwise. */ // public bool IsRevoked( // Certificate cert) // { // if (!cert.getType().Equals("X.509")) // { // throw new RuntimeException("X.509 CRL used with non X.509 Cert"); // } public virtual bool IsRevoked( X509Certificate cert) { CrlEntry[] certs = c.GetRevokedCertificates(); if (certs != null) { // IBigInteger serial = ((X509Certificate)cert).SerialNumber; IBigInteger serial = cert.SerialNumber; for (int i = 0; i < certs.Length; i++) { if (certs[i].UserCertificate.Value.Equals(serial)) { return true; } } } return false; } protected virtual bool IsIndirectCrl { get { Asn1OctetString idp = GetExtensionValue(X509Extensions.IssuingDistributionPoint); bool isIndirect = false; try { if (idp != null) { isIndirect = IssuingDistributionPoint.GetInstance( X509ExtensionUtilities.FromExtensionValue(idp)).IsIndirectCrl; } } catch (Exception e) { // TODO // throw new ExtCrlException("Exception reading IssuingDistributionPoint", e); throw new CrlException("Exception reading IssuingDistributionPoint" + e); } return isIndirect; } } } }
using System; using System.Collections.Generic; using ModestTree; using System.Linq; #if !NOT_UNITY3D using UnityEngine; #endif namespace Zenject { public class FromBinderGeneric<TContract> : FromBinder { public FromBinderGeneric( DiContainer bindContainer, BindInfo bindInfo, BindFinalizerWrapper finalizerWrapper) : base(bindContainer, bindInfo, finalizerWrapper) { BindingUtil.AssertIsDerivedFromTypes(typeof(TContract), BindInfo.ContractTypes); } // Shortcut for FromIFactory and also for backwards compatibility public ScopeConcreteIdArgConditionCopyNonLazyBinder FromFactory<TFactory>() where TFactory : IFactory<TContract> { return FromIFactory(x => x.To<TFactory>().AsCached()); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromIFactory( Action<ConcreteBinderGeneric<IFactory<TContract>>> factoryBindGenerator) { return FromIFactoryBase<TContract>(factoryBindGenerator); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromMethod(Func<TContract> method) { return FromMethodBase<TContract>(ctx => method()); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromMethod(Func<InjectContext, TContract> method) { return FromMethodBase<TContract>(method); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromMethodMultiple(Func<InjectContext, IEnumerable<TContract>> method) { return FromMethodMultipleBase<TContract>(method); } public ScopeConditionCopyNonLazyBinder FromResolveGetter<TObj>(Func<TObj, TContract> method) { return FromResolveGetter<TObj>(null, method); } public ScopeConditionCopyNonLazyBinder FromResolveGetter<TObj>(object identifier, Func<TObj, TContract> method) { return FromResolveGetter<TObj>(identifier, method, InjectSources.Any); } public ScopeConditionCopyNonLazyBinder FromResolveGetter<TObj>(object identifier, Func<TObj, TContract> method, InjectSources source) { return FromResolveGetterBase<TObj, TContract>(identifier, method, source, false); } public ScopeConditionCopyNonLazyBinder FromResolveAllGetter<TObj>(Func<TObj, TContract> method) { return FromResolveAllGetter<TObj>(null, method); } public ScopeConditionCopyNonLazyBinder FromResolveAllGetter<TObj>(object identifier, Func<TObj, TContract> method) { return FromResolveAllGetter<TObj>(identifier, method, InjectSources.Any); } public ScopeConditionCopyNonLazyBinder FromResolveAllGetter<TObj>(object identifier, Func<TObj, TContract> method, InjectSources source) { return FromResolveGetterBase<TObj, TContract>(identifier, method, source, true); } public ScopeConditionCopyNonLazyBinder FromInstance(TContract instance) { return FromInstanceBase(instance); } #if !NOT_UNITY3D public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentInChildren(bool includeInactive = true) { BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); // Use FromMethodMultiple so that we can return the empty list when context is optional return FromMethodMultiple((ctx) => { Assert.That(ctx.ObjectType.DerivesFromOrEqual<MonoBehaviour>(), "Cannot use FromComponentInChildren to inject data into non monobehaviours!"); Assert.IsNotNull(ctx.ObjectInstance); var res = ((MonoBehaviour)ctx.ObjectInstance).GetComponentInChildren<TContract>(includeInactive); if (res == null) { Assert.That(ctx.Optional, "Could not find component '{0}' through FromComponentInChildren binding", typeof(TContract)); return Enumerable.Empty<TContract>(); } return new TContract[] { res }; }); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentsInChildren( Func<TContract, bool> predicate, bool includeInactive = true) { return FromComponentsInChildren(false, predicate, includeInactive); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentsInChildren( bool excludeSelf = false, Func<TContract, bool> predicate = null, bool includeInactive = true) { BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); return FromMethodMultiple((ctx) => { Assert.That(ctx.ObjectType.DerivesFromOrEqual<MonoBehaviour>(), "Cannot use FromComponentsInChildren to inject data into non monobehaviours!"); Assert.IsNotNull(ctx.ObjectInstance); var res = ((MonoBehaviour)ctx.ObjectInstance).GetComponentsInChildren<TContract>(includeInactive) .Where(x => !ReferenceEquals(x, ctx.ObjectInstance)); if (excludeSelf) { res = res.Where(x => (x as Component).gameObject != (ctx.ObjectInstance as Component).gameObject); } if (predicate != null) { res = res.Where(predicate); } return res; }); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentInParents( bool excludeSelf = false, bool includeInactive = true) { BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); // Use FromMethodMultiple so that we can return the empty list when context is optional return FromMethodMultiple((ctx) => { Assert.That(ctx.ObjectType.DerivesFromOrEqual<MonoBehaviour>(), "Cannot use FromComponentInParents to inject data into non monobehaviours!"); Assert.IsNotNull(ctx.ObjectInstance); var matches = ((MonoBehaviour)ctx.ObjectInstance).GetComponentsInParent<TContract>(includeInactive) .Where(x => !ReferenceEquals(x, ctx.ObjectInstance)); if (excludeSelf) { matches = matches.Where(x => (x as Component).gameObject != (ctx.ObjectInstance as Component).gameObject); } var result = matches.FirstOrDefault(); if (result == null) { Assert.That(ctx.Optional, "Could not find component '{0}' through FromComponentInParents binding", typeof(TContract)); return Enumerable.Empty<TContract>(); } return new TContract[] { result }; }); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentsInParents( bool excludeSelf = false, bool includeInactive = true) { BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); return FromMethodMultiple((ctx) => { Assert.That(ctx.ObjectType.DerivesFromOrEqual<MonoBehaviour>(), "Cannot use FromComponentInParents to inject data into non monobehaviours!"); Assert.IsNotNull(ctx.ObjectInstance); var res = ((MonoBehaviour)ctx.ObjectInstance).GetComponentsInParent<TContract>(includeInactive) .Where(x => !ReferenceEquals(x, ctx.ObjectInstance)); if (excludeSelf) { res = res.Where(x => (x as Component).gameObject != (ctx.ObjectInstance as Component).gameObject); } return res; }); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentSibling() { BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); // Use FromMethodMultiple so that we can return the empty list when context is optional return FromMethodMultiple((ctx) => { Assert.That(ctx.ObjectType.DerivesFromOrEqual<MonoBehaviour>(), "Cannot use FromComponentSibling to inject data into non monobehaviours!"); Assert.IsNotNull(ctx.ObjectInstance); var match = ((MonoBehaviour)ctx.ObjectInstance).GetComponent<TContract>(); if (match == null) { Assert.That(ctx.Optional, "Could not find component '{0}' through FromComponentSibling binding", typeof(TContract)); return Enumerable.Empty<TContract>(); } return new TContract[] { match }; }); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentsSibling() { BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); return FromMethodMultiple((ctx) => { Assert.That(ctx.ObjectType.DerivesFromOrEqual<MonoBehaviour>(), "Cannot use FromComponentSibling to inject data into non monobehaviours!"); Assert.IsNotNull(ctx.ObjectInstance); return ((MonoBehaviour)ctx.ObjectInstance).GetComponents<TContract>() .Where(x => !ReferenceEquals(x, ctx.ObjectInstance)); }); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentInHierarchy( bool includeInactive = true) { BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); // Use FromMethodMultiple so that we can return the empty list when context is optional return FromMethodMultiple((ctx) => { var res = BindContainer.Resolve<Context>().GetRootGameObjects() .Select(x => x.GetComponentInChildren<TContract>(includeInactive)) .Where(x => x != null).FirstOrDefault(); if (res == null) { Assert.That(ctx.Optional, "Could not find component '{0}' through FromComponentInHierarchy binding", typeof(TContract)); return Enumerable.Empty<TContract>(); } return new TContract[] { res }; }); } public ScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentsInHierarchy( Func<TContract, bool> predicate = null, bool includeInactive = true) { BindingUtil.AssertIsInterfaceOrComponent(AllParentTypes); return FromMethodMultiple((ctx) => { var res = BindContainer.Resolve<Context>().GetRootGameObjects() .SelectMany(x => x.GetComponentsInChildren<TContract>(includeInactive)) .Where(x => !ReferenceEquals(x, ctx.ObjectInstance)); if (predicate != null) { res = res.Where(predicate); } return res; }); } #endif } }
/* * 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. */ // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global #pragma warning disable 618 namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity.Rendezvous; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Eviction; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Ssl; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.DataStructures.Configuration; using Apache.Ignite.Core.Deployment; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Multicast; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Failure; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Plugin.Cache; using Apache.Ignite.Core.Tests.Binary; using Apache.Ignite.Core.Tests.Plugin; using Apache.Ignite.Core.Transactions; using Apache.Ignite.NLog; using NUnit.Framework; using CheckpointWriteOrder = Apache.Ignite.Core.PersistentStore.CheckpointWriteOrder; using DataPageEvictionMode = Apache.Ignite.Core.Cache.Configuration.DataPageEvictionMode; using WalMode = Apache.Ignite.Core.PersistentStore.WalMode; /// <summary> /// Tests <see cref="IgniteConfiguration"/> serialization. /// </summary> public class IgniteConfigurationSerializerTest { /// <summary> /// Tests the predefined XML. /// </summary> [Test] public void TestPredefinedXml() { var xml = File.ReadAllText("Config\\full-config.xml"); var cfg = IgniteConfiguration.FromXml(xml); Assert.AreEqual("c:", cfg.WorkDirectory); Assert.AreEqual("127.1.1.1", cfg.Localhost); Assert.IsTrue(cfg.IsDaemon); Assert.AreEqual(1024, cfg.JvmMaxMemoryMb); Assert.AreEqual(TimeSpan.FromSeconds(10), cfg.MetricsLogFrequency); Assert.AreEqual(TimeSpan.FromMinutes(1), ((TcpDiscoverySpi)cfg.DiscoverySpi).JoinTimeout); Assert.AreEqual("192.168.1.1", ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalAddress); Assert.AreEqual(6655, ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalPort); Assert.AreEqual(7, ((TcpDiscoveryMulticastIpFinder) ((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder).AddressRequestAttempts); Assert.AreEqual(new[] { "-Xms1g", "-Xmx4g" }, cfg.JvmOptions); Assert.AreEqual(15, ((LifecycleBean) cfg.LifecycleHandlers.Single()).Foo); Assert.AreEqual("testBar", ((NameMapper) cfg.BinaryConfiguration.NameMapper).Bar); Assert.AreEqual( "Apache.Ignite.Core.Tests.IgniteConfigurationSerializerTest+FooClass, Apache.Ignite.Core.Tests", cfg.BinaryConfiguration.Types.Single()); Assert.IsFalse(cfg.BinaryConfiguration.CompactFooter); Assert.AreEqual(new[] {42, EventType.TaskFailed, EventType.JobFinished}, cfg.IncludedEventTypes); Assert.AreEqual(@"c:\myconfig.xml", cfg.SpringConfigUrl); Assert.IsTrue(cfg.AutoGenerateIgniteInstanceName); Assert.AreEqual(new TimeSpan(1, 2, 3), cfg.LongQueryWarningTimeout); Assert.IsFalse(cfg.IsActiveOnStart); Assert.IsTrue(cfg.AuthenticationEnabled); Assert.IsNotNull(cfg.SqlSchemas); Assert.AreEqual(2, cfg.SqlSchemas.Count); Assert.IsTrue(cfg.SqlSchemas.Contains("SCHEMA_1")); Assert.IsTrue(cfg.SqlSchemas.Contains("schema_2")); Assert.AreEqual("someId012", cfg.ConsistentId); Assert.IsFalse(cfg.RedirectJavaConsoleOutput); Assert.AreEqual("secondCache", cfg.CacheConfiguration.Last().Name); var cacheCfg = cfg.CacheConfiguration.First(); Assert.AreEqual(CacheMode.Replicated, cacheCfg.CacheMode); Assert.IsTrue(cacheCfg.ReadThrough); Assert.IsTrue(cacheCfg.WriteThrough); Assert.IsInstanceOf<MyPolicyFactory>(cacheCfg.ExpiryPolicyFactory); Assert.IsTrue(cacheCfg.EnableStatistics); Assert.IsFalse(cacheCfg.WriteBehindCoalescing); Assert.AreEqual(PartitionLossPolicy.ReadWriteAll, cacheCfg.PartitionLossPolicy); Assert.AreEqual("fooGroup", cacheCfg.GroupName); Assert.AreEqual("bar", cacheCfg.KeyConfiguration.Single().AffinityKeyFieldName); Assert.AreEqual("foo", cacheCfg.KeyConfiguration.Single().TypeName); Assert.IsTrue(cacheCfg.OnheapCacheEnabled); Assert.AreEqual(8, cacheCfg.StoreConcurrentLoadAllThreshold); Assert.AreEqual(9, cacheCfg.RebalanceOrder); Assert.AreEqual(10, cacheCfg.RebalanceBatchesPrefetchCount); Assert.AreEqual(11, cacheCfg.MaxQueryIteratorsCount); Assert.AreEqual(12, cacheCfg.QueryDetailMetricsSize); Assert.AreEqual(13, cacheCfg.QueryParallelism); Assert.AreEqual("mySchema", cacheCfg.SqlSchema); var queryEntity = cacheCfg.QueryEntities.Single(); Assert.AreEqual(typeof(int), queryEntity.KeyType); Assert.AreEqual(typeof(string), queryEntity.ValueType); Assert.AreEqual("myTable", queryEntity.TableName); Assert.AreEqual("length", queryEntity.Fields.Single().Name); Assert.AreEqual(typeof(int), queryEntity.Fields.Single().FieldType); Assert.IsTrue(queryEntity.Fields.Single().IsKeyField); Assert.IsTrue(queryEntity.Fields.Single().NotNull); Assert.AreEqual(3.456d, (double)queryEntity.Fields.Single().DefaultValue); Assert.AreEqual("somefield.field", queryEntity.Aliases.Single().FullName); Assert.AreEqual("shortField", queryEntity.Aliases.Single().Alias); var queryIndex = queryEntity.Indexes.Single(); Assert.AreEqual(QueryIndexType.Geospatial, queryIndex.IndexType); Assert.AreEqual("indexFld", queryIndex.Fields.Single().Name); Assert.AreEqual(true, queryIndex.Fields.Single().IsDescending); Assert.AreEqual(123, queryIndex.InlineSize); var nearCfg = cacheCfg.NearConfiguration; Assert.IsNotNull(nearCfg); Assert.AreEqual(7, nearCfg.NearStartSize); var plc = nearCfg.EvictionPolicy as FifoEvictionPolicy; Assert.IsNotNull(plc); Assert.AreEqual(10, plc.BatchSize); Assert.AreEqual(20, plc.MaxSize); Assert.AreEqual(30, plc.MaxMemorySize); var plc2 = cacheCfg.EvictionPolicy as LruEvictionPolicy; Assert.IsNotNull(plc2); Assert.AreEqual(1, plc2.BatchSize); Assert.AreEqual(2, plc2.MaxSize); Assert.AreEqual(3, plc2.MaxMemorySize); var af = cacheCfg.AffinityFunction as RendezvousAffinityFunction; Assert.IsNotNull(af); Assert.AreEqual(99, af.Partitions); Assert.IsTrue(af.ExcludeNeighbors); Assert.AreEqual(new Dictionary<string, object> { {"myNode", "true"}, {"foo", new FooClass {Bar = "Baz"}} }, cfg.UserAttributes); var atomicCfg = cfg.AtomicConfiguration; Assert.AreEqual(2, atomicCfg.Backups); Assert.AreEqual(CacheMode.Local, atomicCfg.CacheMode); Assert.AreEqual(250, atomicCfg.AtomicSequenceReserveSize); var tx = cfg.TransactionConfiguration; Assert.AreEqual(TransactionConcurrency.Optimistic, tx.DefaultTransactionConcurrency); Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.DefaultTransactionIsolation); Assert.AreEqual(new TimeSpan(0,1,2), tx.DefaultTimeout); Assert.AreEqual(15, tx.PessimisticTransactionLogSize); Assert.AreEqual(TimeSpan.FromSeconds(33), tx.PessimisticTransactionLogLinger); var comm = cfg.CommunicationSpi as TcpCommunicationSpi; Assert.IsNotNull(comm); Assert.AreEqual(33, comm.AckSendThreshold); Assert.AreEqual(new TimeSpan(0, 1, 2), comm.IdleConnectionTimeout); Assert.IsInstanceOf<TestLogger>(cfg.Logger); var binType = cfg.BinaryConfiguration.TypeConfigurations.Single(); Assert.AreEqual("typeName", binType.TypeName); Assert.AreEqual("affKeyFieldName", binType.AffinityKeyFieldName); Assert.IsTrue(binType.IsEnum); Assert.AreEqual(true, binType.KeepDeserialized); Assert.IsInstanceOf<IdMapper>(binType.IdMapper); Assert.IsInstanceOf<NameMapper>(binType.NameMapper); Assert.IsInstanceOf<TestSerializer>(binType.Serializer); var plugins = cfg.PluginConfigurations; Assert.IsNotNull(plugins); Assert.IsNotNull(plugins.Cast<TestIgnitePluginConfiguration>().SingleOrDefault()); Assert.IsNotNull(cacheCfg.PluginConfigurations.Cast<MyPluginConfiguration>().SingleOrDefault()); var eventStorage = cfg.EventStorageSpi as MemoryEventStorageSpi; Assert.IsNotNull(eventStorage); Assert.AreEqual(23.45, eventStorage.ExpirationTimeout.TotalSeconds); Assert.AreEqual(129, eventStorage.MaxEventCount); var memCfg = cfg.MemoryConfiguration; Assert.IsNotNull(memCfg); Assert.AreEqual(3, memCfg.ConcurrencyLevel); Assert.AreEqual("dfPlc", memCfg.DefaultMemoryPolicyName); Assert.AreEqual(45, memCfg.PageSize); Assert.AreEqual(67, memCfg.SystemCacheInitialSize); Assert.AreEqual(68, memCfg.SystemCacheMaxSize); var memPlc = memCfg.MemoryPolicies.Single(); Assert.AreEqual(1, memPlc.EmptyPagesPoolSize); Assert.AreEqual(0.2, memPlc.EvictionThreshold); Assert.AreEqual("dfPlc", memPlc.Name); Assert.AreEqual(DataPageEvictionMode.RandomLru, memPlc.PageEvictionMode); Assert.AreEqual("abc", memPlc.SwapFilePath); Assert.AreEqual(89, memPlc.InitialSize); Assert.AreEqual(98, memPlc.MaxSize); Assert.IsTrue(memPlc.MetricsEnabled); Assert.AreEqual(9, memPlc.SubIntervals); Assert.AreEqual(TimeSpan.FromSeconds(62), memPlc.RateTimeInterval); Assert.AreEqual(PeerAssemblyLoadingMode.CurrentAppDomain, cfg.PeerAssemblyLoadingMode); var sql = cfg.SqlConnectorConfiguration; Assert.IsNotNull(sql); Assert.AreEqual("bar", sql.Host); Assert.AreEqual(10, sql.Port); Assert.AreEqual(11, sql.PortRange); Assert.AreEqual(12, sql.SocketSendBufferSize); Assert.AreEqual(13, sql.SocketReceiveBufferSize); Assert.IsTrue(sql.TcpNoDelay); Assert.AreEqual(14, sql.MaxOpenCursorsPerConnection); Assert.AreEqual(15, sql.ThreadPoolSize); var client = cfg.ClientConnectorConfiguration; Assert.IsNotNull(client); Assert.AreEqual("bar", client.Host); Assert.AreEqual(10, client.Port); Assert.AreEqual(11, client.PortRange); Assert.AreEqual(12, client.SocketSendBufferSize); Assert.AreEqual(13, client.SocketReceiveBufferSize); Assert.IsTrue(client.TcpNoDelay); Assert.AreEqual(14, client.MaxOpenCursorsPerConnection); Assert.AreEqual(15, client.ThreadPoolSize); Assert.AreEqual(19, client.IdleTimeout.TotalSeconds); var pers = cfg.PersistentStoreConfiguration; Assert.AreEqual(true, pers.AlwaysWriteFullPages); Assert.AreEqual(TimeSpan.FromSeconds(1), pers.CheckpointingFrequency); Assert.AreEqual(2, pers.CheckpointingPageBufferSize); Assert.AreEqual(3, pers.CheckpointingThreads); Assert.AreEqual(TimeSpan.FromSeconds(4), pers.LockWaitTime); Assert.AreEqual("foo", pers.PersistentStorePath); Assert.AreEqual(5, pers.TlbSize); Assert.AreEqual("bar", pers.WalArchivePath); Assert.AreEqual(TimeSpan.FromSeconds(6), pers.WalFlushFrequency); Assert.AreEqual(7, pers.WalFsyncDelayNanos); Assert.AreEqual(8, pers.WalHistorySize); Assert.AreEqual(WalMode.None, pers.WalMode); Assert.AreEqual(9, pers.WalRecordIteratorBufferSize); Assert.AreEqual(10, pers.WalSegments); Assert.AreEqual(11, pers.WalSegmentSize); Assert.AreEqual("baz", pers.WalStorePath); Assert.IsTrue(pers.MetricsEnabled); Assert.AreEqual(3, pers.SubIntervals); Assert.AreEqual(TimeSpan.FromSeconds(6), pers.RateTimeInterval); Assert.AreEqual(CheckpointWriteOrder.Random, pers.CheckpointWriteOrder); Assert.IsTrue(pers.WriteThrottlingEnabled); var listeners = cfg.LocalEventListeners; Assert.AreEqual(2, listeners.Count); var rebalListener = (LocalEventListener<CacheRebalancingEvent>) listeners.First(); Assert.AreEqual(new[] {EventType.CacheObjectPut, 81}, rebalListener.EventTypes); Assert.AreEqual("Apache.Ignite.Core.Tests.EventsTestLocalListeners+Listener`1" + "[Apache.Ignite.Core.Events.CacheRebalancingEvent]", rebalListener.Listener.GetType().ToString()); var ds = cfg.DataStorageConfiguration; Assert.IsFalse(ds.AlwaysWriteFullPages); Assert.AreEqual(TimeSpan.FromSeconds(1), ds.CheckpointFrequency); Assert.AreEqual(3, ds.CheckpointThreads); Assert.AreEqual(4, ds.ConcurrencyLevel); Assert.AreEqual(TimeSpan.FromSeconds(5), ds.LockWaitTime); Assert.IsTrue(ds.MetricsEnabled); Assert.AreEqual(6, ds.PageSize); Assert.AreEqual("cde", ds.StoragePath); Assert.AreEqual(TimeSpan.FromSeconds(7), ds.MetricsRateTimeInterval); Assert.AreEqual(8, ds.MetricsSubIntervalCount); Assert.AreEqual(9, ds.SystemRegionInitialSize); Assert.AreEqual(10, ds.SystemRegionMaxSize); Assert.AreEqual(11, ds.WalThreadLocalBufferSize); Assert.AreEqual("abc", ds.WalArchivePath); Assert.AreEqual(TimeSpan.FromSeconds(12), ds.WalFlushFrequency); Assert.AreEqual(13, ds.WalFsyncDelayNanos); Assert.AreEqual(14, ds.WalHistorySize); Assert.AreEqual(Core.Configuration.WalMode.Background, ds.WalMode); Assert.AreEqual(15, ds.WalRecordIteratorBufferSize); Assert.AreEqual(16, ds.WalSegments); Assert.AreEqual(17, ds.WalSegmentSize); Assert.AreEqual("wal-store", ds.WalPath); Assert.AreEqual(TimeSpan.FromSeconds(18), ds.WalAutoArchiveAfterInactivity); Assert.IsTrue(ds.WriteThrottlingEnabled); var dr = ds.DataRegionConfigurations.Single(); Assert.AreEqual(1, dr.EmptyPagesPoolSize); Assert.AreEqual(2, dr.EvictionThreshold); Assert.AreEqual(3, dr.InitialSize); Assert.AreEqual(4, dr.MaxSize); Assert.AreEqual("reg2", dr.Name); Assert.AreEqual(Core.Configuration.DataPageEvictionMode.RandomLru, dr.PageEvictionMode); Assert.AreEqual(TimeSpan.FromSeconds(1), dr.MetricsRateTimeInterval); Assert.AreEqual(5, dr.MetricsSubIntervalCount); Assert.AreEqual("swap", dr.SwapPath); Assert.IsTrue(dr.MetricsEnabled); Assert.AreEqual(7, dr.CheckpointPageBufferSize); dr = ds.DefaultDataRegionConfiguration; Assert.AreEqual(2, dr.EmptyPagesPoolSize); Assert.AreEqual(3, dr.EvictionThreshold); Assert.AreEqual(4, dr.InitialSize); Assert.AreEqual(5, dr.MaxSize); Assert.AreEqual("reg1", dr.Name); Assert.AreEqual(Core.Configuration.DataPageEvictionMode.Disabled, dr.PageEvictionMode); Assert.AreEqual(TimeSpan.FromSeconds(3), dr.MetricsRateTimeInterval); Assert.AreEqual(6, dr.MetricsSubIntervalCount); Assert.AreEqual("swap2", dr.SwapPath); Assert.IsFalse(dr.MetricsEnabled); Assert.IsInstanceOf<SslContextFactory>(cfg.SslContextFactory); Assert.IsInstanceOf<StopNodeOrHaltFailureHandler>(cfg.FailureHandler); var failureHandler = (StopNodeOrHaltFailureHandler)cfg.FailureHandler; Assert.IsTrue(failureHandler.TryStop); Assert.AreEqual(TimeSpan.Parse("0:1:0"), failureHandler.Timeout); } /// <summary> /// Tests the serialize deserialize. /// </summary> [Test] public void TestSerializeDeserialize() { // Test custom CheckSerializeDeserialize(GetTestConfig()); // Test custom with different culture to make sure numbers are serialized properly RunWithCustomCulture(() => CheckSerializeDeserialize(GetTestConfig())); // Test default CheckSerializeDeserialize(new IgniteConfiguration()); } /// <summary> /// Tests that all properties are present in the schema. /// </summary> [Test] public void TestAllPropertiesArePresentInSchema() { CheckAllPropertiesArePresentInSchema("IgniteConfigurationSection.xsd", "igniteConfiguration", typeof(IgniteConfiguration)); } /// <summary> /// Checks that all properties are present in schema. /// </summary> [SuppressMessage("ReSharper", "PossibleNullReferenceException")] public static void CheckAllPropertiesArePresentInSchema(string xsd, string sectionName, Type type) { var schema = XDocument.Load(xsd) .Root.Elements() .Single(x => x.Attribute("name").Value == sectionName); CheckPropertyIsPresentInSchema(type, schema); } /// <summary> /// Checks the property is present in schema. /// </summary> // ReSharper disable once UnusedParameter.Local // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void CheckPropertyIsPresentInSchema(Type type, XElement schema) { Func<string, string> toLowerCamel = x => char.ToLowerInvariant(x[0]) + x.Substring(1); foreach (var prop in type.GetProperties()) { if (!prop.CanWrite) continue; // Read-only properties are not configured in XML. if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()) continue; // Skip deprecated. var propType = prop.PropertyType; var isCollection = propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(ICollection<>); if (isCollection) propType = propType.GetGenericArguments().First(); var propName = toLowerCamel(prop.Name); Assert.IsTrue(schema.Descendants().Select(x => x.Attribute("name")) .Any(x => x != null && x.Value == propName), "Property is missing in XML schema: " + propName); var isComplexProp = propType.Namespace != null && propType.Namespace.StartsWith("Apache.Ignite.Core"); if (isComplexProp) CheckPropertyIsPresentInSchema(propType, schema); } } /// <summary> /// Tests the schema validation. /// </summary> [Test] public void TestSchemaValidation() { CheckSchemaValidation(); RunWithCustomCulture(CheckSchemaValidation); // Check invalid xml const string invalidXml = @"<igniteConfiguration xmlns='http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection'> <binaryConfiguration /><binaryConfiguration /> </igniteConfiguration>"; Assert.Throws<XmlSchemaValidationException>(() => CheckSchemaValidation(invalidXml)); } /// <summary> /// Tests the XML conversion. /// </summary> [Test] public void TestToXml() { // Empty config Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<igniteConfiguration " + "xmlns=\"http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection\" />", new IgniteConfiguration().ToXml()); // Some properties var cfg = new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true, CacheConfiguration = new[] { new CacheConfiguration("myCache") { CacheMode = CacheMode.Replicated, QueryEntities = new[] { new QueryEntity(typeof(int)), new QueryEntity(typeof(int), typeof(string)) } } }, IncludedEventTypes = new[] { EventType.CacheEntryCreated, EventType.CacheNodesLeft } }; Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?> <igniteConfiguration clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection""> <cacheConfiguration> <cacheConfiguration cacheMode=""Replicated"" name=""myCache""> <queryEntities> <queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" /> <queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" /> </queryEntities> </cacheConfiguration> </cacheConfiguration> <includedEventTypes> <int>CacheEntryCreated</int> <int>CacheNodesLeft</int> </includedEventTypes> </igniteConfiguration>"), cfg.ToXml()); // Custom section name and indent var sb = new StringBuilder(); var settings = new XmlWriterSettings { Indent = true, IndentChars = " " }; using (var xmlWriter = XmlWriter.Create(sb, settings)) { cfg.ToXml(xmlWriter, "igCfg"); } Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?> <igCfg clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection""> <cacheConfiguration> <cacheConfiguration cacheMode=""Replicated"" name=""myCache""> <queryEntities> <queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" /> <queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" /> </queryEntities> </cacheConfiguration> </cacheConfiguration> <includedEventTypes> <int>CacheEntryCreated</int> <int>CacheNodesLeft</int> </includedEventTypes> </igCfg>"), sb.ToString()); } /// <summary> /// Tests the deserialization. /// </summary> [Test] public void TestFromXml() { // Empty section. var cfg = IgniteConfiguration.FromXml("<x />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg); // Empty section with XML header. cfg = IgniteConfiguration.FromXml("<?xml version=\"1.0\" encoding=\"utf-16\"?><x />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg); // Simple test. cfg = IgniteConfiguration.FromXml(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration {IgniteInstanceName = "myGrid", ClientMode = true}, cfg); // Invalid xml. var ex = Assert.Throws<ConfigurationErrorsException>(() => IgniteConfiguration.FromXml(@"<igCfg foo=""bar"" />")); Assert.AreEqual("Invalid IgniteConfiguration attribute 'foo=bar', there is no such property " + "on 'Apache.Ignite.Core.IgniteConfiguration'", ex.Message); // Xml reader. using (var xmlReader = XmlReader.Create( new StringReader(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />"))) { cfg = IgniteConfiguration.FromXml(xmlReader); } AssertExtensions.ReflectionEqual(new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true }, cfg); } /// <summary> /// Ensures windows-style \r\n line endings in a string literal. /// Git settings may cause string literals in both styles. /// </summary> private static string FixLineEndings(string s) { return s.Split('\n').Select(x => x.TrimEnd('\r')) .Aggregate((acc, x) => string.Format("{0}\r\n{1}", acc, x)); } /// <summary> /// Checks the schema validation. /// </summary> private static void CheckSchemaValidation() { CheckSchemaValidation(GetTestConfig().ToXml()); } /// <summary> /// Checks the schema validation. /// </summary> private static void CheckSchemaValidation(string xml) { var xmlns = "http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection"; var schemaFile = "IgniteConfigurationSection.xsd"; CheckSchemaValidation(xml, xmlns, schemaFile); } /// <summary> /// Checks the schema validation. /// </summary> public static void CheckSchemaValidation(string xml, string xmlns, string schemaFile) { var document = new XmlDocument(); document.Schemas.Add(xmlns, XmlReader.Create(schemaFile)); document.Load(new StringReader(xml)); document.Validate(null); } /// <summary> /// Checks the serialize deserialize. /// </summary> /// <param name="cfg">The config.</param> private static void CheckSerializeDeserialize(IgniteConfiguration cfg) { var resCfg = SerializeDeserialize(cfg); AssertExtensions.ReflectionEqual(cfg, resCfg); } /// <summary> /// Serializes and deserializes a config. /// </summary> private static IgniteConfiguration SerializeDeserialize(IgniteConfiguration cfg) { var xml = cfg.ToXml(); return IgniteConfiguration.FromXml(xml); } /// <summary> /// Gets the test configuration. /// </summary> private static IgniteConfiguration GetTestConfig() { return new IgniteConfiguration { IgniteInstanceName = "gridName", JvmOptions = new[] {"1", "2"}, Localhost = "localhost11", JvmClasspath = "classpath", Assemblies = new[] {"asm1", "asm2", "asm3"}, BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new[] { new BinaryTypeConfiguration { IsEnum = true, KeepDeserialized = true, AffinityKeyFieldName = "affKeyFieldName", TypeName = "typeName", IdMapper = new IdMapper(), NameMapper = new NameMapper(), Serializer = new TestSerializer() }, new BinaryTypeConfiguration { IsEnum = false, KeepDeserialized = false, AffinityKeyFieldName = "affKeyFieldName", TypeName = "typeName2", Serializer = new BinaryReflectiveSerializer() } }, Types = new[] {typeof(string).FullName}, IdMapper = new IdMapper(), KeepDeserialized = true, NameMapper = new NameMapper(), Serializer = new TestSerializer() }, CacheConfiguration = new[] { new CacheConfiguration("cacheName") { AtomicityMode = CacheAtomicityMode.Transactional, Backups = 15, CacheMode = CacheMode.Replicated, CacheStoreFactory = new TestCacheStoreFactory(), CopyOnRead = false, EagerTtl = false, Invalidate = true, KeepBinaryInStore = true, LoadPreviousValue = true, LockTimeout = TimeSpan.FromSeconds(56), MaxConcurrentAsyncOperations = 24, QueryEntities = new[] { new QueryEntity { Fields = new[] { new QueryField("field", typeof(int)) { IsKeyField = true, NotNull = true, DefaultValue = "foo" } }, Indexes = new[] { new QueryIndex("field") { IndexType = QueryIndexType.FullText, InlineSize = 32 } }, Aliases = new[] { new QueryAlias("field.field", "fld") }, KeyType = typeof(string), ValueType = typeof(long), TableName = "table-1", KeyFieldName = "k", ValueFieldName = "v" }, }, ReadFromBackup = false, RebalanceBatchSize = 33, RebalanceDelay = TimeSpan.MaxValue, RebalanceMode = CacheRebalanceMode.Sync, RebalanceThrottle = TimeSpan.FromHours(44), RebalanceTimeout = TimeSpan.FromMinutes(8), SqlEscapeAll = true, WriteBehindBatchSize = 45, WriteBehindEnabled = true, WriteBehindFlushFrequency = TimeSpan.FromSeconds(55), WriteBehindFlushSize = 66, WriteBehindFlushThreadCount = 2, WriteBehindCoalescing = false, WriteSynchronizationMode = CacheWriteSynchronizationMode.FullAsync, NearConfiguration = new NearCacheConfiguration { NearStartSize = 5, EvictionPolicy = new FifoEvictionPolicy { BatchSize = 19, MaxMemorySize = 1024, MaxSize = 555 } }, EvictionPolicy = new LruEvictionPolicy { BatchSize = 18, MaxMemorySize = 1023, MaxSize = 554 }, AffinityFunction = new RendezvousAffinityFunction { ExcludeNeighbors = true, Partitions = 48 }, ExpiryPolicyFactory = new MyPolicyFactory(), EnableStatistics = true, PluginConfigurations = new[] { new MyPluginConfiguration() }, MemoryPolicyName = "somePolicy", PartitionLossPolicy = PartitionLossPolicy.ReadOnlyAll, GroupName = "abc", SqlIndexMaxInlineSize = 24, KeyConfiguration = new[] { new CacheKeyConfiguration { AffinityKeyFieldName = "abc", TypeName = "def" }, }, OnheapCacheEnabled = true, StoreConcurrentLoadAllThreshold = 7, RebalanceOrder = 3, RebalanceBatchesPrefetchCount = 4, MaxQueryIteratorsCount = 512, QueryDetailMetricsSize = 100, QueryParallelism = 16, SqlSchema = "foo" } }, ClientMode = true, DiscoverySpi = new TcpDiscoverySpi { NetworkTimeout = TimeSpan.FromSeconds(1), SocketTimeout = TimeSpan.FromSeconds(2), AckTimeout = TimeSpan.FromSeconds(3), JoinTimeout = TimeSpan.FromSeconds(4), MaxAckTimeout = TimeSpan.FromSeconds(5), IpFinder = new TcpDiscoveryMulticastIpFinder { TimeToLive = 110, MulticastGroup = "multicastGroup", AddressRequestAttempts = 10, MulticastPort = 987, ResponseTimeout = TimeSpan.FromDays(1), LocalAddress = "127.0.0.2", Endpoints = new[] {"", "abc"} }, ClientReconnectDisabled = true, ForceServerMode = true, IpFinderCleanFrequency = TimeSpan.FromMinutes(7), LocalAddress = "127.0.0.1", LocalPort = 49900, LocalPortRange = 13, ReconnectCount = 11, StatisticsPrintFrequency = TimeSpan.FromSeconds(20), ThreadPriority = 6, TopologyHistorySize = 1234567 }, IgniteHome = "igniteHome", IncludedEventTypes = EventType.CacheQueryAll, JvmDllPath = @"c:\jvm", JvmInitialMemoryMb = 1024, JvmMaxMemoryMb = 2048, LifecycleHandlers = new[] {new LifecycleBean(), new LifecycleBean()}, MetricsExpireTime = TimeSpan.FromSeconds(15), MetricsHistorySize = 45, MetricsLogFrequency = TimeSpan.FromDays(2), MetricsUpdateFrequency = TimeSpan.MinValue, NetworkSendRetryCount = 7, NetworkSendRetryDelay = TimeSpan.FromSeconds(98), NetworkTimeout = TimeSpan.FromMinutes(4), SuppressWarnings = true, WorkDirectory = @"c:\work", IsDaemon = true, UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(), x => x % 2 == 0 ? (object) x : new FooClass {Bar = x.ToString()}), AtomicConfiguration = new AtomicConfiguration { CacheMode = CacheMode.Replicated, AtomicSequenceReserveSize = 200, Backups = 2 }, TransactionConfiguration = new TransactionConfiguration { PessimisticTransactionLogSize = 23, DefaultTransactionIsolation = TransactionIsolation.ReadCommitted, DefaultTimeout = TimeSpan.FromDays(2), DefaultTransactionConcurrency = TransactionConcurrency.Optimistic, PessimisticTransactionLogLinger = TimeSpan.FromHours(3) }, CommunicationSpi = new TcpCommunicationSpi { LocalPort = 47501, MaxConnectTimeout = TimeSpan.FromSeconds(34), MessageQueueLimit = 15, ConnectTimeout = TimeSpan.FromSeconds(17), IdleConnectionTimeout = TimeSpan.FromSeconds(19), SelectorsCount = 8, ReconnectCount = 33, SocketReceiveBufferSize = 512, AckSendThreshold = 99, DirectBuffer = false, DirectSendBuffer = true, LocalPortRange = 45, LocalAddress = "127.0.0.1", TcpNoDelay = false, SlowClientQueueLimit = 98, SocketSendBufferSize = 2045, UnacknowledgedMessagesBufferSize = 3450 }, SpringConfigUrl = "test", Logger = new IgniteNLogLogger(), FailureDetectionTimeout = TimeSpan.FromMinutes(2), ClientFailureDetectionTimeout = TimeSpan.FromMinutes(3), LongQueryWarningTimeout = TimeSpan.FromDays(4), PluginConfigurations = new[] {new TestIgnitePluginConfiguration()}, EventStorageSpi = new MemoryEventStorageSpi { ExpirationTimeout = TimeSpan.FromMilliseconds(12345), MaxEventCount = 257 }, MemoryConfiguration = new MemoryConfiguration { ConcurrencyLevel = 3, DefaultMemoryPolicyName = "somePolicy", PageSize = 4, SystemCacheInitialSize = 5, SystemCacheMaxSize = 6, MemoryPolicies = new[] { new MemoryPolicyConfiguration { Name = "myDefaultPlc", PageEvictionMode = DataPageEvictionMode.Random2Lru, InitialSize = 245 * 1024 * 1024, MaxSize = 345 * 1024 * 1024, EvictionThreshold = 0.88, EmptyPagesPoolSize = 77, SwapFilePath = "myPath1", RateTimeInterval = TimeSpan.FromSeconds(22), SubIntervals = 99 }, new MemoryPolicyConfiguration { Name = "customPlc", PageEvictionMode = DataPageEvictionMode.RandomLru, EvictionThreshold = 0.77, EmptyPagesPoolSize = 66, SwapFilePath = "somePath2", MetricsEnabled = true } } }, PeerAssemblyLoadingMode = PeerAssemblyLoadingMode.CurrentAppDomain, ClientConnectorConfiguration = new ClientConnectorConfiguration { Host = "foo", Port = 2, PortRange = 3, MaxOpenCursorsPerConnection = 4, SocketReceiveBufferSize = 5, SocketSendBufferSize = 6, TcpNoDelay = false, ThinClientEnabled = false, OdbcEnabled = false, JdbcEnabled = false, ThreadPoolSize = 7, IdleTimeout = TimeSpan.FromMinutes(5) }, PersistentStoreConfiguration = new PersistentStoreConfiguration { AlwaysWriteFullPages = true, CheckpointingFrequency = TimeSpan.FromSeconds(25), CheckpointingPageBufferSize = 28 * 1024 * 1024, CheckpointingThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), PersistentStorePath = Path.GetTempPath(), TlbSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = WalMode.Background, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalStorePath = Path.GetTempPath(), SubIntervals = 25, MetricsEnabled = true, RateTimeInterval = TimeSpan.FromDays(1), CheckpointWriteOrder = CheckpointWriteOrder.Random, WriteThrottlingEnabled = true }, IsActiveOnStart = false, ConsistentId = "myId123", LocalEventListeners = new[] { new LocalEventListener<IEvent> { EventTypes = new[] {1, 2}, Listener = new MyEventListener() } }, DataStorageConfiguration = new DataStorageConfiguration { AlwaysWriteFullPages = true, CheckpointFrequency = TimeSpan.FromSeconds(25), CheckpointThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), StoragePath = Path.GetTempPath(), WalThreadLocalBufferSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = Core.Configuration.WalMode.None, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalPath = Path.GetTempPath(), MetricsEnabled = true, MetricsSubIntervalCount = 7, MetricsRateTimeInterval = TimeSpan.FromSeconds(9), CheckpointWriteOrder = Core.Configuration.CheckpointWriteOrder.Sequential, WriteThrottlingEnabled = true, SystemRegionInitialSize = 64 * 1024 * 1024, SystemRegionMaxSize = 128 * 1024 * 1024, ConcurrencyLevel = 1, PageSize = 5 * 1024, WalAutoArchiveAfterInactivity = TimeSpan.FromSeconds(19), DefaultDataRegionConfiguration = new DataRegionConfiguration { Name = "reg1", EmptyPagesPoolSize = 50, EvictionThreshold = 0.8, InitialSize = 100 * 1024 * 1024, MaxSize = 150 * 1024 * 1024, MetricsEnabled = true, PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(2), MetricsSubIntervalCount = 6, SwapPath = Path.GetTempPath(), CheckpointPageBufferSize = 7 }, DataRegionConfigurations = new[] { new DataRegionConfiguration { Name = "reg2", EmptyPagesPoolSize = 51, EvictionThreshold = 0.7, InitialSize = 101 * 1024 * 1024, MaxSize = 151 * 1024 * 1024, MetricsEnabled = false, PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(3), MetricsSubIntervalCount = 7, SwapPath = Path.GetTempPath() } } }, SslContextFactory = new SslContextFactory(), FailureHandler = new StopNodeOrHaltFailureHandler() { TryStop = false, Timeout = TimeSpan.FromSeconds(10) } }; } /// <summary> /// Runs the with custom culture. /// </summary> /// <param name="action">The action.</param> private static void RunWithCustomCulture(Action action) { RunWithCulture(action, CultureInfo.InvariantCulture); RunWithCulture(action, CultureInfo.GetCultureInfo("ru-RU")); } /// <summary> /// Runs the with culture. /// </summary> /// <param name="action">The action.</param> /// <param name="cultureInfo">The culture information.</param> private static void RunWithCulture(Action action, CultureInfo cultureInfo) { var oldCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = cultureInfo; action(); } finally { Thread.CurrentThread.CurrentCulture = oldCulture; } } /// <summary> /// Test bean. /// </summary> public class LifecycleBean : ILifecycleHandler { /// <summary> /// Gets or sets the foo. /// </summary> /// <value> /// The foo. /// </value> public int Foo { get; set; } /// <summary> /// This method is called when lifecycle event occurs. /// </summary> /// <param name="evt">Lifecycle event.</param> public void OnLifecycleEvent(LifecycleEventType evt) { // No-op. } } /// <summary> /// Test mapper. /// </summary> public class NameMapper : IBinaryNameMapper { /// <summary> /// Gets or sets the bar. /// </summary> /// <value> /// The bar. /// </value> public string Bar { get; set; } /// <summary> /// Gets the type name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// Type name. /// </returns> public string GetTypeName(string name) { return name; } /// <summary> /// Gets the field name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// Field name. /// </returns> public string GetFieldName(string name) { return name; } } /// <summary> /// Serializer. /// </summary> public class TestSerializer : IBinarySerializer { /** <inheritdoc /> */ public void WriteBinary(object obj, IBinaryWriter writer) { // No-op. } /** <inheritdoc /> */ public void ReadBinary(object obj, IBinaryReader reader) { // No-op. } } /// <summary> /// Test class. /// </summary> public class FooClass { public string Bar { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return string.Equals(Bar, ((FooClass) obj).Bar); } public override int GetHashCode() { return Bar != null ? Bar.GetHashCode() : 0; } public static bool operator ==(FooClass left, FooClass right) { return Equals(left, right); } public static bool operator !=(FooClass left, FooClass right) { return !Equals(left, right); } } /// <summary> /// Test factory. /// </summary> public class TestCacheStoreFactory : IFactory<ICacheStore> { /// <summary> /// Creates an instance of the cache store. /// </summary> /// <returns> /// New instance of the cache store. /// </returns> public ICacheStore CreateInstance() { return null; } } /// <summary> /// Test logger. /// </summary> public class TestLogger : ILogger { /** <inheritdoc /> */ public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider, string category, string nativeErrorInfo, Exception ex) { throw new NotImplementedException(); } /** <inheritdoc /> */ public bool IsEnabled(LogLevel level) { throw new NotImplementedException(); } } /// <summary> /// Test factory. /// </summary> public class MyPolicyFactory : IFactory<IExpiryPolicy> { /** <inheritdoc /> */ public IExpiryPolicy CreateInstance() { throw new NotImplementedException(); } } public class MyPluginConfiguration : ICachePluginConfiguration { int? ICachePluginConfiguration.CachePluginConfigurationClosureFactoryId { get { return 0; } } void ICachePluginConfiguration.WriteBinary(IBinaryRawWriter writer) { throw new NotImplementedException(); } } public class MyEventListener : IEventListener<IEvent> { public bool Invoke(IEvent evt) { throw new NotImplementedException(); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ManifestBasedResourceGroveler ** ** <OWNER>[....]</OWNER> ** ** ** Purpose: Searches for resources in Assembly manifest, used ** for assembly-based resource lookup. ** ** ===========================================================*/ namespace System.Resources { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Diagnostics.Contracts; using Microsoft.Win32; #if !FEATURE_CORECLR using System.Diagnostics.Tracing; #endif // // Note: this type is integral to the construction of exception objects, // and sometimes this has to be done in low memory situtations (OOM) or // to create TypeInitializationExceptions due to failure of a static class // constructor. This type needs to be extremely careful and assume that // any type it references may have previously failed to construct, so statics // belonging to that type may not be initialized. FrameworkEventSource.Log // is one such example. // internal class ManifestBasedResourceGroveler : IResourceGroveler { private ResourceManager.ResourceManagerMediator _mediator; public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { // here and below: convert asserts to preconditions where appropriate when we get // contracts story in place. Contract.Requires(mediator != null, "mediator shouldn't be null; check caller"); _mediator = mediator; } [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark) { Contract.Assert(culture != null, "culture shouldn't be null; check caller"); Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); ResourceSet rs = null; Stream stream = null; RuntimeAssembly satellite = null; // 1. Fixups for ultimate fallbacks CultureInfo lookForCulture = UltimateFallbackFixup(culture); // 2. Look for satellite assembly or main assembly, as appropriate if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { // don't bother looking in satellites in this case satellite = _mediator.MainAssembly; } #if RESOURCE_SATELLITE_CONFIG // If our config file says the satellite isn't here, don't ask for it. else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture)) { satellite = null; } #endif else { satellite = GetSatelliteAssembly(lookForCulture, ref stackMark); if (satellite == null) { bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)); // didn't find satellite, give error if necessary if (raiseException) { HandleSatelliteMissing(); } } } // get resource file name we'll search for. Note, be careful if you're moving this statement // around because lookForCulture may be modified from originally requested culture above. String fileName = _mediator.GetResourceFileName(lookForCulture); // 3. If we identified an assembly to search; look in manifest resource stream for resource file if (satellite != null) { // Handle case in here where someone added a callback for assembly load events. // While no other threads have called into GetResourceSet, our own thread can! // At that point, we could already have an RS in our hash table, and we don't // want to add it twice. lock (localResourceSets) { if (localResourceSets.TryGetValue(culture.Name, out rs)) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(_mediator.BaseName, _mediator.MainAssembly, culture.Name); } #endif } } stream = GetManifestResourceStream(satellite, fileName, ref stackMark); } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (stream != null) { FrameworkEventSource.Log.ResourceManagerStreamFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName); } else { FrameworkEventSource.Log.ResourceManagerStreamNotFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName); } } #endif // 4a. Found a stream; create a ResourceSet if possible if (createIfNotExists && stream != null && rs == null) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name, fileName); } #endif rs = CreateResourceSet(stream, satellite); } else if (stream == null && tryParents) { // 4b. Didn't find stream; give error if necessary bool raiseException = culture.HasInvariantCultureName; if (raiseException) { HandleResourceStreamMissing(fileName); } } #if !FEATURE_CORECLR if (!createIfNotExists && stream != null && rs == null) { if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name); } } #endif return rs; } #if !FEATURE_CORECLR // Returns whether or not the main assembly contains a particular resource // file in it's assembly manifest. Used to verify that the neutral // Culture's .resources file is present in the main assembly public bool HasNeutralResources(CultureInfo culture, String defaultResName) { String resName = defaultResName; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter + defaultResName; String[] resourceFiles = _mediator.MainAssembly.GetManifestResourceNames(); foreach(String s in resourceFiles) if (s.Equals(resName)) return true; return false; } #endif private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture) { CultureInfo returnCulture = lookForCulture; // If our neutral resources were written in this culture AND we know the main assembly // does NOT contain neutral resources, don't probe for this satellite. if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNeutralResourcesSufficient(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name); } #endif returnCulture = CultureInfo.InvariantCulture; } else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite) { returnCulture = _mediator.NeutralResourcesCulture; } return returnCulture; } [System.Security.SecurityCritical] internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation) { #if FEATURE_LEGACYNETCF // Windows Phone 7.0/7.1 ignore NeutralResourceLanguage attribute and // defaults fallbackLocation to MainAssembly if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return CultureInfo.InvariantCulture; } #endif Contract.Assert(a != null, "assembly != null"); string cultureName = null; short fallback = 0; if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref cultureName), out fallback)) { if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallback)); } fallbackLocation = (UltimateResourceFallbackLocation)fallback; } else { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNeutralResourceAttributeMissing(a); } #endif fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return CultureInfo.InvariantCulture; } try { CultureInfo c = CultureInfo.GetCultureInfo(cultureName); return c; } catch (ArgumentException e) { // we should catch ArgumentException only. // Note we could go into infinite loops if mscorlib's // NeutralResourcesLanguageAttribute is mangled. If this assert // fires, please fix the build process for the BCL directory. if (a == typeof(Object).Assembly) { Contract.Assert(false, "mscorlib's NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e); return CultureInfo.InvariantCulture; } throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", a.ToString(), cultureName), e); } } // Constructs a new ResourceSet for a given file name. The logic in // here avoids a ReflectionPermission check for our RuntimeResourceSet // for perf and working set reasons. // Use the assembly to resolve assembly manifest resource references. // Note that is can be null, but probably shouldn't be. // This method could use some refactoring. One thing at a time. [System.Security.SecurityCritical] internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) { Contract.Assert(store != null, "I need a Stream!"); // Check to see if this is a Stream the ResourceManager understands, // and check for the correct resource reader type. if (store.CanSeek && store.Length > 4) { long startPos = store.Position; // not disposing because we want to leave stream open BinaryReader br = new BinaryReader(store); // Look for our magic number as a little endian Int32. int bytes = br.ReadInt32(); if (bytes == ResourceManager.MagicNumber) { int resMgrHeaderVersion = br.ReadInt32(); String readerTypeName = null, resSetTypeName = null; if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber) { br.ReadInt32(); // We don't want the number of bytes to skip. readerTypeName = br.ReadString(); resSetTypeName = br.ReadString(); } else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber) { // Assume that the future ResourceManager headers will // have two strings for us - the reader type name and // resource set type name. Read those, then use the num // bytes to skip field to correct our position. int numBytesToSkip = br.ReadInt32(); long endPosition = br.BaseStream.Position + numBytesToSkip; readerTypeName = br.ReadString(); resSetTypeName = br.ReadString(); br.BaseStream.Seek(endPosition, SeekOrigin.Begin); } else { // resMgrHeaderVersion is older than this ResMgr version. // We should add in backwards compatibility support here. throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", _mediator.MainAssembly.GetSimpleName())); } store.Position = startPos; // Perf optimization - Don't use Reflection for our defaults. // Note there are two different sets of strings here - the // assembly qualified strings emitted by ResourceWriter, and // the abbreviated ones emitted by InternalResGen. if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName)) { RuntimeResourceSet rs; #if LOOSELY_LINKED_RESOURCE_REFERENCE rs = new RuntimeResourceSet(store, assembly); #else rs = new RuntimeResourceSet(store); #endif // LOOSELY_LINKED_RESOURCE_REFERENCE return rs; } else { // we do not want to use partial binding here. Type readerType = Type.GetType(readerTypeName, true); Object[] args = new Object[1]; args[0] = store; IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args); Object[] resourceSetArgs = #if LOOSELY_LINKED_RESOURCE_REFERENCE new Object[2]; #else new Object[1]; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE resourceSetArgs[0] = reader; #if LOOSELY_LINKED_RESOURCE_REFERENCE resourceSetArgs[1] = assembly; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE Type resSetType; if (_mediator.UserResourceSet == null) { Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here."); resSetType = Type.GetType(resSetTypeName, true, false); } else resSetType = _mediator.UserResourceSet; ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, resourceSetArgs, null, null); return rs; } } else { store.Position = startPos; } } if (_mediator.UserResourceSet == null) { // Explicitly avoid CreateInstance if possible, because it // requires ReflectionPermission to call private & protected // constructors. #if LOOSELY_LINKED_RESOURCE_REFERENCE return new RuntimeResourceSet(store, assembly); #else return new RuntimeResourceSet(store); #endif // LOOSELY_LINKED_RESOURCE_REFERENCE } else { Object[] args = new Object[2]; args[0] = store; args[1] = assembly; try { ResourceSet rs = null; // Add in a check for a constructor taking in an assembly first. try { rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); return rs; } catch (MissingMethodException) { } args = new Object[1]; args[0] = store; rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); #if LOOSELY_LINKED_RESOURCE_REFERENCE rs.Assembly = assembly; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE return rs; } catch (MissingMethodException e) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e); } } } [System.Security.SecurityCritical] private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark) { Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); Contract.Requires(fileName != null, "fileName shouldn't be null; check caller"); // If we're looking in the main assembly AND if the main assembly was the person who // created the ResourceManager, skip a security check for private manifest resources. bool canSkipSecurityCheck = (_mediator.MainAssembly == satellite) && (_mediator.CallingAssembly == _mediator.MainAssembly); Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName, canSkipSecurityCheck, ref stackMark); if (stream == null) { stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName); } return stream; } // Looks up a .resources file in the assembly manifest using // case-insensitive lookup rules. Yes, this is slow. The metadata // dev lead refuses to make all assembly manifest resource lookups case-insensitive, // even optionally case-insensitive. [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name) { Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); Contract.Requires(name != null, "name shouldn't be null; check caller"); StringBuilder sb = new StringBuilder(); if (_mediator.LocationInfo != null) { String nameSpace = _mediator.LocationInfo.Namespace; if (nameSpace != null) { sb.Append(nameSpace); if (name != null) sb.Append(Type.Delimiter); } } sb.Append(name); String givenName = sb.ToString(); CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; String canonicalName = null; foreach (String existingName in satellite.GetManifestResourceNames()) { if (comparer.Compare(existingName, givenName, CompareOptions.IgnoreCase) == 0) { if (canonicalName == null) { canonicalName = existingName; } else { throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_MultipleBlobs", givenName, satellite.ToString())); } } } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (canonicalName != null) { FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName); } else { FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupFailed(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName); } } #endif if (canonicalName == null) { return null; } // If we're looking in the main assembly AND if the main // assembly was the person who created the ResourceManager, // skip a security check for private manifest resources. bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly; StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Stream s = satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck); // GetManifestResourceStream will return null if we don't have // permission to read this stream from the assembly. For example, // if the stream is private and we're trying to access it from another // assembly (ie, ResMgr in mscorlib accessing anything else), we // require Reflection TypeInformation permission to be able to read // this. <STRIP>This meaning of private in satellite assemblies is a really // odd concept, and is orthogonal to the ResourceManager. // We should not assume we can skip this security check, // which means satellites must always use public manifest resources // if you want to support semi-trusted code. </STRIP> #if !FEATURE_CORECLR if (s!=null) { if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerManifestResourceAccessDenied(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), canonicalName); } } #endif return s; } [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark) { if (!_mediator.LookedForSatelliteContractVersion) { _mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly); _mediator.LookedForSatelliteContractVersion = true; } RuntimeAssembly satellite = null; String satAssemblyName = GetSatelliteAssemblyName(); // Look up the satellite assembly, but don't let problems // like a partially signed satellite assembly stop us from // doing fallback and displaying something to the user. // Yet also somehow log this error for a developer. try { satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark); } // Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback. // catch (FileLoadException fle) { // Ignore cases where the loader gets an access // denied back from the OS. This showed up for // href-run exe's at one point. int hr = fle._HResult; if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED)) { Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle); } } // Don't throw for zero-length satellite assemblies, for compat with v1 catch (BadImageFormatException bife) { Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife); } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (satellite != null) { FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblySucceeded(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName); } else { FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblyFailed(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName); } } #endif return satellite; } // Perf optimization - Don't use Reflection for most cases with // our .resources files. This makes our code run faster and we can // creating a ResourceReader via Reflection. This would incur // a security check (since the link-time check on the constructor that // takes a String is turned into a full demand with a stack walk) // and causes partially trusted localized apps to fail. private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName) { Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller"); Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller"); if (_mediator.UserResourceSet != null) return false; // Ignore the actual version of the ResourceReader and // RuntimeResourceSet classes. Let those classes deal with // versioning themselves. AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName); if (readerTypeName != null) { if (!ResourceManager.CompareNames(readerTypeName, ResourceManager.ResReaderTypeName, mscorlib)) return false; } if (resSetTypeName != null) { if (!ResourceManager.CompareNames(resSetTypeName, ResourceManager.ResSetTypeName, mscorlib)) return false; } return true; } [System.Security.SecurityCritical] private String GetSatelliteAssemblyName() { String satAssemblyName = _mediator.MainAssembly.GetSimpleName(); satAssemblyName += ".resources"; return satAssemblyName; } [System.Security.SecurityCritical] private void HandleSatelliteMissing() { String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll"; if (_mediator.SatelliteContractVersion != null) { satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString(); } AssemblyName an = new AssemblyName(); an.SetPublicKey(_mediator.MainAssembly.GetPublicKey()); byte[] token = an.GetPublicKeyToken(); int iLen = token.Length; StringBuilder publicKeyTok = new StringBuilder(iLen * 2); for (int i = 0; i < iLen; i++) { publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture)); } satAssemName += ", PublicKeyToken=" + publicKeyTok; String missingCultureName = _mediator.NeutralResourcesCulture.Name; if (missingCultureName.Length == 0) { missingCultureName = "<invariant>"; } throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName); } [System.Security.SecurityCritical] // auto-generated private void HandleResourceStreamMissing(String fileName) { // Keep people from bothering me about resources problems if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals("mscorlib")) { // This would break CultureInfo & all our exceptions. Contract.Assert(false, "Couldn't get mscorlib" + ResourceManager.ResFileExtension + " from mscorlib's assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug."); // We cannot continue further - simply FailFast. string mesgFailFast = "mscorlib" + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!"; System.Environment.FailFast(mesgFailFast); } // We really don't think this should happen - we always // expect the neutral locale's resources to be present. String resName = String.Empty; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter; resName += fileName; throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralAsm", resName, _mediator.MainAssembly.GetSimpleName())); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods. [ResourceExposure(ResourceScope.None)] [System.Security.SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation); } }
namespace TaskManager { using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Threading; using TaskManager.Configuration; /// <summary> /// Loads and unloads modules, and listen for module file changes to reload the module when necessary. /// </summary> internal static class ModuleSupervisor { /// <summary> /// Default module zip file extension. /// </summary> public const string ZipFileDefaultExtension = ".zip"; /// <summary> /// Default module file extension. /// </summary> public const string ModuleFileDefaultExtension = ".dll"; /// <summary> /// Default module configuration file extension. /// </summary> public const string ConfigFileDefaultExtension = ".xml"; /// <summary> /// List of known loaded modules. /// </summary> private static List<ModuleData> _moduleList; /// <summary> /// Enumeration lock. /// </summary> private static object _moduleListLock; /// <summary> /// File system watcher. /// </summary> private static FileSystemWatcher _fileSystemWatcher; /// <summary> /// The time when the next reload should occur. /// </summary> private static DateTime _reload; /// <summary> /// Loader lock. /// </summary> private static object _reloadLock; /// <summary> /// Reloading thread. /// </summary> private static Thread _reloadThread; /// <summary> /// Initializes static members of the <see cref="ModuleSupervisor"/> class. /// </summary> static ModuleSupervisor() { _moduleListLock = new object(); _reloadLock = new object(); _reload = DateTime.Now; _reloadThread = null; } /// <summary> /// Initializes the supervisor. /// </summary> public static void Initialize() { _moduleList = new List<ModuleData>(); lock (_moduleListLock) { LoadAndConfigure(false); } if (_moduleList.Count < 1) { throw new Exception("Unable to locate task modules."); } StartMonitoringFileSystem(); } /// <summary> /// Loads all modules. /// </summary> public static void Execute() { if (null == _moduleList) { throw new Exception("TaskManager failed to initialize."); } lock (_moduleListLock) { foreach (ModuleData module in _moduleList) { foreach (TaskWrapper task in module.Tasks) { TaskManagerService.Logger.Log(string.Format("Registering task '{0}'...", task.TaskName)); TaskSupervisor.ScheduleTask(task); } } } } /// <summary> /// Unloads all modules. /// </summary> public static void Shutdown() { if (null == _moduleList) { throw new Exception("TaskManager failed to initialize."); } _fileSystemWatcher.EnableRaisingEvents = false; if (_reloadThread != null) { _reloadThread.Abort(); _reloadThread.Join(); } lock (_moduleListLock) { for (int i = _moduleList.Count - 1; i >= 0; i--) { StopModule(_moduleList[i]); } } } #region Module loading /// <summary> /// Locates and configures all modules. /// </summary> /// <param name="startImmediately">True if execution should be started immediately after configuring all modules, false if modules should be configured but not started.</param> public static void LoadAndConfigure(bool startImmediately) { string basePath = AppDomain.CurrentDomain.BaseDirectory; List<string> filesToScan = new List<string>(); filesToScan.AddRange(Directory.GetFiles(basePath, "*" + ModuleFileDefaultExtension, SearchOption.AllDirectories)); filesToScan.AddRange(Directory.GetFiles(basePath, "*" + ZipFileDefaultExtension, SearchOption.AllDirectories)); TaskManagerService.Logger.Log(string.Format("Scanning path '{0}' for modules...", basePath)); List<string> possibleFiles = new List<string>(); foreach (string file in filesToScan) { if (Path.GetExtension(file) != ModuleFileDefaultExtension && Path.GetExtension(file) != ZipFileDefaultExtension) { continue; } if (Path.GetDirectoryName(file) + @"\" == basePath && Path.GetExtension(file) != ZipFileDefaultExtension) { continue; } bool alreadyLoaded = false; lock (_moduleListLock) { foreach (ModuleData module in _moduleList) { if (module.DllFile == file || module.ZipFile == file) { alreadyLoaded = true; break; } } } if (alreadyLoaded) { continue; } string xmlFile = Path.ChangeExtension(file, ConfigFileDefaultExtension); if (File.Exists(xmlFile)) { possibleFiles.Add(file); } string filePath = Path.GetDirectoryName(file); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); string overridePath = Path.Combine(filePath, fileNameWithoutExtension); if (Path.GetExtension(file).ToLower() == ModuleFileDefaultExtension) { xmlFile = Path.Combine(overridePath, Path.ChangeExtension(Path.GetFileName(file), ConfigFileDefaultExtension)); if (File.Exists(xmlFile)) { possibleFiles.Add(file); } } else if (Path.GetExtension(file).ToLower() == ZipFileDefaultExtension) { possibleFiles.Add(file); } } foreach (string moduleFile in possibleFiles) { switch (Path.GetExtension(moduleFile).ToLower()) { case ModuleFileDefaultExtension: { string xmlFile = Path.ChangeExtension(moduleFile, ConfigFileDefaultExtension); if (File.Exists(xmlFile)) { if (xmlFile.IsValidConfigurationFile()) { LoadAndConfigure(moduleFile, xmlFile, startImmediately); } else { TaskManagerService.Logger.Log(string.Format("Unable to load module '{0}': exception caught while loading configuration file.", moduleFile)); } } break; } case ZipFileDefaultExtension: { try { LoadZipAndConfigure(moduleFile, startImmediately); } catch (Exception e) { TaskManagerService.Logger.Log(string.Format("Unable to load zipped module '{0}'.", moduleFile), e); } break; } } } TaskManagerService.Logger.Log(string.Format("{0} modules found.", _moduleList.Count)); } /// <summary> /// Loads a module from a zip file. /// </summary> /// <param name="zipFile">The path to the zip file.</param> /// <param name="startImmediately">True if execution should be started immediately after configuring the module, false if module should be configured but not started.</param> private static void LoadZipAndConfigure(string zipFile, bool startImmediately) { string tempPath = null; int i = 0; while (Directory.Exists(tempPath = Path.Combine(Path.Combine(Path.GetTempPath(), "TaskManager"), Path.GetRandomFileName()))) { i++; if (i == 10) throw new Exception("Failed to create a new temporary folder."); } if (!tempPath.EndsWith(Path.DirectorySeparatorChar.ToString())) { tempPath += Path.DirectorySeparatorChar; } string overridePath = Path.Combine(Path.GetDirectoryName(zipFile), Path.GetFileNameWithoutExtension(zipFile)) + Path.DirectorySeparatorChar; string loaderDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll"); string tempLoaderDll = Path.Combine(tempPath, "TaskManager.Loader.dll"); string commonDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Common.dll"); string tempCommonDll = Path.Combine(tempPath, "TaskManager.Common.dll"); List<string> dependencies = new List<string>(); DirectoryInfo directoryInfo = Directory.CreateDirectory(tempPath); try { using (Stream fileStream = File.Open(zipFile, FileMode.Open, FileAccess.Read)) { using (ZipArchive zip = new ZipArchive(fileStream, ZipArchiveMode.Read)) { var directory = zip.Entries; foreach (var compressedFile in directory) { string destinationFile = Path.Combine(tempPath, compressedFile.FullName); string overrideFile = Path.Combine(overridePath, compressedFile.FullName); dependencies.Add(overrideFile); compressedFile.ExtractToFile(destinationFile, true); } } } if (Directory.Exists(overridePath)) { foreach (string overrideFile in Directory.GetFiles(overridePath, "*.*", SearchOption.AllDirectories)) { if (!dependencies.Contains(overrideFile)) { dependencies.Add(overrideFile); } dependencies.Add(Path.Combine(overridePath, overrideFile.Replace(tempPath, string.Empty))); string relativeName = overrideFile.Replace(overridePath, string.Empty); string destination = Path.Combine(tempPath, relativeName); string destinationPath = Path.GetDirectoryName(destination); if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); } File.Copy(overrideFile, destination, true); } } List<string> possibleFiles = new List<string>(); foreach (string moduleFile in Directory.GetFiles(tempPath, "*" + ModuleFileDefaultExtension, SearchOption.AllDirectories)) { string xmlFile = Path.ChangeExtension(moduleFile, ConfigFileDefaultExtension); if (File.Exists(xmlFile)) { possibleFiles.Add(moduleFile); } } File.Copy(loaderDll, tempLoaderDll, true); File.Copy(commonDll, tempCommonDll, true); foreach (string dllFile in possibleFiles) { string xmlFile = Path.ChangeExtension(dllFile, ConfigFileDefaultExtension); if (File.Exists(xmlFile)) { if (!xmlFile.IsValidConfigurationFile()) { continue; } string modulePath = Path.GetDirectoryName(dllFile); string[] files = Directory.GetFiles(modulePath, "*.*", SearchOption.AllDirectories); AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ShadowCopyFiles = "true"; domainSetup.ApplicationBase = tempPath; domainSetup.ConfigurationFile = dllFile + ".config"; AppDomain domain = AppDomain.CreateDomain(dllFile, null, domainSetup); TaskWrapper[] tasks = new TaskWrapper[0]; try { TaskManagerService.Logger.Log(string.Format("Module found: '{0}', configuration file: '{1}', scanning assembly for tasks...", dllFile, xmlFile)); AssemblyName loaderAssemblyName = AssemblyName.GetAssemblyName(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll")); Loader loader = (Loader)domain.CreateInstanceAndUnwrap(loaderAssemblyName.ToString(), "TaskManager.Loader"); tasks = loader.LoadAndConfigure(dllFile, xmlFile, TaskManagerService.Logger, AppDomain.CurrentDomain.BaseDirectory); ModuleData newModule = new ModuleData(); newModule.BasePath = overridePath; newModule.Tasks = tasks; newModule.DllFile = dllFile; newModule.XmlFile = xmlFile; newModule.ZipFile = zipFile; newModule.ZipDirectory = tempPath; newModule.Files = new List<string>(files); newModule.Files.AddRange(dependencies); newModule.Files.Add(zipFile); newModule.Domain = domain; if (startImmediately) { foreach (TaskWrapper task in newModule.Tasks) { TaskSupervisor.ScheduleTask(task); } } _moduleList.Add(newModule); } catch (Exception ex) { foreach (TaskWrapper task in tasks) { try { TaskSupervisor.RemoveTask(task); } catch { } } AppDomain.Unload(domain); TaskManagerService.Logger.Log(string.Format("Unable to load module '{0}' from zipped file '{1}'.", dllFile, zipFile), ex); } } } foreach (ModuleData module in _moduleList) { if (module.ZipFile == zipFile) { return; } } throw new Exception(string.Format("Unable to find tasks in zipped file '{0}'.", zipFile)); } catch { try { Directory.Delete(tempPath, true); } catch (Exception ex) { TaskManagerService.Logger.Log(string.Format("Unable to remove temporary directory '{0}'.", tempPath), ex); } throw; } } /// <summary> /// Loads a module. /// </summary> /// <param name="dllFile">The path to the module DLL file.</param> /// <param name="xmlFile">The path to the module XML configuration file.</param> /// <param name="startImmediately">True if execution should be started immediately after configuring the module, false if module should be configured but not started.</param> private static void LoadAndConfigure(string dllFile, string xmlFile, bool startImmediately) { string modulePath = Path.GetDirectoryName(dllFile); if (!modulePath.EndsWith(Path.DirectorySeparatorChar.ToString())) { modulePath += Path.DirectorySeparatorChar; } string[] files = Directory.GetFiles(modulePath, "*.*", SearchOption.AllDirectories); AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ShadowCopyFiles = "true"; domainSetup.ApplicationBase = modulePath; domainSetup.ConfigurationFile = dllFile + ".config"; AppDomain domain = AppDomain.CreateDomain(dllFile, null, domainSetup); TaskManagerService.Logger.Log(string.Format("Module found: '{0}', configuration file: '{1}', scanning assembly for tasks...", dllFile, xmlFile)); if (modulePath != AppDomain.CurrentDomain.BaseDirectory) { string loaderDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll"); string tempLoaderDll = Path.Combine(modulePath, "TaskManager.Loader.dll"); string commonDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Common.dll"); string tempCommonDll = Path.Combine(modulePath, "TaskManager.Common.dll"); File.Copy(loaderDll, tempLoaderDll, true); File.Copy(commonDll, tempCommonDll, true); } AssemblyName loaderAssemblyName = AssemblyName.GetAssemblyName(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll")); Loader loader = (Loader)domain.CreateInstanceAndUnwrap(loaderAssemblyName.ToString(), "TaskManager.Loader"); TaskWrapper[] tasks = loader.LoadAndConfigure(dllFile, xmlFile, TaskManagerService.Logger, AppDomain.CurrentDomain.BaseDirectory); ModuleData newModule = new ModuleData(); newModule.BasePath = Path.GetDirectoryName(dllFile); newModule.Tasks = tasks; newModule.DllFile = dllFile; newModule.XmlFile = xmlFile; newModule.Files = new List<string>(files); newModule.Domain = domain; if (startImmediately) { foreach (TaskWrapper task in newModule.Tasks) { TaskSupervisor.ScheduleTask(task); } } _moduleList.Add(newModule); } /// <summary> /// Unloads a module. /// </summary> /// <param name="moduleData">The module.</param> private static void StopModule(ModuleData moduleData) { try { for (int i = moduleData.Tasks.Length - 1; i >= 0; i--) { TaskManagerService.Logger.Log(string.Format("Stopping task '{0}'...", moduleData.Tasks[i].TaskName)); TaskSupervisor.RemoveTask(moduleData.Tasks[i]); } TaskManagerService.Logger.Log(string.Format("Unloading AppDomain '{0}'...", moduleData.Domain.FriendlyName)); AppDomain.Unload(moduleData.Domain); TaskManagerService.Logger.Log("AppDomain successfully unloaded."); if (moduleData.ZipFile != null && moduleData.ZipDirectory != null) { Directory.Delete(moduleData.ZipDirectory, true); } _moduleList.Remove(moduleData); } catch (Exception e) { TaskManagerService.Logger.Log(string.Format("Exception caught while shutting down module '{0}'", moduleData.DllFile), e); throw; } } #endregion #region File system monitoring /// <summary> /// Starts monitoring the file system for changes to module files. /// </summary> private static void StartMonitoringFileSystem() { _fileSystemWatcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory); _fileSystemWatcher.Changed += new FileSystemEventHandler(FileSystem_Event); _fileSystemWatcher.Created += new FileSystemEventHandler(FileSystem_Event); _fileSystemWatcher.Renamed += new RenamedEventHandler(FileSystem_Renamed); _fileSystemWatcher.Deleted += new FileSystemEventHandler(FileSystem_Event); _fileSystemWatcher.IncludeSubdirectories = true; _fileSystemWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite; _fileSystemWatcher.EnableRaisingEvents = true; } /// <summary> /// Handler for the Renamed event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event arguments.</param> private static void FileSystem_Renamed(object sender, RenamedEventArgs e) { HandleFileSystemEvent(e, e.OldFullPath, e.FullPath); } /// <summary> /// Handler for the generic event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event arguments.</param> private static void FileSystem_Event(object sender, FileSystemEventArgs e) { HandleFileSystemEvent(e, e.FullPath, null); } /// <summary> /// Handles the file system event. /// </summary> /// <param name="e">The event arguments.</param> /// <param name="fileName">The path to the file.</param> /// <param name="relatedFileName">The path to the related file.</param> private static void HandleFileSystemEvent(FileSystemEventArgs e, string fileName, string relatedFileName) { try { string directory = Path.GetDirectoryName(fileName); string extension = Path.GetExtension(fileName); if (null != extension) { extension = extension.ToLower(); } string extension2 = Path.GetExtension(relatedFileName); if (null != extension2) { extension2 = extension2.ToLower(); } if (directory + @"\" == AppDomain.CurrentDomain.BaseDirectory && (extension != ZipFileDefaultExtension && extension2 != ZipFileDefaultExtension)) { return; } lock (_moduleListLock) { for (int i = _moduleList.Count - 1; i >= 0; i--) { bool restartModule = false; string file = null; if (_moduleList[i].DllFile == fileName || _moduleList[i].XmlFile == fileName || (_moduleList[i].ZipFile != null && _moduleList[i].ZipFile == fileName) || (null != fileName && _moduleList[i].Files.Contains(fileName))) { restartModule = true; file = fileName; } if (_moduleList[i].DllFile == relatedFileName || _moduleList[i].XmlFile == relatedFileName || (_moduleList[i].ZipFile != null && _moduleList[i].ZipFile == relatedFileName) || (null != relatedFileName && _moduleList[i].Files.Contains(relatedFileName))) { restartModule = true; file = relatedFileName; } if (restartModule) { string eventDescription = "modified"; if (e.ChangeType == WatcherChangeTypes.Created) { eventDescription = "created"; } else if (e.ChangeType == WatcherChangeTypes.Deleted) { eventDescription = "deleted"; } else if (e.ChangeType == WatcherChangeTypes.Renamed) { eventDescription = "renamed"; } TaskManagerService.Logger.Log(string.Format("File '{2}' of module '{0}' was {1}, restarting module...", _moduleList[i].Domain.FriendlyName, eventDescription, file)); StopModule(_moduleList[i]); } } } lock (_reloadLock) { _reload = DateTime.Now.AddSeconds(5); if (_reloadThread == null) { _reloadThread = new Thread(new ThreadStart(Reload)); _reloadThread.Name = "Reload thread"; _reloadThread.Start(); } } } catch (Exception ex) { TaskManagerService.Logger.Log("Unable to watch filesystem for events.", ex); } } /// <summary> /// Entry point for the reload thread. /// </summary> private static void Reload() { while (true) { lock (_reloadLock) { if (_reload <= DateTime.Now) { break; } } Thread.Sleep(500); } LoadAndConfigure(true); lock (_reloadLock) { _reloadThread = null; } } #endregion /// <summary> /// Represents internal module information. /// </summary> private class ModuleData { /// <summary> /// Gets or sets the path to the module files. /// </summary> public string BasePath { get; set; } /// <summary> /// Gets or sets the path to the module DLL file. /// </summary> public string DllFile { get; set; } /// <summary> /// Gets or sets the path to the module configuration file. /// </summary> public string XmlFile { get; set; } /// <summary> /// Gets or sets the path to the module zip file. /// </summary> public string ZipFile { get; set; } /// <summary> /// Gets or sets the path to the temporary directory where module files have been extracted to. /// </summary> public string ZipDirectory { get; set; } /// <summary> /// Gets or sets the list of files related to the module. /// </summary> public List<string> Files { get; set; } /// <summary> /// Gets or sets the list of task instances. /// </summary> public TaskWrapper[] Tasks { get; set; } /// <summary> /// Gets or sets the module AppDomain. /// </summary> public AppDomain Domain { get; set; } } } }
using System; using System.ComponentModel; using CoreAnimation; using CoreGraphics; using Foundation; using UIKit; namespace Messier16.Forms.iOS.Controls.Native.Checkbox { public class Checkbox : UIControl { #region Color layers private void ColorLayers() { containerLayer.StrokeColor = CheckboxBackgroundColor.CGColor; // Set colors based on 'on' property if (Checked) { containerLayer.FillColor = FillsOnChecked ? CheckboxBackgroundColor.CGColor : UIColor.Clear.CGColor; checkLayer.FillColor = CheckColor.CGColor; checkLayer.StrokeColor = CheckColor.CGColor; } else { containerLayer.FillColor = UIColor.Clear.CGColor; checkLayer.FillColor = UIColor.Clear.CGColor; checkLayer.StrokeColor = UIColor.Clear.CGColor; } } #endregion #region Interface builder public override void PrepareForInterfaceBuilder() { base.PrepareForInterfaceBuilder(); CustomInitialization(); } #endregion #region Public properties private float _checkLineWidth = 2f; [Export("CheckLineWidth")] [Browsable(true)] public float CheckLineWidth { get => _checkLineWidth; set { _checkLineWidth = value; LayoutLayers(); } } private UIColor _checkColor = UIColor.FromRGB(84, 142, 205); [Export("CheckColor")] [Browsable(true)] public UIColor CheckColor { get => _checkColor; set { _checkColor = value; ColorLayers(); } } private float _containerLineWidth = 2f; [Export("ContainerLineWidth")] [Browsable(true)] public float ContainerLineWidth { get => _containerLineWidth; set { _containerLineWidth = value; LayoutLayers(); } } private UIColor _checkboxBackgroundColor = UIColor.FromRGB(49, 95, 153); [Export("CheckboxBackgroundColor")] [Browsable(true)] public UIColor CheckboxBackgroundColor { get => _checkboxBackgroundColor; set { _checkboxBackgroundColor = value; SetNeedsDisplay(); } } private bool _fillsOnChecked = true; [Export("FillsOnChecked")] [Browsable(true)] public bool FillsOnChecked { get => _fillsOnChecked; set { _fillsOnChecked = value; ColorLayers(); } } private bool _checked; [Export("Checked")] [Browsable(true)] public bool Checked { get => _checked; set { _checked = value; ColorLayers(); } } #endregion #region Internal and private propertoies private readonly CAShapeLayer containerLayer = new CAShapeLayer(); private readonly CAShapeLayer checkLayer = new CAShapeLayer(); private CGRect frame { get { var width = (float) Bounds.Width; var height = (float) Bounds.Height; float x; float y; float sideLength; if (width > height) { sideLength = height; x = (width - sideLength) / 2; y = 0; } else { sideLength = width; x = 0; y = (height - sideLength) / 2; } var halfLineWidth = ContainerLineWidth / 2; return new CGRect(x + halfLineWidth, y + halfLineWidth, sideLength - ContainerLineWidth, sideLength - ContainerLineWidth); } } private UIBezierPath containerPath => UIBezierPath.FromRoundedRect( new CGRect(frame.GetMinX() + NMath.Floor(frame.Width * 0.05000f) + 0.5f, frame.GetMinY() + NMath.Floor(frame.Height * 0.05000f) + 0.5f, NMath.Floor(frame.Width * 0.95000f) - NMath.Floor(frame.Width * 0.05000f), NMath.Floor(frame.Height * 0.95000f) - NMath.Floor(frame.Height * 0.05000f)), frame.Height * 0.1f); private UIBezierPath checkPath { get { var checkPath = new UIBezierPath(); checkPath.MoveTo(new CGPoint(frame.GetMinX() + 0.76208f * frame.Width, frame.GetMinY() + 0.26000f * frame.Height)); checkPath.AddLineTo(new CGPoint(frame.GetMinX() + 0.38805f * frame.Width, frame.GetMinY() + 0.62670f * frame.Height)); checkPath.AddLineTo(new CGPoint(frame.GetMinX() + 0.23230f * frame.Width, frame.GetMinY() + 0.47400f * frame.Height)); checkPath.AddLineTo(new CGPoint(frame.GetMinX() + 0.18000f * frame.Width, frame.GetMinY() + 0.52527f * frame.Height)); checkPath.AddLineTo(new CGPoint(frame.GetMinX() + 0.36190f * frame.Width, frame.GetMinY() + 0.70360f * frame.Height)); checkPath.AddLineTo(new CGPoint(frame.GetMinX() + 0.38805f * frame.Width, frame.GetMinY() + 0.72813f * frame.Height)); checkPath.AddLineTo(new CGPoint(frame.GetMinX() + 0.41420f * frame.Width, frame.GetMinY() + 0.70360f * frame.Height)); checkPath.AddLineTo(new CGPoint(frame.GetMinX() + 0.81437f * frame.Width, frame.GetMinY() + 0.31127f * frame.Height)); checkPath.AddLineTo(new CGPoint(frame.GetMinX() + 0.76208f * frame.Width, frame.GetMinY() + 0.26000f * frame.Height)); checkPath.ClosePath(); return checkPath; } } private const float validBoundsOffset = 80f; #endregion #region Initialization public Checkbox(NSCoder coder) : base(coder) { } public override void AwakeFromNib() { CustomInitialization(); } public Checkbox(CGRect frame) : base(frame) { CustomInitialization(); } public Checkbox(CGRect frame, bool on) : this(frame) { Checked = on; } private void CustomInitialization() { checkLayer.FillColor = UIColor.Clear.CGColor; ColorLayers(); LayoutLayers(); Layer.AddSublayer(containerLayer); Layer.AddSublayer(checkLayer); } #endregion #region Layout layers public override void LayoutSubviews() { base.LayoutSubviews(); LayoutLayers(); } private void LayoutLayers() { // Set frames, line widths and paths for layers containerLayer.Frame = Bounds; containerLayer.LineWidth = ContainerLineWidth; containerLayer.Path = containerPath.CGPath; checkLayer.Frame = Bounds; checkLayer.LineWidth = CheckLineWidth; checkLayer.Path = checkPath.CGPath; } #endregion #region Touch tracking public override bool BeginTracking(UITouch uitouch, UIEvent uievent) { base.BeginTracking(uitouch, uievent); return true; } public override bool ContinueTracking(UITouch uitouch, UIEvent uievent) { base.ContinueTracking(uitouch, uievent); return true; } public override void EndTracking(UITouch uitouch, UIEvent uievent) { base.EndTracking(uitouch, uievent); var touchLocationInView = uitouch?.LocationInView(this); if (touchLocationInView == null) return; //let offset = type(of: self).validBoundsOffset //let validBounds = CGRect(x: bounds.origin.x - offset, y: bounds.origin.y - offset, width: bounds.width + (2 * offset), height: bounds.height + (2 * offset)) var validBounds = Bounds; if (validBounds.Contains(touchLocationInView.Value)) { Checked = !Checked; SendActionForControlEvents(UIControlEvent.ValueChanged); } } #endregion } }
// BTProgressHUD - port of SVProgressHUD // // https://github.com/nicwise/BTProgressHUD // // Ported by Nic Wise - // Copyright 2013 Nic Wise. MIT license. // // SVProgressHUD.m // // Created by Sam Vermette on 27.03.11. // Copyright 2011 Sam Vermette. All rights reserved. // // https://github.com/samvermette/SVProgressHUD // // Version 1.6.1 using System; using System.Collections.Generic; #if __UNIFIED__ using UIKit; using Foundation; using CoreAnimation; using CoreGraphics; using ObjCRuntime; #else using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreAnimation; using MonoTouch.CoreGraphics; using MonoTouch.ObjCRuntime; using nfloat = System.Single; using System.Drawing; using CGRect = global::System.Drawing.RectangleF; using CGPoint = global::System.Drawing.PointF; using CGSize = global::System.Drawing.SizeF; #endif namespace BigTed { public class ProgressHUD : UIView { static Class clsUIPeripheralHostView = null; static Class clsUIKeyboard = null; static Class clsUIInputSetContainerView = null; static Class clsUIInputSetHostView = null; static ProgressHUD () { //initialize static fields used for input view detection var ptrUIPeripheralHostView = Class.GetHandle("UIPeripheralHostView"); if (ptrUIPeripheralHostView != IntPtr.Zero) clsUIPeripheralHostView = new Class (ptrUIPeripheralHostView); var ptrUIKeyboard = Class.GetHandle("UIKeyboard"); if (ptrUIKeyboard != IntPtr.Zero) clsUIKeyboard = new Class (ptrUIKeyboard); var ptrUIInputSetContainerView = Class.GetHandle("UIInputSetContainerView"); if (ptrUIInputSetContainerView != IntPtr.Zero) clsUIInputSetContainerView = new Class (ptrUIInputSetContainerView); var ptrUIInputSetHostView = Class.GetHandle("UIInputSetHostView"); if (ptrUIInputSetHostView != IntPtr.Zero) clsUIInputSetHostView = new Class (ptrUIInputSetHostView); } public ProgressHUD () : this (UIScreen.MainScreen.Bounds) { } public ProgressHUD (CGRect frame) : base (frame) { UserInteractionEnabled = false; BackgroundColor = UIColor.Clear; Alpha = 0; AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; SetOSSpecificLookAndFeel (); } public void SetOSSpecificLookAndFeel () { if (IsiOS7ForLookAndFeel) { HudBackgroundColour = UIColor.White.ColorWithAlpha (0.8f); HudForegroundColor = UIColor.FromWhiteAlpha (0.0f, 0.8f); HudStatusShadowColor = UIColor.FromWhiteAlpha (200f / 255f, 0.8f); _ringThickness = 1f; } else { HudBackgroundColour = UIColor.FromWhiteAlpha (0.0f, 0.8f); HudForegroundColor = UIColor.White; HudStatusShadowColor = UIColor.Black; _ringThickness = 6f; } } public enum MaskType { None = 1, Clear, Black, Gradient } public enum ToastPosition { Bottom = 1, Center, Top } public UIColor HudBackgroundColour = UIColor.FromWhiteAlpha (0.0f, 0.8f); public UIColor HudForegroundColor = UIColor.White; public UIColor HudStatusShadowColor = UIColor.Black; public UIColor HudToastBackgroundColor = UIColor.Clear; public UIFont HudFont = UIFont.BoldSystemFontOfSize (16f); public UITextAlignment HudTextAlignment = UITextAlignment.Center; public Ring Ring = new Ring (); static NSObject obj = new NSObject (); public void Show (string status = null, float progress = -1, MaskType maskType = MaskType.None, double timeoutMs = 1000) { obj.InvokeOnMainThread (() => ShowProgressWorker (progress, status, maskType, timeoutMs: timeoutMs)); } public void Show (string cancelCaption, Action cancelCallback, string status = null, float progress = -1, MaskType maskType = MaskType.None, double timeoutMs = 1000) { // Making cancelCaption optional hides the method via the overload if (string.IsNullOrEmpty (cancelCaption)) { cancelCaption = "Cancel"; } obj.InvokeOnMainThread (() => ShowProgressWorker (progress, status, maskType, cancelCaption: cancelCaption, cancelCallback: cancelCallback, timeoutMs: timeoutMs)); } public void ShowContinuousProgress (string status = null, MaskType maskType = MaskType.None, double timeoutMs = 1000, UIImage img = null) { obj.InvokeOnMainThread (() => ShowProgressWorker (0, status, maskType, false, ToastPosition.Center, null, null, timeoutMs, true, img)); } public void ShowContinuousProgressTest (string status = null, MaskType maskType = MaskType.None, double timeoutMs = 1000) { obj.InvokeOnMainThread (() => ShowProgressWorker (0, status, maskType, false, ToastPosition.Center, null, null, timeoutMs, true)); } public void ShowToast (string status, MaskType maskType = MaskType.None, ToastPosition toastPosition = ToastPosition.Center, double timeoutMs = 1000) { obj.InvokeOnMainThread (() => ShowProgressWorker (status: status, textOnly: true, toastPosition: toastPosition, timeoutMs: timeoutMs, maskType: maskType)); } public void SetStatus (string status) { obj.InvokeOnMainThread (() => SetStatusWorker (status)); } public void ShowSuccessWithStatus (string status, double timeoutMs = 1000) { ShowImage (SuccessImage, status, timeoutMs); } public void ShowErrorWithStatus (string status, double timeoutMs = 1000) { ShowImage (ErrorImage, status, timeoutMs); } public void ShowImage (UIImage image, string status, double timeoutMs = 1000) { obj.InvokeOnMainThread (() => ShowImageWorker (image, status, TimeSpan.FromMilliseconds (timeoutMs))); } public void Dismiss () { obj.InvokeOnMainThread (DismissWorker); } public UIImage ErrorImage { get { return (IsiOS7ForLookAndFeel ? UIImage.FromBundle ("error_7.png") : UIImage.FromBundle ("error.png")); } } public UIImage SuccessImage { get { return (IsiOS7ForLookAndFeel ? UIImage.FromBundle ("success_7.png") : UIImage.FromBundle ("success.png")); } } public bool IsVisible { get { return Alpha == 1; } } static ProgressHUD sharedHUD = null; public static ProgressHUD Shared { get { if (sharedHUD == null) { UIApplication.EnsureUIThread (); sharedHUD = new ProgressHUD (UIScreen.MainScreen.Bounds); } return sharedHUD; } } float _ringRadius = 14f; float _ringThickness = 6f; MaskType _maskType; NSTimer _fadeoutTimer; UIView _overlayView; UIView _hudView; UILabel _stringLabel; UIImageView _imageView; UIActivityIndicatorView _spinnerView; UIButton _cancelHud; NSTimer _progressTimer; float _progress; CAShapeLayer _backgroundRingLayer; CAShapeLayer _ringLayer; List<NSObject> _eventListeners; bool _displayContinuousImage; public float RingRadius { get { return _ringRadius; } set { _ringRadius = value; } } public float RingThickness { get { return _ringThickness; } set { _ringThickness = value; } } public override void Draw (CGRect rect) { using (var context = UIGraphics.GetCurrentContext ()) { switch (_maskType) { case MaskType.Black: UIColor.FromWhiteAlpha (0f, 0.5f).SetColor (); context.FillRect (Bounds); break; case MaskType.Gradient: nfloat[] colors = new nfloat[] { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.75f }; nfloat[] locations = new nfloat[] { 0.0f, 1.0f }; using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) { using (var gradient = new CGGradient (colorSpace, colors, locations)) { var center = new CGPoint (Bounds.Size.Width / 2, Bounds.Size.Height / 2); float radius = Math.Min ((float)Bounds.Size.Width, (float)Bounds.Size.Height); context.DrawRadialGradient (gradient, center, 0, center, radius, CGGradientDrawingOptions.DrawsAfterEndLocation); } } break; } } } void ShowProgressWorker (float progress = -1, string status = null, MaskType maskType = MaskType.None, bool textOnly = false, ToastPosition toastPosition = ToastPosition.Center, string cancelCaption = null, Action cancelCallback = null, double timeoutMs = 1000, bool showContinuousProgress = false, UIImage displayContinuousImage = null) { Ring.ResetStyle(IsiOS7ForLookAndFeel, (IsiOS7ForLookAndFeel ? TintColor : UIColor.White)); if (OverlayView.Superview == null) { var windows = UIApplication.SharedApplication.Windows; Array.Reverse (windows); foreach (UIWindow window in windows) { if (window.WindowLevel == UIWindowLevel.Normal && !window.Hidden) { window.AddSubview (OverlayView); break; } } } if (Superview == null) OverlayView.AddSubview (this); _fadeoutTimer = null; ImageView.Hidden = true; _maskType = maskType; _progress = progress; StringLabel.Text = status; if (!string.IsNullOrEmpty (cancelCaption)) { CancelHudButton.SetTitle (cancelCaption, UIControlState.Normal); CancelHudButton.TouchUpInside += delegate { Dismiss (); if (cancelCallback != null) { obj.InvokeOnMainThread (() => cancelCallback.DynamicInvoke (null)); //cancelCallback.DynamicInvoke(null); } }; } UpdatePosition (textOnly); if (showContinuousProgress) { if (displayContinuousImage != null) { _displayContinuousImage = true; ImageView.Image = displayContinuousImage; ImageView.Hidden = false; } RingLayer.StrokeEnd = 0.0f; StartProgressTimer (TimeSpan.FromMilliseconds (Ring.ProgressUpdateInterval)); } else { if (progress >= 0) { ImageView.Image = null; ImageView.Hidden = false; SpinnerView.StopAnimating (); RingLayer.StrokeEnd = progress; } else if (textOnly) { CancelRingLayerAnimation (); SpinnerView.StopAnimating (); } else { CancelRingLayerAnimation (); SpinnerView.StartAnimating (); } } bool cancelButtonVisible = _cancelHud != null && _cancelHud.IsDescendantOfView (_hudView); // intercept user interaction with the underlying view if (maskType != MaskType.None || cancelButtonVisible) { OverlayView.UserInteractionEnabled = true; //AccessibilityLabel = status; //IsAccessibilityElement = true; } else { OverlayView.UserInteractionEnabled = false; //hudView.IsAccessibilityElement = true; } OverlayView.Hidden = false; this.toastPosition = toastPosition; PositionHUD (null); if (Alpha != 1) { RegisterNotifications (); HudView.Transform.Scale (1.3f, 1.3f); if (isClear) { Alpha = 1f; HudView.Alpha = 0f; } UIView.Animate (0.15f, 0, UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.BeginFromCurrentState, delegate { HudView.Transform.Scale ((float)1 / 1.3f, (float)1f / 1.3f); if (isClear) { HudView.Alpha = 1f; } else { Alpha = 1f; } }, delegate { //UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, string); if (textOnly) StartDismissTimer (TimeSpan.FromMilliseconds (timeoutMs)); }); SetNeedsDisplay (); } } void ShowImageWorker (UIImage image, string status, TimeSpan duration) { _progress = -1; CancelRingLayerAnimation (); //this should happen when Dismiss is called, but it happens AFTER the animation ends // so sometimes, the cancel button is left on :( if (_cancelHud != null) { _cancelHud.RemoveFromSuperview (); _cancelHud = null; } if (!IsVisible) Show (); ImageView.Image = image; ImageView.Hidden = false; StringLabel.Text = status; UpdatePosition (); SpinnerView.StopAnimating (); StartDismissTimer (duration); } void StartDismissTimer (TimeSpan duration) { #if __UNIFIED__ _fadeoutTimer = NSTimer.CreateTimer (duration, timer => DismissWorker ()); #else _fadeoutTimer = NSTimer.CreateTimer(duration, DismissWorker); #endif NSRunLoop.Main.AddTimer (_fadeoutTimer, NSRunLoopMode.Common); } void StartProgressTimer (TimeSpan duration) { if (_progressTimer == null) { #if __UNIFIED__ _progressTimer = NSTimer.CreateRepeatingTimer (duration, timer => UpdateProgress ()); #else _progressTimer = NSTimer.CreateRepeatingTimer(duration, UpdateProgress); #endif NSRunLoop.Current.AddTimer (_progressTimer, NSRunLoopMode.Common); } } void StopProgressTimer () { if (_progressTimer != null) { _progressTimer.Invalidate (); _progressTimer = null; } } void UpdateProgress () { obj.InvokeOnMainThread (delegate { if (!_displayContinuousImage) { ImageView.Image = null; ImageView.Hidden = false; } SpinnerView.StopAnimating (); if (RingLayer.StrokeEnd > 1) { RingLayer.StrokeEnd = 0.0f; } else { RingLayer.StrokeEnd += 0.1f; } }); } void CancelRingLayerAnimation () { CATransaction.Begin (); CATransaction.DisableActions = true; HudView.Layer.RemoveAllAnimations (); RingLayer.StrokeEnd = 0; if (RingLayer.SuperLayer != null) { RingLayer.RemoveFromSuperLayer (); } RingLayer = null; if (BackgroundRingLayer.SuperLayer != null) { BackgroundRingLayer.RemoveFromSuperLayer (); } BackgroundRingLayer = null; CATransaction.Commit (); } CAShapeLayer RingLayer { get { if (_ringLayer == null) { var center = new CGPoint (HudView.Frame.Width / 2, HudView.Frame.Height / 2); _ringLayer = CreateRingLayer (center, _ringRadius, _ringThickness, Ring.Color); HudView.Layer.AddSublayer (_ringLayer); } return _ringLayer; } set { _ringLayer = value; } } CAShapeLayer BackgroundRingLayer { get { if (_backgroundRingLayer == null) { var center = new CGPoint (HudView.Frame.Width / 2, HudView.Frame.Height / 2); _backgroundRingLayer = CreateRingLayer (center, _ringRadius, _ringThickness, Ring.BackgroundColor); _backgroundRingLayer.StrokeEnd = 1; HudView.Layer.AddSublayer (_backgroundRingLayer); } return _backgroundRingLayer; } set { _backgroundRingLayer = value; } } CGPoint PointOnCircle (CGPoint center, float radius, float angleInDegrees) { float x = radius * (float)Math.Cos (angleInDegrees * Math.PI / 180) + radius; float y = radius * (float)Math.Sin (angleInDegrees * Math.PI / 180) + radius; return new CGPoint (x, y); } UIBezierPath CreateCirclePath (CGPoint center, float radius, int sampleCount) { var smoothedPath = new UIBezierPath (); CGPoint startPoint = PointOnCircle (center, radius, -90); smoothedPath.MoveTo (startPoint); float delta = 360 / sampleCount; float angleInDegrees = -90; for (int i = 1; i < sampleCount; i++) { angleInDegrees += delta; var point = PointOnCircle (center, radius, angleInDegrees); smoothedPath.AddLineTo (point); } smoothedPath.AddLineTo (startPoint); return smoothedPath; } CAShapeLayer CreateRingLayer (CGPoint center, float radius, float lineWidth, UIColor color) { var smoothedPath = CreateCirclePath (center, radius, 72); var slice = new CAShapeLayer (); slice.Frame = new CGRect (center.X - radius, center.Y - radius, radius * 2, radius * 2); slice.FillColor = UIColor.Clear.CGColor; slice.StrokeColor = color.CGColor; slice.LineWidth = lineWidth; slice.LineCap = CAShapeLayer.JoinBevel; slice.LineJoin = CAShapeLayer.JoinBevel; slice.Path = smoothedPath.CGPath; return slice; } bool isClear { get { return (_maskType == ProgressHUD.MaskType.Clear || _maskType == ProgressHUD.MaskType.None); } } UIView OverlayView { get { if (_overlayView == null) { _overlayView = new UIView (UIScreen.MainScreen.Bounds); _overlayView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; _overlayView.BackgroundColor = UIColor.Clear; _overlayView.UserInteractionEnabled = false; } return _overlayView; } set { _overlayView = value; } } UIView HudView { get { if (_hudView == null) { if (IsiOS7ForLookAndFeel) { _hudView = new UIToolbar (); (_hudView as UIToolbar).Translucent = true; (_hudView as UIToolbar).BarTintColor = HudBackgroundColour; } else { _hudView = new UIView (); } _hudView.Layer.CornerRadius = 10; _hudView.Layer.MasksToBounds = true; _hudView.BackgroundColor = HudBackgroundColour; _hudView.AutoresizingMask = (UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleLeftMargin); AddSubview (_hudView); } return _hudView; } set { _hudView = value; } } UILabel StringLabel { get { if (_stringLabel == null) { _stringLabel = new UILabel (); _stringLabel.BackgroundColor = HudToastBackgroundColor; _stringLabel.AdjustsFontSizeToFitWidth = true; _stringLabel.TextAlignment = HudTextAlignment; _stringLabel.BaselineAdjustment = UIBaselineAdjustment.AlignCenters; _stringLabel.TextColor = HudForegroundColor; _stringLabel.Font = HudFont; if (!IsiOS7ForLookAndFeel) { _stringLabel.ShadowColor = HudStatusShadowColor; _stringLabel.ShadowOffset = new CGSize (0, -1); } _stringLabel.Lines = 0; } if (_stringLabel.Superview == null) { HudView.AddSubview (_stringLabel); } return _stringLabel; } set { _stringLabel = value; } } UIButton CancelHudButton { get { if (_cancelHud == null) { _cancelHud = new UIButton (); _cancelHud.BackgroundColor = UIColor.Clear; _cancelHud.SetTitleColor (HudForegroundColor, UIControlState.Normal); _cancelHud.UserInteractionEnabled = true; _cancelHud.Font = HudFont; this.UserInteractionEnabled = true; } if (_cancelHud.Superview == null) { HudView.AddSubview (_cancelHud); // Position the Cancel button at the bottom /* var hudFrame = HudView.Frame; var cancelFrame = _cancelHud.Frame; var x = ((hudFrame.Width - cancelFrame.Width)/2) + 0; var y = (hudFrame.Height - cancelFrame.Height - 10); _cancelHud.Frame = new RectangleF(x, y, cancelFrame.Width, cancelFrame.Height); HudView.SizeToFit(); */ } return _cancelHud; } set { _cancelHud = value; } } UIImageView ImageView { get { if (_imageView == null) { _imageView = new UIImageView (new CGRect (0, 0, 28, 28)); } if (_imageView.Superview == null) { HudView.AddSubview (_imageView); } return _imageView; } set { _imageView = value; } } UIActivityIndicatorView SpinnerView { get { if (_spinnerView == null) { _spinnerView = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.WhiteLarge); _spinnerView.HidesWhenStopped = true; _spinnerView.Bounds = new CGRect (0, 0, 37, 37); _spinnerView.Color = HudForegroundColor; } if (_spinnerView.Superview == null) HudView.AddSubview (_spinnerView); return _spinnerView; } set { _spinnerView = value; } } float VisibleKeyboardHeight { get { foreach (var testWindow in UIApplication.SharedApplication.Windows) { if (testWindow.Class.Handle != Class.GetHandle("UIWindow")) { foreach (var possibleKeyboard in testWindow.Subviews) { if ((clsUIPeripheralHostView != null && possibleKeyboard.IsKindOfClass(clsUIPeripheralHostView)) || (clsUIKeyboard != null && possibleKeyboard.IsKindOfClass(clsUIKeyboard))) { return (float)possibleKeyboard.Bounds.Size.Height; } else if (clsUIInputSetContainerView != null && possibleKeyboard.IsKindOfClass(clsUIInputSetContainerView)) { foreach (var possibleKeyboardSubview in possibleKeyboard.Subviews) { if (clsUIInputSetHostView != null && possibleKeyboardSubview.IsKindOfClass(clsUIInputSetHostView)) return (float)possibleKeyboardSubview.Bounds.Size.Height; } } } } } return 0; } } void DismissWorker () { SetFadeoutTimer (null); SetProgressTimer (null); UIView.Animate (0.3, 0, UIViewAnimationOptions.CurveEaseIn | UIViewAnimationOptions.AllowUserInteraction, delegate { HudView.Transform.Scale (0.8f, 0.8f); if (isClear) { HudView.Alpha = 0f; } else { Alpha = 0f; } }, delegate { if (Alpha == 0f || HudView.Alpha == 0f) { InvokeOnMainThread (delegate { Alpha = 0f; HudView.Alpha = 0f; //Removing observers UnRegisterNotifications (); NSNotificationCenter.DefaultCenter.RemoveObserver (this); Ring.ResetStyle (IsiOS7ForLookAndFeel, (IsiOS7ForLookAndFeel ? TintColor : UIColor.White)); CancelRingLayerAnimation (); StringLabel.RemoveFromSuperview (); SpinnerView.RemoveFromSuperview (); ImageView.RemoveFromSuperview (); if (_cancelHud != null) _cancelHud.RemoveFromSuperview (); StringLabel = null; SpinnerView = null; ImageView = null; _cancelHud = null; HudView.RemoveFromSuperview (); HudView = null; OverlayView.RemoveFromSuperview (); OverlayView = null; this.RemoveFromSuperview (); if (IsiOS7ForLookAndFeel) { var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController; if (rootController != null) rootController.SetNeedsStatusBarAppearanceUpdate (); } }); } }); } void SetStatusWorker (string status) { StringLabel.Text = status; UpdatePosition (); } void RegisterNotifications () { if (_eventListeners == null) { _eventListeners = new List<NSObject> (); } _eventListeners.Add (NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.DidChangeStatusBarOrientationNotification, PositionHUD)); _eventListeners.Add (NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, PositionHUD)); _eventListeners.Add (NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidHideNotification, PositionHUD)); _eventListeners.Add (NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, PositionHUD)); _eventListeners.Add (NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidShowNotification, PositionHUD)); } void UnRegisterNotifications () { if (_eventListeners != null) { NSNotificationCenter.DefaultCenter.RemoveObservers (_eventListeners); _eventListeners.Clear (); _eventListeners = null; } } void MoveToPoint (CGPoint newCenter, float angle) { HudView.Transform = CGAffineTransform.MakeRotation (angle); HudView.Center = newCenter; } ToastPosition toastPosition = ToastPosition.Center; void PositionHUD (NSNotification notification) { nfloat keyboardHeight = 0; double animationDuration = 0; Frame = UIScreen.MainScreen.Bounds; UIInterfaceOrientation orientation = UIApplication.SharedApplication.StatusBarOrientation; bool ignoreOrientation = UIDevice.CurrentDevice.CheckSystemVersion (8, 0); if (notification != null) { var keyboardFrame = UIKeyboard.FrameEndFromNotification (notification); animationDuration = UIKeyboard.AnimationDurationFromNotification (notification); if (notification.Name == UIKeyboard.WillShowNotification || notification.Name == UIKeyboard.DidShowNotification) { if (ignoreOrientation || IsPortrait (orientation)) keyboardHeight = keyboardFrame.Size.Height; else keyboardHeight = keyboardFrame.Size.Width; } else keyboardHeight = 0; } else { keyboardHeight = VisibleKeyboardHeight; } CGRect orientationFrame = UIApplication.SharedApplication.KeyWindow.Bounds; CGRect statusBarFrame = UIApplication.SharedApplication.StatusBarFrame; if (!ignoreOrientation && IsLandscape (orientation)) { orientationFrame.Size = new CGSize (orientationFrame.Size.Height, orientationFrame.Size.Width); statusBarFrame.Size = new CGSize (statusBarFrame.Size.Height, statusBarFrame.Size.Width); } var activeHeight = orientationFrame.Size.Height; if (keyboardHeight > 0) activeHeight += statusBarFrame.Size.Height * 2; activeHeight -= keyboardHeight; nfloat posY = (float)Math.Floor (activeHeight * 0.45); nfloat posX = orientationFrame.Size.Width / 2; nfloat textHeight = _stringLabel.Frame.Height / 2 + 40; switch (toastPosition) { case ToastPosition.Bottom: posY = activeHeight - textHeight; break; case ToastPosition.Center: // Already set above break; case ToastPosition.Top: posY = textHeight; break; default: break; } CGPoint newCenter; float rotateAngle; if (ignoreOrientation) { rotateAngle = 0.0f; newCenter = new CGPoint (posX, posY); } else { switch (orientation) { case UIInterfaceOrientation.PortraitUpsideDown: rotateAngle = (float)Math.PI; newCenter = new CGPoint (posX, orientationFrame.Size.Height - posY); break; case UIInterfaceOrientation.LandscapeLeft: rotateAngle = (float)(-Math.PI / 2.0f); newCenter = new CGPoint (posY, posX); break; case UIInterfaceOrientation.LandscapeRight: rotateAngle = (float)(Math.PI / 2.0f); newCenter = new CGPoint (orientationFrame.Size.Height - posY, posX); break; default: // as UIInterfaceOrientationPortrait rotateAngle = 0.0f; newCenter = new CGPoint (posX, posY); break; } } if (notification != null) { UIView.Animate (animationDuration, 0, UIViewAnimationOptions.AllowUserInteraction, delegate { MoveToPoint (newCenter, rotateAngle); }, null); } else { MoveToPoint (newCenter, rotateAngle); } } void SetFadeoutTimer (NSTimer newtimer) { if (_fadeoutTimer != null) { _fadeoutTimer.Invalidate (); _fadeoutTimer = null; } if (newtimer != null) _fadeoutTimer = newtimer; } void SetProgressTimer (NSTimer newtimer) { StopProgressTimer (); if (newtimer != null) _progressTimer = newtimer; } void UpdatePosition (bool textOnly = false) { nfloat hudWidth = 100f; nfloat hudHeight = 100f; nfloat stringWidth = 0f; nfloat stringHeight = 0f; nfloat stringHeightBuffer = 20f; nfloat stringAndImageHeightBuffer = 80f; CGRect labelRect = new CGRect (); string @string = StringLabel.Text; // False if it's text-only bool imageUsed = (ImageView.Image != null) || (ImageView.Hidden); if (textOnly) { imageUsed = false; } if (imageUsed) { hudHeight = stringAndImageHeightBuffer + stringHeight; } else { hudHeight = (textOnly ? stringHeightBuffer : stringHeightBuffer + 40); } if (!string.IsNullOrEmpty (@string)) { int lineCount = Math.Min (10, @string.Split ('\n').Length + 1); if (IsIOS7OrNewer) { var stringSize = new NSString (@string).GetBoundingRect (new CGSize (200, 30 * lineCount), NSStringDrawingOptions.UsesLineFragmentOrigin, new UIStringAttributes{ Font = StringLabel.Font }, null); stringWidth = stringSize.Width; stringHeight = stringSize.Height; } else { var stringSize = new NSString (@string).StringSize (StringLabel.Font, new CGSize (200, 30 * lineCount)); stringWidth = stringSize.Width; stringHeight = stringSize.Height; } hudHeight += stringHeight; if (stringWidth > hudWidth) hudWidth = (float)Math.Ceiling (stringWidth / 2) * 2; float labelRectY = imageUsed ? 66 : 9; if (hudHeight > 100) { labelRect = new CGRect (12, labelRectY, hudWidth, stringHeight); hudWidth += 24; } else { hudWidth += 24; labelRect = new CGRect (0, labelRectY, hudWidth, stringHeight); } } // Adjust for Cancel Button var cancelRect = new CGRect (); string @cancelCaption = _cancelHud == null ? null : CancelHudButton.Title (UIControlState.Normal); if (!string.IsNullOrEmpty (@cancelCaption)) { const int gap = 20; if (IsIOS7OrNewer) { var stringSize = new NSString (@cancelCaption).GetBoundingRect (new CGSize (200, 300), NSStringDrawingOptions.UsesLineFragmentOrigin, new UIStringAttributes{ Font = StringLabel.Font }, null); stringWidth = stringSize.Width; stringHeight = stringSize.Height; } else { var stringSize = new NSString (@cancelCaption).StringSize (StringLabel.Font, new CGSize (200, 300)); stringWidth = stringSize.Width; stringHeight = stringSize.Height; } if (stringWidth > hudWidth) hudWidth = (float)Math.Ceiling (stringWidth / 2) * 2; // Adjust for label nfloat cancelRectY = 0f; if (labelRect.Height > 0) { cancelRectY = labelRect.Y + labelRect.Height + (nfloat)gap; } else { if (string.IsNullOrEmpty (@string)) { cancelRectY = 76; } else { cancelRectY = (imageUsed ? 66 : 9); } } if (hudHeight > 100) { cancelRect = new CGRect (12, cancelRectY, hudWidth, stringHeight); labelRect = new CGRect (12, labelRect.Y, hudWidth, labelRect.Height); hudWidth += 24; } else { hudWidth += 24; cancelRect = new CGRect (0, cancelRectY, hudWidth, stringHeight); labelRect = new CGRect (0, labelRect.Y, hudWidth, labelRect.Height); } CancelHudButton.Frame = cancelRect; hudHeight += (cancelRect.Height + (string.IsNullOrEmpty (@string) ? 10 : gap)); } HudView.Bounds = new CGRect (0, 0, hudWidth, hudHeight); if (!string.IsNullOrEmpty (@string)) ImageView.Center = new CGPoint (HudView.Bounds.Width / 2, 36); else ImageView.Center = new CGPoint (HudView.Bounds.Width / 2, HudView.Bounds.Height / 2); StringLabel.Hidden = false; StringLabel.Frame = labelRect; if (!textOnly) { if (!string.IsNullOrEmpty (@string) || !string.IsNullOrEmpty(@cancelCaption)) { SpinnerView.Center = new CGPoint ((float)Math.Ceiling (HudView.Bounds.Width / 2.0f) + 0.5f, 40.5f); if (_progress != -1) { BackgroundRingLayer.Position = RingLayer.Position = new CGPoint (HudView.Bounds.Width / 2, 36f); } } else { SpinnerView.Center = new CGPoint ((float)Math.Ceiling (HudView.Bounds.Width / 2.0f) + 0.5f, (float)Math.Ceiling (HudView.Bounds.Height / 2.0f) + 0.5f); if (_progress != -1) { BackgroundRingLayer.Position = RingLayer.Position = new CGPoint (HudView.Bounds.Width / 2, HudView.Bounds.Height / 2.0f + 0.5f); } } } } public bool IsLandscape (UIInterfaceOrientation orientation) { return (orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight); } public bool IsPortrait (UIInterfaceOrientation orientation) { return (orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown); } public bool IsiOS7ForLookAndFeel { get { if (ForceiOS6LookAndFeel) return false; return UIDevice.CurrentDevice.CheckSystemVersion (7, 0); } } public bool IsIOS7OrNewer { get { return UIDevice.CurrentDevice.CheckSystemVersion (7, 0); } } bool forceiOS6LookAndFeel = false; public bool ForceiOS6LookAndFeel { get { return forceiOS6LookAndFeel; } set { forceiOS6LookAndFeel = value; SetOSSpecificLookAndFeel (); } } } }
/* Josip Medved <jmedved@jmedved.com> * www.medo64.com * MIT License */ //2007-12-31: New version. //2008-01-03: Added Resources. //2008-04-11: Cleaned code to match FxCop 1.36 beta 2 (SpecifyMarshalingForPInvokeStringArguments, NormalizeStringsToUppercase). //2008-11-14: Reworked code to use SafeHandle. // Fixed ToInt32 call on x64 bit windows. //2008-12-01: Deleted methods without owner parameter. //2009-07-04: Compatibility with Mono 2.4. //2012-11-24: Suppressing bogus CA5122 warning (http://connect.microsoft.com/VisualStudio/feedback/details/729254/bogus-ca5122-warning-about-p-invoke-declarations-should-not-be-safe-critical). using System; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; namespace Medo { /// <summary> /// Displays a message box that can contain text, buttons, and symbols that inform and instruct the user. /// </summary> public static class MessageBox { private readonly static object _syncRoot = new object(); #region With owner /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> public static DialogResult ShowDialog(IWin32Window owner, string text) { lock (_syncRoot) { return ShowDialog(owner, text, Resources.DefaultCaption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowDialog(IWin32Window owner, string text, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowDialog(owner, text, Resources.DefaultCaption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box.</param> public static DialogResult ShowDialog(IWin32Window owner, string text, MessageBoxButtons buttons, MessageBoxIcon icon) { lock (_syncRoot) { return ShowDialog(owner, text, Resources.DefaultCaption, buttons, icon, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowDialog(IWin32Window owner, string text, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowDialog(owner, text, Resources.DefaultCaption, buttons, icon, defaultButton); } } /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> public static DialogResult ShowDialog(IWin32Window owner, string text, string caption) { lock (_syncRoot) { return ShowDialog(owner, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowDialog(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowDialog(owner, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box.</param> public static DialogResult ShowDialog(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { lock (_syncRoot) { return ShowDialog(owner, text, caption, buttons, icon, MessageBoxDefaultButton.Button1); } } #endregion /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowDialog(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { if (!MessageBox.IsRunningOnMono) { lock (_syncRoot) { if (owner != null) { using (CbtHook ch = new CbtHook(owner)) { return (DialogResult)NativeMethods.MessageBox(owner.Handle, text, caption, (uint)buttons | (uint)icon | (uint)defaultButton); } } else { using (CbtHook ch = new CbtHook(null)) { return (DialogResult)NativeMethods.MessageBox(IntPtr.Zero, text, caption, (uint)buttons | (uint)icon | (uint)defaultButton); } } } //lock } else { //MONO return System.Windows.Forms.MessageBox.Show(owner, text, caption, buttons, icon, defaultButton, 0); } } #region ShowInformation /// <summary> /// Displays a information message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> public static DialogResult ShowInformation(IWin32Window owner, string text) { lock (_syncRoot) { return ShowInformation(owner, text, Resources.DefaultCaption, MessageBoxButtons.OK, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a information message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowInformation(IWin32Window owner, string text, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowInformation(owner, text, Resources.DefaultCaption, buttons, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a information message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowInformation(IWin32Window owner, string text, MessageBoxButtons buttons, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowInformation(owner, text, Resources.DefaultCaption, buttons, defaultButton); } } /// <summary> /// Displays a information message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> public static DialogResult ShowInformation(IWin32Window owner, string text, string caption) { lock (_syncRoot) { return ShowInformation(owner, text, caption, MessageBoxButtons.OK, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a information message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowInformation(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowInformation(owner, text, caption, buttons, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a information message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowInformation(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowDialog(owner, text, caption, buttons, MessageBoxIcon.Information, defaultButton); } } #endregion #region ShowWarning /// <summary> /// Displays a warning message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> public static DialogResult ShowWarning(IWin32Window owner, string text) { lock (_syncRoot) { return ShowWarning(owner, text, Resources.DefaultCaption, MessageBoxButtons.OK, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a warning message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowWarning(IWin32Window owner, string text, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowWarning(owner, text, Resources.DefaultCaption, buttons, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a warning message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowWarning(IWin32Window owner, string text, MessageBoxButtons buttons, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowWarning(owner, text, Resources.DefaultCaption, buttons, defaultButton); } } /// <summary> /// Displays a warning message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> public static DialogResult ShowWarning(IWin32Window owner, string text, string caption) { lock (_syncRoot) { return ShowWarning(owner, text, caption, MessageBoxButtons.OK, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a warning message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowWarning(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowWarning(owner, text, caption, buttons, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a warning message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowWarning(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowDialog(owner, text, caption, buttons, MessageBoxIcon.Warning, defaultButton); } } #endregion #region ShowError /// <summary> /// Displays a error message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> public static DialogResult ShowError(IWin32Window owner, string text) { lock (_syncRoot) { return ShowError(owner, text, Resources.DefaultCaption, MessageBoxButtons.OK, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a error message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowError(IWin32Window owner, string text, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowError(owner, text, Resources.DefaultCaption, buttons, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a error message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowError(IWin32Window owner, string text, MessageBoxButtons buttons, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowError(owner, text, Resources.DefaultCaption, buttons, defaultButton); } } /// <summary> /// Displays a error message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> public static DialogResult ShowError(IWin32Window owner, string text, string caption) { lock (_syncRoot) { return ShowError(owner, text, caption, MessageBoxButtons.OK, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a error message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowError(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowError(owner, text, caption, buttons, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a error message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowError(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowDialog(owner, text, caption, buttons, MessageBoxIcon.Error, defaultButton); } } #endregion #region ShowQuestion /// <summary> /// Displays a question message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> public static DialogResult ShowQuestion(IWin32Window owner, string text) { lock (_syncRoot) { return ShowQuestion(owner, text, Resources.DefaultCaption, MessageBoxButtons.OK, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a question message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowQuestion(IWin32Window owner, string text, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowQuestion(owner, text, Resources.DefaultCaption, buttons, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a question message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowQuestion(IWin32Window owner, string text, MessageBoxButtons buttons, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowQuestion(owner, text, Resources.DefaultCaption, buttons, defaultButton); } } /// <summary> /// Displays a question message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> public static DialogResult ShowQuestion(IWin32Window owner, string text, string caption) { lock (_syncRoot) { return ShowQuestion(owner, text, caption, MessageBoxButtons.OK, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a question message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> public static DialogResult ShowQuestion(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { lock (_syncRoot) { return ShowQuestion(owner, text, caption, buttons, MessageBoxDefaultButton.Button1); } } /// <summary> /// Displays a question message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">An implementation of IWin32Window that will own the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="defaultButton">One of the MessageBoxDefaultButton values that specifies the default button for the message box.</param> public static DialogResult ShowQuestion(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxDefaultButton defaultButton) { lock (_syncRoot) { return ShowDialog(owner, text, caption, buttons, MessageBoxIcon.Question, defaultButton); } } #endregion private static class Resources { internal static string DefaultCaption { get { var assembly = Assembly.GetEntryAssembly(); string caption; object[] productAttributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true); if ((productAttributes != null) && (productAttributes.Length >= 1)) { caption = ((AssemblyProductAttribute)productAttributes[productAttributes.Length - 1]).Product; } else { object[] titleAttributes = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), true); if ((titleAttributes != null) && (titleAttributes.Length >= 1)) { caption = ((AssemblyTitleAttribute)titleAttributes[titleAttributes.Length - 1]).Title; } else { caption = assembly.GetName().Name; } } return caption; } } internal static string OK { get { return GetInCurrentLanguage("OK", "U redu"); } } internal static string Cancel { get { return GetInCurrentLanguage("Cancel", "Odustani"); } } internal static string Abort { get { return GetInCurrentLanguage("&Abort", "P&rekini"); } } internal static string Retry { get { return GetInCurrentLanguage("&Retry", "&Ponovi"); } } internal static string Ignore { get { return GetInCurrentLanguage("&Ignore", "&Zanemari"); } } internal static string Yes { get { return GetInCurrentLanguage("&Yes", "&Da"); } } internal static string No { get { return GetInCurrentLanguage("&No", "&Ne"); } } internal static string ExceptionCbtHookCannotBeRemoved { get { return "CBT Hook cannot be removed."; } } internal static bool IsTranslatable { get { switch (Thread.CurrentThread.CurrentUICulture.Name.ToUpperInvariant()) { case "EN": case "EN-US": case "EN-GB": case "HR": case "HR-HR": case "HR-BA": return true; default: return false; } } } private static string GetInCurrentLanguage(string en_US, string hr_HR) { switch (Thread.CurrentThread.CurrentUICulture.Name.ToUpperInvariant()) { case "EN": case "EN-US": case "EN-GB": return en_US; case "HR": case "HR-HR": case "HR-BA": return hr_HR; default: return en_US; } } } #region Native private class CbtHook : IDisposable { private readonly IWin32Window _owner; private readonly NativeMethods.WindowsHookSafeHandle _hook; private readonly NativeMethods.CbtHookProcDelegate _cbtHookProc; public CbtHook(IWin32Window owner) { _owner = owner; _cbtHookProc = new NativeMethods.CbtHookProcDelegate(CbtHookProc); _hook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_CBT, _cbtHookProc, IntPtr.Zero, NativeMethods.GetCurrentThreadId()); Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "I: Created CBT hook (ID={0}). {{Medo.MessageBox}}", _hook.ToString())); } ~CbtHook() { Dispose(); } public IntPtr CbtHookProc(int nCode, IntPtr wParam, IntPtr lParam) { switch (nCode) { case NativeMethods.HCBT_ACTIVATE: Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "I: Dialog HCBT_ACTIVATE (hWnd={0}). {{Medo.MessageBox}}", wParam.ToString())); if (_owner != null) { NativeMethods.RECT rectMessage = new NativeMethods.RECT(); NativeMethods.RECT rectOwner = new NativeMethods.RECT(); if ((NativeMethods.GetWindowRect(wParam, ref rectMessage)) && (NativeMethods.GetWindowRect(_owner.Handle, ref rectOwner))) { int widthMessage = rectMessage.right - rectMessage.left; int heightMessage = rectMessage.bottom - rectMessage.top; int widthOwner = rectOwner.right - rectOwner.left; int heightOwner = rectOwner.bottom - rectOwner.top; int newLeft = rectOwner.left + (widthOwner - widthMessage) / 2; int newTop = rectOwner.top + (heightOwner - heightMessage) / 2; NativeMethods.SetWindowPos(wParam, IntPtr.Zero, newLeft, newTop, 0, 0, NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); } } if (Resources.IsTranslatable) { NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_OK, Resources.OK); NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_CANCEL, Resources.Cancel); NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_ABORT, Resources.Abort); NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_RETRY, Resources.Retry); NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_IGNORE, Resources.Ignore); NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_YES, Resources.Yes); NativeMethods.SetDlgItemText(wParam, NativeMethods.DLG_ID_NO, Resources.No); } try { return NativeMethods.CallNextHookEx(_hook, nCode, wParam, lParam); } finally { Dispose(); } } return NativeMethods.CallNextHookEx(_hook, nCode, wParam, lParam); } #region IDisposable Members public void Dispose() { if (!_hook.IsClosed) { _hook.Close(); if (_hook.IsClosed) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "I: CBT Hook destroyed (ID={0}). {{Medo.MessageBox}}", _hook.ToString())); } else { throw new InvalidOperationException(Resources.ExceptionCbtHookCannotBeRemoved); } } _hook.Dispose(); GC.SuppressFinalize(this); } #endregion } private static class NativeMethods { #pragma warning disable IDE0049 // Simplify Names public const Int32 WH_CBT = 0x5; public const Int32 DLG_ID_OK = 0x01; public const Int32 DLG_ID_CANCEL = 0x02; public const Int32 DLG_ID_ABORT = 0x03; public const Int32 DLG_ID_RETRY = 0x04; public const Int32 DLG_ID_IGNORE = 0x05; public const Int32 DLG_ID_YES = 0x06; public const Int32 DLG_ID_NO = 0x07; public const Int32 HCBT_ACTIVATE = 0x5; public const Int32 SWP_NOSIZE = 0x01; public const Int32 SWP_NOZORDER = 0x04; public const Int32 SWP_NOACTIVATE = 0x10; [StructLayout(LayoutKind.Sequential)] public struct RECT { public Int32 left; public Int32 top; public Int32 right; public Int32 bottom; } public class WindowsHookSafeHandle : SafeHandle { public WindowsHookSafeHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { get { return (IsClosed) || (base.handle == IntPtr.Zero); } } protected override bool ReleaseHandle() { return UnhookWindowsHookEx(base.handle); } public override string ToString() { return base.handle.ToString(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CallNextHookEx(WindowsHookSafeHandle idHook, Int32 nCode, IntPtr wParam, IntPtr lParam); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern Int32 GetCurrentThreadId(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern Boolean GetWindowRect(IntPtr hWnd, ref RECT lpRect); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Justification = "Managed equivalent does not support all needed features.")] [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Int32 MessageBox(IntPtr hWnd, String lpText, String lpCaption, UInt32 uType); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern Boolean SetDlgItemText(IntPtr hWnd, Int32 nIDDlgItem, String lpString); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern Boolean SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, Int32 X, Int32 Y, Int32 cx, Int32 cy, UInt32 uFlags); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern WindowsHookSafeHandle SetWindowsHookEx(Int32 idHook, CbtHookProcDelegate lpfn, IntPtr hInstance, Int32 threadId); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule", Justification = "Warning is bogus.")] [ReliabilityContract(Consistency.MayCorruptProcess, Cer.Success)] [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern Boolean UnhookWindowsHookEx(IntPtr idHook); public delegate IntPtr CbtHookProcDelegate(Int32 nCode, IntPtr wParam, IntPtr lParam); #pragma warning restore IDE0049 // Simplify Names } #endregion private static bool IsRunningOnMono { get { return (Type.GetType("Mono.Runtime") != null); } } } }
using System; using NUnit.Framework; using strange.framework.api; using strange.framework.impl; using System.Collections; namespace strange.unittests { [TestFixture()] public class TestBindingAsPoolFacade { Binding b; IPool binding; [SetUp] public void Setup() { b = new Binding (); b.ToPool (); binding = (b as IPool); } [TearDown] public void TearDown() { b = null; } [Test] public void TestSetPoolProperties() { Assert.AreEqual (0, binding.Size); binding.Size = 100; Assert.AreEqual (100, binding.Size); binding.OverflowBehavior = PoolOverflowBehavior.EXCEPTION; Assert.AreEqual (PoolOverflowBehavior.EXCEPTION, binding.OverflowBehavior); binding.OverflowBehavior = PoolOverflowBehavior.WARNING; Assert.AreEqual (PoolOverflowBehavior.WARNING, binding.OverflowBehavior); binding.OverflowBehavior = PoolOverflowBehavior.IGNORE; Assert.AreEqual (PoolOverflowBehavior.IGNORE, binding.OverflowBehavior); binding.InflationType = PoolInflationType.DOUBLE; Assert.AreEqual (PoolInflationType.DOUBLE, binding.InflationType); binding.InflationType = PoolInflationType.INCREMENT; Assert.AreEqual (PoolInflationType.INCREMENT, binding.InflationType); } [Test] public void TestGetInstance() { binding.Size = 4; for (int a = 0; a < binding.Size; a++) { b.To (new ClassToBeInjected ()); } for (int a = binding.Size; a > 0; a--) { Assert.AreEqual (a, binding.Available); ClassToBeInjected instance = binding.GetInstance () as ClassToBeInjected; Assert.IsNotNull (instance); Assert.IsInstanceOf<ClassToBeInjected> (instance); Assert.AreEqual (a - 1, binding.Available); } } [Test] public void TestReturnInstance() { binding.Size = 4; Stack stack = new Stack (binding.Size); for (int a = 0; a < binding.Size; a++) { b.To (new ClassToBeInjected ()); } for (int a = 0; a < binding.Size; a++) { stack.Push(binding.GetInstance ()); } Assert.AreEqual (binding.Size, stack.Count); Assert.AreEqual (0, binding.Available); for (int a = 0; a < binding.Size; a++) { binding.ReturnInstance (stack.Pop ()); } Assert.AreEqual (0, stack.Count); Assert.AreEqual (binding.Size, binding.Available); } [Test] public void TestClean() { binding.Size = 4; for (int a = 0; a < binding.Size; a++) { b.To (new ClassToBeInjected ()); } binding.Clean (); Assert.AreEqual (0, binding.Available); } [Test] public void TestPoolOverflowException() { binding.Size = 4; for (int a = 0; a < binding.Size; a++) { b.To (new ClassToBeInjected ()); } for (int a = binding.Size; a > 0; a--) { Assert.AreEqual (a, binding.Available); binding.GetInstance (); } TestDelegate testDelegate = delegate() { binding.GetInstance(); }; PoolException ex = Assert.Throws<PoolException> (testDelegate); Assert.That (ex.type == PoolExceptionType.OVERFLOW); } [Test] public void TestOverflowWithoutException() { binding.Size = 4; binding.OverflowBehavior = PoolOverflowBehavior.IGNORE; for (int a = 0; a < binding.Size; a++) { b.To (new ClassToBeInjected ()); } for (int a = binding.Size; a > 0; a--) { Assert.AreEqual (a, binding.Available); binding.GetInstance (); } TestDelegate testDelegate = delegate() { object shouldBeNull = binding.GetInstance(); Assert.IsNull(shouldBeNull); }; Assert.DoesNotThrow (testDelegate); } [Test] public void TestPoolTypeMismatchException() { binding.Size = 4; b.To (new ClassToBeInjected ()); TestDelegate testDelegate = delegate() { b.To(new InjectableDerivedClass()); }; PoolException ex = Assert.Throws<PoolException> (testDelegate); Assert.That (ex.type == PoolExceptionType.TYPE_MISMATCH); } [Test] public void TestRemoveFromPool() { binding.Size = 4; for (int a = 0; a < binding.Size; a++) { b.To (new ClassToBeInjected ()); } for (int a = binding.Size; a > 0; a--) { Assert.AreEqual (a, binding.Available); ClassToBeInjected instance = binding.GetInstance () as ClassToBeInjected; b.RemoveValue (instance); } Assert.AreEqual (0, binding.Available); } [Test] public void TestRemovalException() { binding.Size = 4; b.To (new ClassToBeInjected ()); TestDelegate testDelegate = delegate() { b.RemoveValue (new InjectableDerivedClass ()); }; PoolException ex = Assert.Throws<PoolException> (testDelegate); Assert.That (ex.type == PoolExceptionType.TYPE_MISMATCH); } [Test] public void TestReleaseOfPoolable() { binding.Size = 4; b.To (new PooledInstanceForBinding ()); PooledInstanceForBinding instance = binding.GetInstance () as PooledInstanceForBinding; instance.someValue = 42; Assert.AreEqual (42, instance.someValue); binding.ReturnInstance (instance); Assert.AreEqual (0, instance.someValue); } [Test] public void TestExceptionsIfNotPool() { Binding failBinding = new Binding (); IPool fb = (failBinding as IPool); assertThrowsFailedFacade ( delegate(){Console.WriteLine(fb.Available);} ); assertThrowsFailedFacade ( delegate(){fb.Clean();} ); assertThrowsFailedFacade ( delegate(){fb.GetInstance();} ); assertThrowsFailedFacade ( delegate(){Console.WriteLine(fb.InflationType);} ); assertThrowsFailedFacade ( delegate(){fb.InflationType = PoolInflationType.DOUBLE;} ); assertThrowsFailedFacade ( delegate(){Console.WriteLine(fb.OverflowBehavior);} ); assertThrowsFailedFacade ( delegate(){fb.OverflowBehavior = PoolOverflowBehavior.WARNING;} ); assertThrowsFailedFacade ( delegate(){fb.ReturnInstance("hello");} ); assertThrowsFailedFacade ( delegate(){Console.WriteLine(fb.Size);} ); assertThrowsFailedFacade ( delegate(){fb.Size = 1;} ); } private void assertThrowsFailedFacade(TestDelegate testDelegate) { PoolException ex1 = Assert.Throws<PoolException>(testDelegate); Assert.That (ex1.type == PoolExceptionType.FAILED_FACADE); } } class PooledInstanceForBinding : IPoolable { public int someValue = 0; public void Release () { someValue = 0; } } }
//--------------------------------------------------------------------- // <copyright file="ODataPreferenceHeader.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Core { using System.Collections.Generic; using System.Diagnostics; using System.Globalization; /// <summary> /// Class to set the "Prefer" header on an <see cref="IODataRequestMessage"/> or /// the "Preference-Applied" header on an <see cref="IODataResponseMessage"/>. /// </summary> public sealed class ODataPreferenceHeader { /// <summary> /// The return preference token. /// </summary> private const string ReturnPreferenceTokenName = "return"; /// <summary> /// The return=representation preference token value. /// </summary> private const string ReturnRepresentationPreferenceTokenValue = "representation"; /// <summary> /// The return=minimalpreference token value. /// </summary> private const string ReturnMinimalPreferenceTokenValue = "minimal"; /// <summary> /// The odata-annotations preference-extensions token. /// </summary> private const string ODataAnnotationPreferenceToken = "odata.include-annotations"; /// <summary> /// The respond-async preference token. /// </summary> private const string RespondAsyncPreferenceToken = "respond-async"; /// <summary> /// The wait preference token. /// </summary> private const string WaitPreferenceTokenName = "wait"; /// <summary> /// The odata.continue-on-error preference token. /// </summary> private const string ODataContinueOnErrorPreferenceToken = "odata.continue-on-error"; /// <summary> /// The odata.maxpagesize=# preference token. /// </summary> private const string ODataMaxPageSizePreferenceToken = "odata.maxpagesize"; /// <summary> /// The odata.track-changes preference token. /// </summary> private const string ODataTrackChangesPreferenceToken = "odata.track-changes"; /// <summary> /// The Prefer header name. /// </summary> private const string PreferHeaderName = "Prefer"; /// <summary> /// The Preference-Applied header name. /// </summary> private const string PreferenceAppliedHeaderName = "Preference-Applied"; /// <summary> /// Empty header parameters /// </summary> private static readonly KeyValuePair<string, string>[] EmptyParameters = new KeyValuePair<string, string>[0]; /// <summary> /// The odata.continue-on-error preference. /// </summary> private static readonly HttpHeaderValueElement ContinueOnErrorPreference = new HttpHeaderValueElement(ODataContinueOnErrorPreferenceToken, null, EmptyParameters); /// <summary> /// The return=minimal preference. /// </summary> private static readonly HttpHeaderValueElement ReturnMinimalPreference = new HttpHeaderValueElement(ReturnPreferenceTokenName, ReturnMinimalPreferenceTokenValue, EmptyParameters); /// <summary> /// The return=representation preference. /// </summary> private static readonly HttpHeaderValueElement ReturnRepresentationPreference = new HttpHeaderValueElement(ReturnPreferenceTokenName, ReturnRepresentationPreferenceTokenValue, EmptyParameters); /// <summary> /// The respond-async preference. /// </summary> private static readonly HttpHeaderValueElement RespondAsyncPreference = new HttpHeaderValueElement(RespondAsyncPreferenceToken, null, EmptyParameters); /// <summary> /// The odata.track-changes preference. /// </summary> private static readonly HttpHeaderValueElement TrackChangesPreference = new HttpHeaderValueElement(ODataTrackChangesPreferenceToken, null, EmptyParameters); /// <summary> /// The message to set the preference header to and to get the preference header from. /// </summary> private readonly ODataMessage message; /// <summary> /// "Prefer" if message is an IODataRequestMessage; "Preference-Applied" if message is an IODataResponseMessage. /// </summary> private readonly string preferenceHeaderName; /// <summary> /// Dictionary of preferences in the header /// </summary> private HttpHeaderValue preferences; /// <summary> /// Internal constructor to instantiate an <see cref="ODataPreferenceHeader"/> from an <see cref="IODataRequestMessage"/>. /// </summary> /// <param name="requestMessage">The request message to get and set the "Prefer" header.</param> internal ODataPreferenceHeader(IODataRequestMessage requestMessage) { Debug.Assert(requestMessage != null, "requestMessage != null"); this.message = new ODataRequestMessage(requestMessage, /*writing*/ true, /*disableMessageStreamDisposal*/ false, /*maxMessageSize*/ -1); this.preferenceHeaderName = PreferHeaderName; } /// <summary> /// Internal constructor to instantiate an <see cref="ODataPreferenceHeader"/> from an <see cref="IODataResponseMessage"/>. /// </summary> /// <param name="responseMessage">The response message to get and set the "Preference-Applied" header.</param> internal ODataPreferenceHeader(IODataResponseMessage responseMessage) { Debug.Assert(responseMessage != null, "responseMessage != null"); this.message = new ODataResponseMessage(responseMessage, /*writing*/ true, /*disableMessageStreamDisposal*/ false, /*maxMessageSize*/ -1); this.preferenceHeaderName = PreferenceAppliedHeaderName; } /// <summary> /// Property to get and set the "return=representation" and "return=minimal" preferences to the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// Setting true sets the "return=representation" preference and clears the "return=minimal" preference. /// Setting false sets the "return=minimal" preference and clears the "return=representation" preference. /// Setting null clears the "return=representation" and "return=minimal" preferences. /// Returns true if the "return=representation" preference is on the header. Otherwise returns false if the "return=minimal" is on the header. /// Returning null indicates that "return=representation" and "return=minimal" are not on the header. /// </summary> public bool? ReturnContent { get { var returnContentPreference = this.Get(ReturnPreferenceTokenName); if (returnContentPreference != null) { if (returnContentPreference.Value.ToLowerInvariant().Equals(ReturnRepresentationPreferenceTokenValue)) { return true; } if (returnContentPreference.Value.ToLowerInvariant().Equals(ReturnMinimalPreferenceTokenValue)) { return false; } } return null; } set { // if the value is null, the "ReturnPreferenceTokenName" is cleared. this.Clear(ReturnPreferenceTokenName); if (value == true) { this.Set(ReturnRepresentationPreference); } if (value == false) { this.Set(ReturnMinimalPreference); } } } /// <summary> /// Property to get and set the "odata.include-annotations" preference with the given filter to the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// If the "odata-annotations" preference is already on the header, set replaces the existing instance. /// Returning null indicates that the "odata.include-annotations" preference is not on the header. /// /// The filter string may be a comma delimited list of any of the following supported patterns: /// "*" -- Matches all annotation names. /// "ns.*" -- Matches all annotation names under the namespace "ns". /// "ns.name" -- Matches only the annotation name "ns.name". /// "-" -- The exclude operator may be used with any of the supported pattern, for example: /// "-ns.*" -- Excludes all annotation names under the namespace "ns". /// "-ns.name" -- Excludes only the annotation name "ns.name". /// Null or empty filter is equivalent to "-*". /// /// The relative priority of the pattern is base on the relative specificity of the patterns being compared. If pattern1 is under the namespace pattern2, /// pattern1 is more specific than pattern2 because pattern1 matches a subset of what pattern2 matches. We give higher priority to the pattern that is more specific. /// For example: /// "ns.*" has higher priority than "*" /// "ns.name" has higher priority than "ns.*" /// "ns1.name" has same priority as "ns2.*" /// /// Patterns with the exclude operator takes higher precedence than the same pattern without. /// For example: "-ns.name" has higher priority than "ns.name". /// /// Examples: /// "ns1.*,ns.name" -- Matches any annotation name under the "ns1" namespace and the "ns.name" annotation. /// "*,-ns.*,ns.name" -- Matches any annotation name outside of the "ns" namespace and only "ns.name" under the "ns" namespace. /// </summary> public string AnnotationFilter { get { var odataAnnotations = this.Get(ODataAnnotationPreferenceToken); if (odataAnnotations != null) { return odataAnnotations.Value.Trim('"'); } return null; } set { ExceptionUtils.CheckArgumentStringNotEmpty(value, "AnnotationFilter"); if (value == null) { this.Clear(ODataAnnotationPreferenceToken); } else { this.Set(new HttpHeaderValueElement(ODataAnnotationPreferenceToken, AddQuotes(value), EmptyParameters)); } } } /// <summary> /// Property to get and set the "respond-async" preference to the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// Setting true sets the "respond-async" preference. /// Setting false clears the "respond-async" preference. /// Returns true if the "respond-async" preference is on the header. Otherwise returns false if the "respond-async" is not on the header. /// </summary> public bool RespondAsync { get { return this.Get(RespondAsyncPreferenceToken) != null; } set { if (value) { this.Set(RespondAsyncPreference); } else { this.Clear(RespondAsyncPreferenceToken); } } } /// <summary> /// Property to get and set the "wait" preference to the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// Setting N sets the "wait=N" preference. /// Setting null clears the "wait" preference. /// Returns N if the "wait=N" preference is on the header. /// Returning null indicates that "wait" is not on the header. /// </summary> public int? Wait { get { var wait = this.Get(WaitPreferenceTokenName); if (wait != null) { return int.Parse(wait.Value, CultureInfo.InvariantCulture); } return null; } set { if (value != null) { this.Set(new HttpHeaderValueElement(WaitPreferenceTokenName, string.Format(CultureInfo.InvariantCulture, "{0}", value), EmptyParameters)); } else { this.Clear(WaitPreferenceTokenName); } } } /// <summary> /// Property to get and set the "odata.continue-on-error" preference to the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// Setting true sets the "odata.continue-on-error" preference. /// Setting false clears the "odata.continue-on-error" preference. /// Returns true of the "odata.continue-on-error" preference is on the header. Otherwise returns false if the "odata.continue-on-error" is not on the header. /// </summary> public bool ContinueOnError { get { return this.Get(ODataContinueOnErrorPreferenceToken) != null; } set { if (value) { this.Set(ContinueOnErrorPreference); } else { this.Clear(ODataContinueOnErrorPreferenceToken); } } } /// <summary> /// Property to get and set the "odata.maxpagesize" preference to the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// Setting N sets the "odata.maxpagesize=N" preference. /// Setting null clears the "odata.maxpagesize" preference. /// Returns N if the "odata.maxpagesize=N" preference is on the header. /// Returning null indicates that "odata.maxpagesize" is not on the header. /// </summary> public int? MaxPageSize { get { var maxPageSizeHttpHeaderValueElement = this.Get(ODataMaxPageSizePreferenceToken); // Should check maxPageSizeHttpHeaderValueElement.Value != null. // Should do int.TryParse. // If either of the above fail, should throw an ODataException for parsing, not a System.Exception (such as FormatException, etc.). if (maxPageSizeHttpHeaderValueElement != null) { return int.Parse(maxPageSizeHttpHeaderValueElement.Value, CultureInfo.InvariantCulture); } return null; } set { if (value.HasValue) { this.Set(new HttpHeaderValueElement(ODataMaxPageSizePreferenceToken, string.Format(CultureInfo.InvariantCulture, "{0}", value.Value), EmptyParameters)); } else { this.Clear(ODataMaxPageSizePreferenceToken); } } } /// <summary> /// Property to get and set the "odata.track-changes" preference to the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// Setting true sets the "odata.track-changes" preference. /// Setting false clears the "odata.track-changes" preference. /// Returns true of the "odata.track-changes" preference is on the header. Otherwise returns false if the "odata.track-changes" is not on the header. /// </summary> public bool TrackChanges { get { return this.Get(ODataTrackChangesPreferenceToken) != null; } set { if (value) { this.Set(TrackChangesPreference); } else { this.Clear(ODataTrackChangesPreferenceToken); } } } /// <summary> /// Dictionary of preferences in the header. /// </summary> private HttpHeaderValue Preferences { get { return this.preferences ?? (this.preferences = this.ParsePreferences()); } } /// <summary> /// Adds quotes around the given text value. /// </summary> /// <param name="text">text to quote.</param> /// <returns>Returns the quoted text.</returns> private static string AddQuotes(string text) { return "\"" + text + "\""; } /// <summary> /// Clears the <paramref name="preference"/> from the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// </summary> /// <param name="preference">The preference to clear.</param> private void Clear(string preference) { Debug.Assert(!string.IsNullOrEmpty(preference), "!string.IsNullOrEmpty(preference)"); if (this.Preferences.Remove(preference)) { this.SetPreferencesToMessageHeader(); } } /// <summary> /// Sets the <paramref name="preference"/> to the "Prefer" header on the underlying IODataRequestMessage or /// the "Preference-Applied" header on the underlying IODataResponseMessage. /// </summary> /// <param name="preference">The preference to set.</param> /// <remarks> /// If <paramref name="preference"/> is already on the header, this method does a replace rather than adding another instance of the same preference. /// </remarks> private void Set(HttpHeaderValueElement preference) { Debug.Assert(preference != null, "preference != null"); this.Preferences[preference.Name] = preference; this.SetPreferencesToMessageHeader(); } /// <summary> /// Gets the <paramref name="preferenceName"/> from the "Prefer" header from the underlying <see cref="IODataRequestMessage"/> or /// the "Preference-Applied" header from the underlying <see cref="IODataResponseMessage"/>. /// </summary> /// <param name="preferenceName">The preference to get.</param> /// <returns>Returns a key value pair of the <paramref name="preferenceName"/> and its value. The Value property of the key value pair may be null since not /// all preferences have value. If the <paramref name="preferenceName"/> is missing from the header, null is returned.</returns> private HttpHeaderValueElement Get(string preferenceName) { Debug.Assert(!string.IsNullOrEmpty(preferenceName), "!string.IsNullOrEmpty(preferenceName)"); HttpHeaderValueElement value; if (!this.Preferences.TryGetValue(preferenceName, out value)) { return null; } return value; } /// <summary> /// Parses the current preference values to a dictionary of preference and value pairs. /// </summary> /// <returns>Returns a dictionary of preference and value pairs; null if the preference header has not been set.</returns> private HttpHeaderValue ParsePreferences() { string preferenceHeaderValue = this.message.GetHeader(this.preferenceHeaderName); HttpHeaderValueLexer preferenceHeaderLexer = HttpHeaderValueLexer.Create(this.preferenceHeaderName, preferenceHeaderValue); return preferenceHeaderLexer.ToHttpHeaderValue(); } /// <summary> /// Sets the "Prefer" or the "Preference-Applied" header to the underlying message. /// </summary> private void SetPreferencesToMessageHeader() { Debug.Assert(this.preferences != null, "this.preferences != null"); this.message.SetHeader(this.preferenceHeaderName, this.Preferences.ToString()); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace System.Runtime.Analyzers.UnitTests { public class TestForNaNCorrectlyTests : DiagnosticAnalyzerTestBase { [Fact] public void CSharpDiagnosticForEqualityWithFloatNaN() { var code = @" public class A { public bool Compare(float f) { return f == float.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicDiagnosticForEqualityWithFloatNaN() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f = Single.NaN End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } [Fact] public void CSharpDiagnosticForInequalityWithFloatNaN() { var code = @" public class A { public bool Compare(float f) { return f != float.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicDiagnosticForInEqualityWithFloatNaN() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f <> Single.NaN End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } [Fact] public void CSharpDiagnosticForGreaterThanFloatNaN() { var code = @" public class A { public bool Compare(float f) { return f > float.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicDiagnosticForGreaterThanFloatNaN() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f > Single.NaN End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } [Fact] public void CSharpDiagnosticForGreaterThanOrEqualToFloatNaN() { var code = @" public class A { public bool Compare(float f) { return f >= float.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicDiagnosticForGreaterThanOrEqualToFloatNaN() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f >= Single.NaN End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } [Fact] public void CSharpDiagnosticForLessThanFloatNaN() { var code = @" public class A { public bool Compare(float f) { return f < float.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicDiagnosticForLessThanFloatNaN() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f < Single.NaN End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } [Fact] public void CSharpDiagnosticForLessThanOrEqualToFloatNaN() { var code = @" public class A { public bool Compare(float f) { return f <= float.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicDiagnosticForLessThanOrEqualToFloatNaN() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f <= Single.NaN End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } [Fact] public void CSharpDiagnosticForComparisonWithDoubleNaN() { var code = @" public class A { public bool Compare(double d) { return d == double.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicDiagnosticForComparisonWithDoubleNaN() { var code = @" Public Class A Public Function Compare(d As Double) As Boolean Return d < Double.NaN End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } [Fact] public void CSharpDiagnosticForComparisonWithNaNOnLeft() { var code = @" public class A { public bool Compare(double d) { return double.NaN == d; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicDiagnosticForComparisonWithNaNOnLeft() { var code = @" Public Class A Public Function Compare(d As Double) As Boolean Return Double.NaN = d End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } [Fact] public void CSharpNoDiagnosticForComparisonWithBadExpression() { var code = @" public class A { public bool Compare(float f) { return f == float.NbN; // Misspelled. } } "; VerifyCSharp(code, TestValidationMode.AllowCompileErrors); } [Fact] public void BasicNoDiagnosticForComparisonWithBadExpression() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f = Single.NbN ' Misspelled End Function End Class "; VerifyBasic(code, TestValidationMode.AllowCompileErrors); } [Fact] public void CSharpNoDiagnosticForComparisonWithFunctionReturningNaN() { var code = @" public class A { public bool Compare(float f) { return f == NaNFunc(); } private float NaNFunc() { return float.NaN; } } "; VerifyCSharp(code); } [Fact] public void BasicNoDiagnosticForComparisonWithFunctionReturningNaN() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f = NaNFunc() End Function Private Function NaNFunc() As Single Return Single.NaN End Function End Class "; VerifyBasic(code); } [Fact] public void CSharpNoDiagnosticForEqualityWithNonNaN() { var code = @" public class A { public bool Compare(float f) { return f == 1.0; } } "; VerifyCSharp(code); } [Fact] public void BasicNoDiagnosticForEqualityWithNonNaN() { var code = @" Public Class A Public Function Compare(f As Single) As Boolean Return f = 1.0 End Function End Class "; VerifyBasic(code); } [Fact] public void CSharpNoDiagnosticForNonComparisonOperationWithNaN() { var code = @" public class A { public float OperateOn(float f) { return f + float.NaN; } } "; VerifyCSharp(code); } [Fact] public void BasicNoDiagnosticForNonComparisonOperationWithNonNaN() { var code = @" Public Class A Public Function OperateOn(f As Single) As Single Return f + Single.NaN End Function End Class "; VerifyBasic(code); } [Fact] public void CSharpOnlyOneDiagnosticForComparisonWithNaNOnBothSides() { var code = @" public class A { public bool Compare() { return float.NaN == float.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(6, 16)); } [Fact] public void BasicOnlyOneDiagnosticForComparisonWithNonNaNOnBothSides() { var code = @" Public Class A Public Function Compare() As Boolean Return Single.NaN = Single.NaN End Function End Class "; VerifyBasic(code, GetBasicResultAt(4, 16)); } // At @srivatsn's suggestion, here are a few tests that verify that the operation // tree is correct when the comparison occurs in syntactic constructs other than // a function return value. Of course we can't be exhaustive about this, and these // tests are really more about the correctness of the operation tree -- ensuring // that "binary operator expressions" are present in places we expect them to be -- // than they are about the correctness of our treatment of these expressions once // we find them. [Fact] public void CSharpDiagnosticForComparisonWithNaNInFunctionArgument() { var code = @" public class A { float _n = 42.0F; public void F() { G(_n == float.NaN); } public void G(bool comparison) {} } "; VerifyCSharp(code, GetCSharpResultAt(8, 11)); } [Fact] public void BasicDiagnosticForComparisonWithNaNInFunctionArgument() { var code = @" Public Class A Private _n As Single = 42.0F Public Sub F() G(_n = Single.NaN) End Sub Public Sub G(comparison As Boolean) End Sub End Class "; VerifyBasic(code, GetBasicResultAt(6, 11)); } [Fact] public void CSharpDiagnosticForComparisonWithNaNInTernaryOperator() { var code = @" public class A { float _n = 42.0F; public int F() { return _n == float.NaN ? 1 : 0; } } "; VerifyCSharp(code, GetCSharpResultAt(8, 16)); } [Fact] public void BasicDiagnosticForComparisonWithNaNInIfOperator() { // VB doesn't have the ternary operator, but we add this test for symmetry. var code = @" Public Class A Private _n As Single = 42.0F Public Function F() As Integer Return If(_n = Single.NaN, 1, 0) End Function End Class "; VerifyBasic(code, GetBasicResultAt(6, 19)); } [Fact] public void CSharpDiagnosticForComparisonWithNaNInThrowStatement() { var code = @" public class A { float _n = 42.0F; public void F() { throw _n != float.NaN ? new System.Exception() : new System.ArgumentException(); } } "; VerifyCSharp(code, GetCSharpResultAt(8, 15)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/11741")] public void CSharpDiagnosticForComparisonWithNaNInCatchFilterClause() { var code = @" public class A { float _n = 42.0F; public void F() { try { } catch (Exception ex) when (_n != float.NaN) { } } } "; VerifyCSharp(code, GetCSharpResultAt(11, 36)); } [Fact] public void CSharpDiagnosticForComparisonWithNaNInYieldReturnStatement() { var code = @" using System.Collections.Generic; public class A { float _n = 42.0F; public IEnumerable<bool> F() { yield return _n != float.NaN; } } "; VerifyCSharp(code, GetCSharpResultAt(10, 22)); } [Fact] public void CSharpDiagnosticForComparisonWithNaNInSwitchStatement() { var code = @" public class A { float _n = 42.0F; public void F() { switch (_n != float.NaN) { default: throw new System.NotImplementedException(); } } } "; VerifyCSharp(code, GetCSharpResultAt(8, 17)); } [Fact] public void CSharpDiagnosticForComparisonWithNaNInForLoop() { var code = @" public class A { float _n = 42.0F; public void F() { for (; _n != float.NaN; ) { throw new System.Exception(); } } } "; VerifyCSharp(code, GetCSharpResultAt(8, 16)); } [Fact] public void CSharpDiagnosticForComparisonWithNaNInWhileLoop() { var code = @" public class A { float _n = 42.0F; public void F() { while (_n != float.NaN) { } } } "; VerifyCSharp(code, GetCSharpResultAt(8, 16)); } [Fact] public void CSharpDiagnosticForComparisonWithNaNInDoWhileLoop() { var code = @" public class A { float _n = 42.0F; public void F() { do { } while (_n != float.NaN); } } "; VerifyCSharp(code, GetCSharpResultAt(11, 16)); } protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new TestForNaNCorrectlyAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new TestForNaNCorrectlyAnalyzer(); } private DiagnosticResult GetCSharpResultAt(int line, int column) { return GetCSharpResultAt(line, column, TestForNaNCorrectlyAnalyzer.Rule); } private DiagnosticResult GetBasicResultAt(int line, int column) { return GetBasicResultAt(line, column, TestForNaNCorrectlyAnalyzer.Rule); } } }
// ------------------------------------------------------------------------------------------- // <copyright file="OrderLineMappingRule.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // ------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // 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 Sitecore.Ecommerce.Data { using System.Globalization; using DomainModel.Orders; using Utils; using Validators.Interception; /// <summary> /// The product line mapping rule. /// </summary> public class OrderLineMappingRule : IMappingRule<OrderLine> { #region Implementation of IMappingRule<Order> /// <summary> /// Gets or sets the mapping object. /// </summary> /// <value>The mapping object.</value> public OrderLine MappingObject { get; [NotNullValue] set; } #endregion /// <summary> /// Gets or sets the type. /// </summary> /// <value>The type of the order line.</value> [Entity(FieldName = "Type")] public virtual string Type { get { return this.MappingObject.Type; } [NotNullValue] set { this.MappingObject.Type = value; } } /// <summary> /// Gets or sets the id. /// </summary> /// <value>The product line id.</value> [Entity(FieldName = "Id")] public virtual string Id { get { return this.MappingObject.Product.Code; } [NotNullValue] set { this.MappingObject.Product.Code = value; } } /// <summary> /// Gets or sets the description. /// </summary> /// <value>The description.</value> [Entity(FieldName = "Description")] public virtual string Description { get { return this.MappingObject.Product.Title; } [NotNullValue] set { this.MappingObject.Product.Title = value; } } /// <summary> /// Gets or sets the VAT. /// </summary> /// <value>The VAT value.</value> [Entity(FieldName = "Vat")] public virtual string Vat { get { return this.MappingObject.Totals.VAT.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.VAT = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the total price ex vat. /// </summary> /// <value>The total price ex vat.</value> [Entity(FieldName = "TotalPriceExVat")] public virtual string TotalPriceExVat { get { return this.MappingObject.Totals.TotalPriceExVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.TotalPriceExVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the total price inc vat. /// </summary> /// <value>The total price inc vat.</value> [Entity(FieldName = "TotalPriceIncVat")] public virtual string TotalPriceIncVat { get { return this.MappingObject.Totals.TotalPriceIncVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.TotalPriceIncVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the discount ex vat. /// </summary> /// <value>The discount ex vat.</value> [Entity(FieldName = "DiscountExVat")] public virtual string DiscountExVat { get { return this.MappingObject.Totals.DiscountExVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.DiscountExVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the discount inc vat. /// </summary> /// <value>The discount inc vat.</value> [Entity(FieldName = "DiscountIncVat")] public virtual string DiscountIncVat { get { return this.MappingObject.Totals.DiscountIncVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.DiscountIncVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the price ex vat. /// </summary> /// <value>The price ex vat.</value> [Entity(FieldName = "PriceExVat")] public virtual string PriceExVat { get { return this.MappingObject.Totals.PriceExVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.PriceExVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the price inc vat. /// </summary> /// <value>The price inc vat.</value> [Entity(FieldName = "PriceIncVat")] public virtual string PriceIncVat { get { return this.MappingObject.Totals.PriceIncVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.PriceIncVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the total vat. /// </summary> /// <value>The total vat.</value> [Entity(FieldName = "TotalVat")] public virtual string TotalVat { get { return this.MappingObject.Totals.TotalVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.TotalVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the possible discount ex vat. /// </summary> /// <value>The possible discount ex vat.</value> [Entity(FieldName = "PossibleDiscountExVat")] public virtual string PossibleDiscountExVat { get { return this.MappingObject.Totals.PossibleDiscountExVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.PossibleDiscountExVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the possible discount inc vat. /// </summary> /// <value>The possible discount inc vat.</value> [Entity(FieldName = "PossibleDiscountIncVat")] public virtual string PossibleDiscountIncVat { get { return this.MappingObject.Totals.PossibleDiscountIncVat.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Totals.PossibleDiscountIncVat = TypeUtil.TryParse(value, decimal.Zero); } } /// <summary> /// Gets or sets the quantity. /// </summary> /// <value>The quantity.</value> [Entity(FieldName = "Quantity")] public virtual string Quantity { get { return this.MappingObject.Quantity.ToString(CultureInfo.InvariantCulture); } [NotNullValue] set { this.MappingObject.Quantity = TypeUtil.Parse<uint>(value); } } /// <summary> /// Gets or sets the friendly URL. /// </summary> /// <value>The friendly URL.</value> [Entity(FieldName = "ProductUrl")] public virtual string FriendlyUrl { get { return this.MappingObject.FriendlyUrl; } set { this.MappingObject.FriendlyUrl = value; } } } }
// 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.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; 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 Microsoft.Rest.Azure; using Models; /// <summary> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestLongRunningOperationTestService : ServiceClient<AutoRestLongRunningOperationTestService>, IAutoRestLongRunningOperationTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// The management credentials for Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// The retry timeout for Long Running Operations. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } public virtual ILROsOperations LROs { get; private set; } public virtual ILRORetrysOperations LRORetrys { get; private set; } public virtual ILROSADsOperations LROSADs { get; private set; } public virtual ILROsCustomHeaderOperations LROsCustomHeader { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestLongRunningOperationTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestLongRunningOperationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestLongRunningOperationTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestLongRunningOperationTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestLongRunningOperationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestLongRunningOperationTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestLongRunningOperationTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestLongRunningOperationTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.LROs = new LROsOperations(this); this.LRORetrys = new LRORetrysOperations(this); this.LROSADs = new LROSADsOperations(this); this.LROsCustomHeader = new LROsCustomHeaderOperations(this); this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/* Copyright 2012-2022 Marco De Salvo Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Microsoft.VisualStudio.TestTools.UnitTesting; using RDFSharp.Model; using System; using System.Collections.Generic; using System.Linq; namespace RDFSharp.Test.Model { [TestClass] public class RDFUniqueLangConstraintTest { #region Tests [DataTestMethod] [DataRow(true)] [DataRow(false)] public void ShouldCreateUniqueLangConstraint(bool uniqueLang) { RDFUniqueLangConstraint ulConstraint = new RDFUniqueLangConstraint(uniqueLang); Assert.IsNotNull(ulConstraint); Assert.IsTrue(ulConstraint.UniqueLang.Equals(uniqueLang)); } [TestMethod] [DataRow(true)] [DataRow(false)] public void ShouldExportUniqueLangConstraint(bool uniqueLang) { RDFUniqueLangConstraint ulConstraint = new RDFUniqueLangConstraint(uniqueLang); RDFGraph graph = ulConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape"))); Assert.IsNotNull(graph); Assert.IsTrue(graph.TriplesCount == 1); if (uniqueLang) Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape")) && t.Value.Predicate.Equals(RDFVocabulary.SHACL.UNIQUE_LANG) && t.Value.Object.Equals(RDFTypedLiteral.True))); else Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape")) && t.Value.Predicate.Equals(RDFVocabulary.SHACL.UNIQUE_LANG) && t.Value.Object.Equals(RDFTypedLiteral.False))); } //PS-CONFORMS:TRUE [TestMethod] public void ShouldConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-UK"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFUniqueLangConstraint(true)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithClassTargetAndFalseConfiguration() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-UK"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFUniqueLangConstraint(false)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithClassTargetAndUnlanguagedValues() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alyce"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFUniqueLangConstraint(false)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-UK"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); propertyShape.AddConstraint(new RDFUniqueLangConstraint(true)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-UK"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.RDF.TYPE)); propertyShape.AddConstraint(new RDFUniqueLangConstraint(true)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFUniqueLangConstraint(true)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //PS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alyce", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alyse", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFUniqueLangConstraint(true)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must not have the same language tag more than one time per value"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.NAME)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.UNIQUE_LANG_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alyce", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); propertyShape.AddConstraint(new RDFUniqueLangConstraint(true)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must not have the same language tag more than one time per value"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.NAME)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.UNIQUE_LANG_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alyce", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.RDF.TYPE)); propertyShape.AddConstraint(new RDFUniqueLangConstraint(true)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must not have the same language tag more than one time per value"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.NAME)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.UNIQUE_LANG_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alice", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Alyce", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Bob", "en-US"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.NAME); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFUniqueLangConstraint(true)); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must not have the same language tag more than one time per value"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultValue); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.NAME)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.UNIQUE_LANG_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using osu.Framework; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Allocation; using osu.Framework.Layout; using osu.Framework.Threading; namespace osu.Game.Screens.Play { public class SquareGraph : Container { private BufferedContainer<Column> columns; public SquareGraph() { AddLayout(layout); } public int ColumnCount => columns?.Children.Count ?? 0; private int progress; public int Progress { get => progress; set { if (value == progress) return; progress = value; redrawProgress(); } } private float[] calculatedValues = Array.Empty<float>(); // values but adjusted to fit the amount of columns private int[] values; public int[] Values { get => values; set { if (value == values) return; values = value; layout.Invalidate(); } } private Color4 fillColour; public Color4 FillColour { get => fillColour; set { if (value == fillColour) return; fillColour = value; redrawFilled(); } } private readonly LayoutValue layout = new LayoutValue(Invalidation.DrawSize); private ScheduledDelegate scheduledCreate; protected override void Update() { base.Update(); if (values != null && !layout.IsValid) { columns?.FadeOut(500, Easing.OutQuint).Expire(); scheduledCreate?.Cancel(); scheduledCreate = Scheduler.AddDelayed(RecreateGraph, 500); layout.Validate(); } } private CancellationTokenSource cts; /// <summary> /// Recreates the entire graph. /// </summary> protected virtual void RecreateGraph() { var newColumns = new BufferedContainer<Column>(cachedFrameBuffer: true) { RedrawOnScale = false, RelativeSizeAxes = Axes.Both, }; for (float x = 0; x < DrawWidth; x += Column.WIDTH) { newColumns.Add(new Column(DrawHeight) { LitColour = fillColour, Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Position = new Vector2(x, 0), State = ColumnState.Dimmed, }); } cts?.Cancel(); LoadComponentAsync(newColumns, c => { Child = columns = c; columns.FadeInFromZero(500, Easing.OutQuint); recalculateValues(); redrawFilled(); redrawProgress(); }, (cts = new CancellationTokenSource()).Token); } /// <summary> /// Redraws all the columns to match their lit/dimmed state. /// </summary> private void redrawProgress() { for (int i = 0; i < ColumnCount; i++) columns[i].State = i <= progress ? ColumnState.Lit : ColumnState.Dimmed; columns?.ForceRedraw(); } /// <summary> /// Redraws the filled amount of all the columns. /// </summary> private void redrawFilled() { for (int i = 0; i < ColumnCount; i++) columns[i].Filled = calculatedValues.ElementAtOrDefault(i); columns?.ForceRedraw(); } /// <summary> /// Takes <see cref="Values"/> and adjusts it to fit the amount of columns. /// </summary> private void recalculateValues() { var newValues = new List<float>(); if (values == null) { for (float i = 0; i < ColumnCount; i++) newValues.Add(0); return; } int max = values.Max(); float step = values.Length / (float)ColumnCount; for (float i = 0; i < values.Length; i += step) { newValues.Add((float)values[(int)i] / max); } calculatedValues = newValues.ToArray(); } public class Column : Container, IStateful<ColumnState> { protected readonly Color4 EmptyColour = Color4.White.Opacity(20); public Color4 LitColour = Color4.LightBlue; protected readonly Color4 DimmedColour = Color4.White.Opacity(140); private float cubeCount => DrawHeight / WIDTH; private const float cube_size = 4; private const float padding = 2; public const float WIDTH = cube_size + padding; public event Action<ColumnState> StateChanged; private readonly List<Box> drawableRows = new List<Box>(); private float filled; public float Filled { get => filled; set { if (value == filled) return; filled = value; fillActive(); } } private ColumnState state; public ColumnState State { get => state; set { if (value == state) return; state = value; if (IsLoaded) fillActive(); StateChanged?.Invoke(State); } } public Column(float height) { Width = WIDTH; Height = height; } [BackgroundDependencyLoader] private void load() { drawableRows.AddRange(Enumerable.Range(0, (int)cubeCount).Select(r => new Box { Size = new Vector2(cube_size), Position = new Vector2(0, r * WIDTH + padding), })); Children = drawableRows; // Reverse drawableRows so when iterating through them they start at the bottom drawableRows.Reverse(); } protected override void LoadComplete() { base.LoadComplete(); fillActive(); } private void fillActive() { Color4 colour = State == ColumnState.Lit ? LitColour : DimmedColour; int countFilled = (int)Math.Clamp(filled * drawableRows.Count, 0, drawableRows.Count); for (int i = 0; i < drawableRows.Count; i++) drawableRows[i].Colour = i < countFilled ? colour : EmptyColour; } } public enum ColumnState { Lit, Dimmed } } }
#region Apache License v2.0 //Copyright 2014 Stephen Yu //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except //in compliance with the License. You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software distributed under the License //is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express //or implied. See the License for the specific language governing permissions and limitations under //the License. #endregion namespace StarMQ { using Consume; using Core; using Model; using Publish; using RabbitMQ.Client.Exceptions; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Queue = Model.Queue; public interface IAdvancedBus : IDisposable { Task ConsumeAsync(Queue queue, Action<IHandlerRegistrar> configure); Task ExchangeDeclareAsync(Exchange exchange); /// <summary> /// With publisher confirms enabled, dispatcher completes task upon receiving Ack or Nack. /// If timeout elapses, message is published again. /// </summary> /// <param name="mandatory">If true, published messages must be routed at least one queue. Otherwise, returned via basic.return.</param> /// <param name="immediate">Not supported by RabbitMQ - use TTL=0. If true, message is only delivered to matching queues with a consumer currently able to accept the message. If no deliveries occur, it is returned via basic.return.</param> Task PublishAsync<T>(Exchange exchange, string routingKey, bool mandatory, bool immediate, IMessage<T> message) where T : class; /// <summary> /// Allows a queue to begin receiving messages matching the routing key from specified exchange. /// </summary> Task QueueBindAsync(Exchange exchange, Queue queue, string routingKey); Task QueueDeclareAsync(Queue queue); /// <summary> /// Fired upon receiving a basic.return for a published message. /// </summary> event BasicReturnHandler BasicReturn; } public class AdvancedBus : IAdvancedBus { private const string KeyFormat = "{0}:{1}:{2}"; // exchange:queue:routingKey private readonly IConsumerFactory _consumerFactory; private readonly IOutboundDispatcher _dispatcher; private readonly ILog _log; private readonly IPublisher _publisher; private readonly ConcurrentDictionary<string, Task> _tasks = new ConcurrentDictionary<string, Task>(); private bool _disposed; public event BasicReturnHandler BasicReturn; public AdvancedBus(IConsumerFactory consumerFactory, IOutboundDispatcher dispatcher, ILog log, IPublisher publisher) { _consumerFactory = consumerFactory; _dispatcher = dispatcher; _log = log; _publisher = publisher; _publisher.BasicReturn += (o, args) => { var basicReturn = BasicReturn; if (basicReturn != null) BasicReturn(o, args); }; } public async Task ConsumeAsync(Queue queue, Action<IHandlerRegistrar> configure) { if (queue == null) throw new ArgumentNullException("queue"); await _consumerFactory.CreateConsumer(queue.Exclusive).Consume(queue, configure); _log.Info(String.Format("Consumption from queue '{0}' started.", queue.Name)); } public async Task ExchangeDeclareAsync(Exchange exchange) { if (exchange == null) throw new ArgumentNullException("exchange"); await _tasks.AddOrUpdate(String.Format(KeyFormat, exchange.Name, String.Empty, String.Empty), x => InvokeExchangeDeclareAsync(exchange), (_, existing) => existing); } private async Task InvokeExchangeDeclareAsync(Exchange exchange) { if (exchange == null) throw new ArgumentNullException("exchange"); await _dispatcher.Invoke(x => { try { using (var model = x.CreateModel()) model.ExchangeDeclarePassive(exchange.Name); _log.Info(String.Format("Exchange '{0}' already exists.", exchange.Name)); return; } catch (OperationInterruptedException ex) { if (!IsAmqpNotFoundError(ex)) throw; if (exchange.Passive) return; } var args = new Dictionary<string, object>(); var config = new StringBuilder(); if (!String.IsNullOrEmpty(exchange.AlternateExchangeName)) { args.Add("alternate-exchange", exchange.AlternateExchangeName); config.Append(" [AE]=").Append(exchange.AlternateExchangeName); } using (var model = x.CreateModel()) model.ExchangeDeclare(exchange.Name, exchange.Type.ToString().ToLower(), exchange.Durable, exchange.AutoDelete, args); _log.Info(String.Format("Exchange '{0}' declared.{1}", exchange.Name, config)); }); } private static bool IsAmqpNotFoundError(OperationInterruptedException ex) { return ex.Message.Contains("AMQP operation") && ex.Message.Contains("code=404"); } public async Task PublishAsync<T>(Exchange exchange, string routingKey, bool mandatory, bool immediate, IMessage<T> message) where T : class { if (exchange == null) throw new ArgumentNullException("exchange"); if (routingKey == null) throw new ArgumentNullException("routingKey"); await _dispatcher.Invoke(() => _publisher.Publish(message, (x, y, z) => x.BasicPublish(exchange.Name, routingKey, mandatory, false, y, z))); _log.Info(String.Format("Message published to '{0}' with routing key '{1}'", exchange.Name, routingKey)); } public async Task QueueBindAsync(Exchange exchange, Queue queue, string routingKey) { if (exchange == null) throw new ArgumentNullException("exchange"); if (queue == null) throw new ArgumentNullException("queue"); if (routingKey == null) throw new ArgumentNullException("routingKey"); await _tasks.AddOrUpdate(String.Format(KeyFormat, exchange.Name, queue.Name, routingKey), x => InvokeQueueBindAsync(exchange, queue, routingKey), (_, existing) => existing); } private async Task InvokeQueueBindAsync(Exchange exchange, Queue queue, string routingKey) { if (exchange == null) throw new ArgumentNullException("exchange"); if (queue == null) throw new ArgumentNullException("queue"); if (routingKey == null) throw new ArgumentNullException("routingKey"); await _dispatcher.Invoke(x => { using (var model = x.CreateModel()) model.QueueBind(queue.Name, exchange.Name, routingKey); _log.Info(String.Format("Queue '{0}' bound to exchange '{1}' with routing key '{2}'.", queue.Name, exchange.Name, routingKey)); }); } public async Task QueueDeclareAsync(Queue queue) { if (queue == null) throw new ArgumentNullException("queue"); await _tasks.AddOrUpdate(String.Format(KeyFormat, String.Empty, queue.Name, String.Empty), x => InvokeQueueDeclareAsync(queue), (_, existing) => existing); } private async Task InvokeQueueDeclareAsync(Queue queue) { if (queue == null) throw new ArgumentNullException("queue"); await _dispatcher.Invoke(x => { try { using (var model = x.CreateModel()) model.QueueDeclarePassive(queue.Name); _log.Info(String.Format("Queue '{0}' already exists.", queue.Name)); return; } catch (OperationInterruptedException ex) { if (!IsAmqpNotFoundError(ex)) throw; if (queue.Passive) return; } var args = new Dictionary<string, object>(); var config = new StringBuilder(); if (!String.IsNullOrEmpty(queue.DeadLetterExchangeName)) { args.Add("x-dead-letter-exchange", queue.DeadLetterExchangeName); config.Append(" [DLX]=").Append(queue.DeadLetterExchangeName); } if (!String.IsNullOrEmpty(queue.DeadLetterRoutingKey)) args.Add("x-dead-letter-routing-key", queue.DeadLetterRoutingKey); if (queue.Expires > 0) { args.Add("x-expires", queue.Expires); config.Append(" [Expires]=").Append(queue.Expires); } if (queue.MessageTimeToLive != uint.MaxValue) { args.Add("x-message-ttl", queue.MessageTimeToLive); config.Append(" [TTL]=").Append(queue.MessageTimeToLive); } using (var model = x.CreateModel()) model.QueueDeclare(queue.Name, queue.Durable, queue.Exclusive, queue.AutoDelete, args); _log.Info(String.Format("Queue '{0}' declared.{1}", queue.Name, config)); }); } public void Dispose() { if (_disposed) return; _disposed = true; _dispatcher.Dispose(); _log.Info("Dispose completed."); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public partial class ParallelQueryCombinationTests { [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Cast_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); foreach (int? i in operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>()) { Assert.True(i.HasValue); seen.Add(i.Value); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Cast_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>().ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void DefaultIfEmpty_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty()) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void DefaultIfEmpty_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty().ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Distinct_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); foreach (int i in query) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Distinct_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); Assert.All(query.ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Except_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item)); foreach (int i in query) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Except_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item)); Assert.All(query.ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GetEnumerator_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); IEnumerator<int> enumerator = operation.Item(DefaultStart, DefaultSize, source.Item).GetEnumerator(); while (enumerator.MoveNext()) { int current = enumerator.Current; seen.Add(current); Assert.Equal(current, enumerator.Current); } seen.AssertComplete(); Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GroupBy_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor); foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor)) { seenKey.Add(group.Key); IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor)); Assert.All(group, x => seenElement.Add(x)); seenElement.AssertComplete(); } seenKey.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GroupBy_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor); foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor).ToList()) { seenKey.Add(group.Key); IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor)); Assert.All(group, x => seenElement.Add(x)); seenElement.AssertComplete(); } seenKey.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GroupBy_ElementSelector_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor); foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y)) { seenKey.Add(group.Key); IntegerRangeSet seenElement = new IntegerRangeSet(1 - Math.Min(DefaultStart + DefaultSize, (group.Key + 1) * GroupFactor), Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor)); Assert.All(group, x => seenElement.Add(x)); seenElement.AssertComplete(); } seenKey.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void GroupBy_ElementSelector_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor); foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y).ToList()) { seenKey.Add(group.Key); IntegerRangeSet seenElement = new IntegerRangeSet(1 - Math.Min(DefaultStart + DefaultSize, (group.Key + 1) * GroupFactor), Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor)); Assert.All(group, x => seenElement.Add(x)); seenElement.AssertComplete(); } seenKey.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Intersect_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); foreach (int i in query) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Intersect_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); Assert.All(query.ToList(), x => seen.Add((int)x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OfType_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>()) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OfType_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>().ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Select_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Select_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Select_Index_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { indices.Add(index); return -x; })) { seen.Add(i); } seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Select_Index_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { indices.Add(index); return -x; }).ToList(), x => seen.Add(x)); seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Indexed_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); })) { seen.Add(i); } seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Indexed_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => seen.Add(x)); seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_ResultSelector_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_ResultSelector_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Indexed_ResultSelector_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x)) { seen.Add(i); } seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SelectMany_Indexed_ResultSelector_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2); IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize); Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => seen.Add(x)); seen.AssertComplete(); indices.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Skip_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); int count = 0; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2)) { seen.Add(i); count++; } Assert.Equal((DefaultSize - 1) / 2 + 1, count); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Skip_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); int count = 0; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2).ToList(), x => { seen.Add(x); count++; }); Assert.Equal((DefaultSize - 1) / 2 + 1, count); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Take_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); int count = 0; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2)) { seen.Add(i); count++; } Assert.Equal(DefaultSize / 2, count); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Take_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); int count = 0; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2).ToList(), x => { seen.Add(x); count++; }); Assert.Equal(DefaultSize / 2, count); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ToArray_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToArray(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Where_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Where_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Where_Indexed_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2); foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => x < DefaultStart + DefaultSize / 2)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Where_Indexed_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => x < DefaultStart + DefaultSize / 2).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Zip_Unordered(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item) .Zip(operation.Item(0, DefaultSize, source.Item), (x, y) => x); foreach (int i in query) { seen.Add(i); } seen.AssertComplete(); } [Theory] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Zip_Unordered_NotPipelined(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); ParallelQuery<int> query = operation.Item(0, DefaultSize, source.Item) .Zip(operation.Item(DefaultStart, DefaultSize, source.Item), (x, y) => y); Assert.All(query.ToList(), x => seen.Add(x)); seen.AssertComplete(); } } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; namespace BusinessObjects.MdPlaces { [Serializable] public partial class cMDPlaces_Enums_Geo_Country: CoreBusinessClass<cMDPlaces_Enums_Geo_Country> { #region Business Methods public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.String > nameProperty = RegisterProperty<System.String>(p => p.Name, string.Empty); [System.ComponentModel.DataAnnotations.StringLength(100, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String Name { get { return GetProperty(nameProperty); } set { SetProperty(nameProperty, value.Trim()); } } private static readonly PropertyInfo< System.String > labelProperty = RegisterProperty<System.String>(p => p.Label, string.Empty); [System.ComponentModel.DataAnnotations.StringLength(5, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String Label { get { return GetProperty(labelProperty); } set { SetProperty(labelProperty, value.Trim()); } } private static readonly PropertyInfo< System.Int32? > languageIdProperty = RegisterProperty<System.Int32?>(p => p.LanguageId, string.Empty,(System.Int32?)null); public System.Int32? LanguageId { get { return GetProperty(languageIdProperty); } set { SetProperty(languageIdProperty, value); } } private static readonly PropertyInfo< System.Int32? > currencyIdProperty = RegisterProperty<System.Int32?>(p => p.CurrencyId, string.Empty,(System.Int32?)null); public System.Int32? CurrencyId { get { return GetProperty(currencyIdProperty); } set { SetProperty(currencyIdProperty, value); } } protected static readonly PropertyInfo<System.Int32?> companyUsingServiceIdProperty = RegisterProperty<System.Int32?>(p => p.CompanyUsingServiceId, string.Empty); public System.Int32? CompanyUsingServiceId { get { return GetProperty(companyUsingServiceIdProperty); } set { SetProperty(companyUsingServiceIdProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; #endregion #region Factory Methods public static cMDPlaces_Enums_Geo_Country NewMDPlaces_Enums_Geo_Country() { return DataPortal.Create<cMDPlaces_Enums_Geo_Country>(); } public static cMDPlaces_Enums_Geo_Country GetMDPlaces_Enums_Geo_Country(int uniqueId) { return DataPortal.Fetch<cMDPlaces_Enums_Geo_Country>(new SingleCriteria<cMDPlaces_Enums_Geo_Country, int>(uniqueId)); } internal static cMDPlaces_Enums_Geo_Country GetMDPlaces_Enums_Geo_Country(MDPlaces_Enums_Geo_Country data) { return DataPortal.Fetch<cMDPlaces_Enums_Geo_Country>(data); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cMDPlaces_Enums_Geo_Country, int> criteria) { using (var ctx = ObjectContextManager<MDPlacesEntities>.GetManager("MDPlacesEntities")) { var data = ctx.ObjectContext.MDPlaces_Enums_Geo_Country.First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<string>(labelProperty, data.Label); LoadProperty<int?>(languageIdProperty, data.LanguageId); LoadProperty<int?>(currencyIdProperty, data.CurrencyId); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } } private void DataPortal_Fetch(MDPlaces_Enums_Geo_Country data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<string>(labelProperty, data.Label); LoadProperty<int?>(languageIdProperty, data.LanguageId); LoadProperty<int?>(currencyIdProperty, data.CurrencyId); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); MarkAsChild(); } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<MDPlacesEntities>.GetManager("MDPlacesEntities")) { var data = new MDPlaces_Enums_Geo_Country(); data.Name = ReadProperty<string>(nameProperty); data.Label = ReadProperty<string>(labelProperty); data.LanguageId = ReadProperty<int?>(languageIdProperty); data.CurrencyId = ReadProperty<int?>(currencyIdProperty); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); ctx.ObjectContext.AddToMDPlaces_Enums_Geo_Country(data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<MDPlacesEntities>.GetManager("MDPlacesEntities")) { var data = new MDPlaces_Enums_Geo_Country(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.Name = ReadProperty<string>(nameProperty); data.Label = ReadProperty<string>(labelProperty); data.LanguageId = ReadProperty<int?>(languageIdProperty); data.CurrencyId = ReadProperty<int?>(currencyIdProperty); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); ctx.ObjectContext.SaveChanges(); } } #endregion } public partial class cMDPlaces_Enums_Geo_Country_List : BusinessListBase<cMDPlaces_Enums_Geo_Country_List, cMDPlaces_Enums_Geo_Country> { public static cMDPlaces_Enums_Geo_Country_List GetcMDPlaces_Enums_Geo_Country_List() { return DataPortal.Fetch<cMDPlaces_Enums_Geo_Country_List>(); } private void DataPortal_Fetch() { using (var ctx = ObjectContextManager<MDPlacesEntities>.GetManager("MDPlacesEntities")) { var result = ctx.ObjectContext.MDPlaces_Enums_Geo_Country; foreach (var data in result) { var obj = cMDPlaces_Enums_Geo_Country.GetMDPlaces_Enums_Geo_Country(data); this.Add(obj); } } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; using System.Text; using Amazon.Runtime; using Amazon.S3.Util; using Amazon.Util; using System.Globalization; namespace Amazon.S3.Model { /// <summary> /// Returns information about the GetObject response and response metadata. /// </summary> public partial class GetObjectResponse : StreamResponse { private string deleteMarker; private string acceptRanges; private Expiration expiration; private DateTime? restoreExpiration; private bool restoreInProgress; private DateTime? lastModified; private string eTag; private int? missingMeta; private string versionId; private DateTime? expires; private string websiteRedirectLocation; private ServerSideEncryptionMethod serverSideEncryption; private ServerSideEncryptionCustomerMethod serverSideEncryptionCustomerMethod; private string serverSideEncryptionKeyManagementServiceKeyId; private HeadersCollection headersCollection = new HeadersCollection(); private MetadataCollection metadataCollection = new MetadataCollection(); private ReplicationStatus replicationStatus; private S3StorageClass storageClass; private string bucketName; private string key; /// <summary> /// Gets and sets the BucketName property. /// </summary> public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } /// <summary> /// Gets and sets the Key property. /// </summary> public string Key { get { return this.key; } set { this.key = value; } } /// <summary> /// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker. If false, this response header does not appear in the /// response. /// /// </summary> public string DeleteMarker { get { return this.deleteMarker; } set { this.deleteMarker = value; } } // Check to see if DeleteMarker property is set internal bool IsSetDeleteMarker() { return this.deleteMarker != null; } /// <summary> /// The collection of headers for the request. /// </summary> public HeadersCollection Headers { get { if (this.headersCollection == null) this.headersCollection = new HeadersCollection(); return this.headersCollection; } } /// <summary> /// The collection of meta data for the request. /// </summary> public MetadataCollection Metadata { get { if (this.metadataCollection == null) this.metadataCollection = new MetadataCollection(); return this.metadataCollection; } } /// <summary> /// Gets and sets the AcceptRanges. /// </summary> public string AcceptRanges { get { return this.acceptRanges; } set { this.acceptRanges = value; } } // Check to see if AcceptRanges property is set internal bool IsSetAcceptRanges() { return this.acceptRanges != null; } /// <summary> /// Gets and sets the Expiration property. /// Specifies the expiration date for the object and the /// rule governing the expiration. /// Is null if expiration is not applicable. /// </summary> public Expiration Expiration { get { return this.expiration; } set { this.expiration = value; } } // Check to see if Expiration property is set internal bool IsSetExpiration() { return this.expiration != null; } /// <summary> /// Gets and sets the RestoreExpiration property. /// RestoreExpiration will be set for objects that have been restored from Amazon Glacier. /// It indiciates for those objects how long the restored object will exist. /// </summary> public DateTime? RestoreExpiration { get { return this.restoreExpiration; } set { this.restoreExpiration = value; } } /// <summary> /// Gets and sets the RestoreInProgress /// Will be true when the object is in the process of being restored from Amazon Glacier. /// </summary> public bool RestoreInProgress { get { return this.restoreInProgress; } set { this.restoreInProgress = value; } } /// <summary> /// Last modified date of the object /// /// </summary> public DateTime LastModified { get { return this.lastModified ?? default(DateTime); } set { this.lastModified = value; } } // Check to see if LastModified property is set internal bool IsSetLastModified() { return this.lastModified.HasValue; } /// <summary> /// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL /// /// </summary> public string ETag { get { return this.eTag; } set { this.eTag = value; } } // Check to see if ETag property is set internal bool IsSetETag() { return this.eTag != null; } /// <summary> /// This is set to the number of metadata entries not returned in x-amz-meta headers. This can happen if you create metadata using an API like /// SOAP that supports more flexible metadata than the REST API. For example, using SOAP, you can create metadata whose values are not legal /// HTTP headers. /// /// </summary> public int MissingMeta { get { return this.missingMeta ?? default(int); } set { this.missingMeta = value; } } // Check to see if MissingMeta property is set internal bool IsSetMissingMeta() { return this.missingMeta.HasValue; } /// <summary> /// Version of the object. /// /// </summary> public string VersionId { get { return this.versionId; } set { this.versionId = value; } } // Check to see if VersionId property is set internal bool IsSetVersionId() { return this.versionId != null; } /// <summary> /// The date and time at which the object is no longer cacheable. /// /// </summary> public DateTime Expires { get { return this.expires ?? default(DateTime); } set { this.expires = value; } } // Check to see if Expires property is set internal bool IsSetExpires() { return this.expires.HasValue; } /// <summary> /// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. /// Amazon S3 stores the value of this header in the object metadata. /// /// </summary> public string WebsiteRedirectLocation { get { return this.websiteRedirectLocation; } set { this.websiteRedirectLocation = value; } } // Check to see if WebsiteRedirectLocation property is set internal bool IsSetWebsiteRedirectLocation() { return this.websiteRedirectLocation != null; } /// <summary> /// The Server-side encryption algorithm used when storing this object in S3. /// /// </summary> public ServerSideEncryptionMethod ServerSideEncryptionMethod { get { return this.serverSideEncryption; } set { this.serverSideEncryption = value; } } // Check to see if ServerSideEncryptionMethod property is set internal bool IsSetServerSideEncryptionMethod() { return this.serverSideEncryption != null; } /// <summary> /// The class of storage used to store the object. /// /// </summary> public S3StorageClass StorageClass { get { return this.storageClass; } set { this.storageClass = value; } } // Check to see if StorageClass property is set internal bool IsSetStorageClass() { return this.storageClass != null; } /// <summary> /// The id of the AWS Key Management Service key that Amazon S3 uses to encrypt and decrypt the object. /// </summary> public string ServerSideEncryptionKeyManagementServiceKeyId { get { return this.serverSideEncryptionKeyManagementServiceKeyId; } set { this.serverSideEncryptionKeyManagementServiceKeyId = value; } } /// <summary> /// Checks if ServerSideEncryptionKeyManagementServiceKeyId property is set. /// </summary> /// <returns>true if ServerSideEncryptionKeyManagementServiceKeyId property is set.</returns> internal bool IsSetServerSideEncryptionKeyManagementServiceKeyId() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionKeyManagementServiceKeyId); } /// <summary> /// The status of the replication job associated with this source object. /// </summary> public ReplicationStatus ReplicationStatus { get { return this.replicationStatus; } set { this.replicationStatus = value; } } /// <summary> /// Checks if ReplicationStatus property is set. /// </summary> /// <returns>true if ReplicationStatus property is set.</returns> internal bool IsSetReplicationStatus() { return ReplicationStatus != null; } #if BCL /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> public void WriteResponseStreamToFile(string filePath) { WriteResponseStreamToFile(filePath, false); } /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> /// <param name="append">Whether or not to append to the file if it exists</param> public void WriteResponseStreamToFile(string filePath, bool append) { CreateDirectory(filePath); Stream downloadStream = CreateDownloadStream(filePath, append); using (downloadStream) { long current = 0; byte[] buffer = new byte[S3Constants.DefaultBufferSize]; int bytesRead = 0; long totalIncrementTransferred = 0; while ((bytesRead = this.ResponseStream.Read(buffer, 0, buffer.Length)) > 0) { downloadStream.Write(buffer, 0, bytesRead); current += bytesRead; totalIncrementTransferred += bytesRead; if (totalIncrementTransferred >= AWSSDKUtils.DefaultProgressUpdateInterval || current == this.ContentLength) { this.OnRaiseProgressEvent(filePath, totalIncrementTransferred, current, this.ContentLength); totalIncrementTransferred = 0; } } ValidateWrittenStreamSize(current); } } private static Stream CreateDownloadStream(string filePath, bool append) { Stream downloadStream; if (append && File.Exists(filePath)) downloadStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read, S3Constants.DefaultBufferSize); else downloadStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, S3Constants.DefaultBufferSize); return downloadStream; } private static void CreateDirectory(string filePath) { // Make sure the directory exists to write too. FileInfo fi = new FileInfo(filePath); Directory.CreateDirectory(fi.DirectoryName); } #endif #region Progress Event /// <summary> /// The event for Write Object progress notifications. All /// subscribers will be notified when a new progress /// event is raised. /// </summary> /// <remarks> /// Subscribe to this event if you want to receive /// put object progress notifications. Here is how:<br /> /// 1. Define a method with a signature similar to this one: /// <code> /// private void displayProgress(object sender, WriteObjectProgressArgs args) /// { /// Console.WriteLine(args); /// } /// </code> /// 2. Add this method to the Put Object Progress Event delegate's invocation list /// <code> /// GetObjectResponse response = s3Client.GetObject(request); /// response.WriteObjectProgressEvent += displayProgress; /// </code> /// </remarks> public event EventHandler<WriteObjectProgressArgs> WriteObjectProgressEvent; #endregion /// <summary> /// This method is called by a producer of write object progress /// notifications. When called, all the subscribers in the /// invocation list will be called sequentially. /// </summary> /// <param name="file">The file being written.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal void OnRaiseProgressEvent(string file, long incrementTransferred, long transferred, long total) { AWSSDKUtils.InvokeInBackground(WriteObjectProgressEvent, new WriteObjectProgressArgs(this.BucketName, this.Key, file, this.VersionId, incrementTransferred, transferred, total), this); } /// <summary> /// The Server-side encryption algorithm to be used with the customer provided key. /// /// </summary> public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod { get { if (this.serverSideEncryptionCustomerMethod == null) return ServerSideEncryptionCustomerMethod.None; return this.serverSideEncryptionCustomerMethod; } set { this.serverSideEncryptionCustomerMethod = value; } } private void ValidateWrittenStreamSize(long bytesWritten) { #if !PCL // Check if response stream or it's base stream is a AESDecryptionStream var stream = Runtime.Internal.Util.WrapperStream.SearchWrappedStream(this.ResponseStream, (s => s is Runtime.Internal.Util.DecryptStream)); // Don't validate length if response is an encrypted object. if (stream!=null) return; #endif if (bytesWritten != this.ContentLength) { string amzId2; this.ResponseMetadata.Metadata.TryGetValue(HeaderKeys.XAmzId2Header, out amzId2); amzId2 = amzId2 ?? string.Empty; var message = string.Format(CultureInfo.InvariantCulture, "The total bytes read {0} from response stream is not equal to the Content-Length {1} for the object {2} in bucket {3}."+ " Request ID = {4} , AmzId2 = {5}.", bytesWritten, this.ContentLength, this.Key, this.BucketName, this.ResponseMetadata.RequestId, amzId2); throw new StreamSizeMismatchException(message, this.ContentLength, bytesWritten, this.ResponseMetadata.RequestId, amzId2); } } } /// <summary> /// Encapsulates the information needed to provide /// download progress for the Write Object Event. /// </summary> public class WriteObjectProgressArgs : TransferProgressArgs { /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="bucketName">The bucket name for the S3 object being written.</param> /// <param name="key">The object key for the S3 object being written.</param> /// <param name="versionId">The version-id of the S3 object.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal WriteObjectProgressArgs(string bucketName, string key, string versionId, long incrementTransferred, long transferred, long total) : base(incrementTransferred, transferred, total) { this.BucketName = bucketName; this.Key = key; this.VersionId = versionId; } /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="bucketName">The bucket name for the S3 object being written.</param> /// <param name="key">The object key for the S3 object being written.</param> /// <param name="filePath">The file for the S3 object being written.</param> /// <param name="versionId">The version-id of the S3 object.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal WriteObjectProgressArgs(string bucketName, string key, string filePath, string versionId, long incrementTransferred, long transferred, long total) : base(incrementTransferred, transferred, total) { this.BucketName = bucketName; this.Key = key; this.VersionId = versionId; this.FilePath = filePath; } /// <summary> /// Gets the bucket name for the S3 object being written. /// </summary> public string BucketName { get; private set; } /// <summary> /// Gets the object key for the S3 object being written. /// </summary> public string Key { get; private set; } /// <summary> /// Gets the version-id of the S3 object. /// </summary> public string VersionId { get; private set; } /// <summary> /// The file for the S3 object being written. /// </summary> public string FilePath { get; private set; } } }
using System; using HalconDotNet; namespace HDisplayControl.ViewROI { /// <summary> /// This class demonstrates one of the possible implementations for a /// linear ROI. ROILine inherits from the base class ROI and /// implements (besides other auxiliary methods) all virtual methods /// defined in ROI.cs. /// </summary> public class ROILine : ROI { private double row1, col1; // first end point of line private double row2, col2; // second end point of line private double midR, midC; // midPoint of line private HXLDCont arrowHandleXLD; public ROILine() { NumHandles = 3; // two end points of line activeHandleIdx = 2; arrowHandleXLD = new HXLDCont(); arrowHandleXLD.GenEmptyObj(); } /// <summary>Creates a new ROI instance at the mouse position.</summary> public override void createROI(double midX, double midY) { midR = midY; midC = midX; row1 = midR; col1 = midC - 50; row2 = midR; col2 = midC + 50; updateArrowHandle(); } /// <summary>Paints the ROI into the supplied window.</summary> public override void draw(HalconDotNet.HWindow window) { window.DispLine(row1, col1, row2, col2); window.DispRectangle2(row1, col1, 0, 5, 5); window.DispObj(arrowHandleXLD); //window.DispRectangle2( row2, col2, 0, 5, 5); window.DispRectangle2(midR, midC, 0, 5, 5); } /// <summary> /// Returns the distance of the ROI handle being /// closest to the image point(x,y). /// </summary> public override double distToClosestHandle(double x, double y) { double max = 10000; double [] val = new double[NumHandles]; val[0] = HMisc.DistancePp(y, x, row1, col1); // upper left val[1] = HMisc.DistancePp(y, x, row2, col2); // upper right val[2] = HMisc.DistancePp(y, x, midR, midC); // midpoint for (int i=0; i < NumHandles; i++) { if (val[i] < max) { max = val[i]; activeHandleIdx = i; } }// end of for return val[activeHandleIdx]; } /// <summary> /// Paints the active handle of the ROI object into the supplied window. /// </summary> public override void displayActive(HalconDotNet.HWindow window) { switch (activeHandleIdx) { case 0: window.DispRectangle2(row1, col1, 0, 5, 5); break; case 1: window.DispObj(arrowHandleXLD); //window.DispRectangle2(row2, col2, 0, 5, 5); break; case 2: window.DispRectangle2(midR, midC, 0, 5, 5); break; } } /// <summary>Gets the HALCON region described by the ROI.</summary> public override HRegion getRegion() { HRegion region = new HRegion(); region.GenRegionLine(row1, col1, row2, col2); return region; } public override double getDistanceFromStartPoint(double row, double col) { double distance = HMisc.DistancePp(row, col, row1, col1); return distance; } /// <summary> /// Gets the model information described by /// the ROI. /// </summary> public override HTuple getModelData() { return new HTuple(new double[] { row1, col1, row2, col2 }); } /// <summary> /// Recalculates the shape of the ROI. Translation is /// performed at the active handle of the ROI object /// for the image coordinate (x,y). /// </summary> public override void moveByHandle(double newX, double newY) { double lenR, lenC; switch (activeHandleIdx) { case 0: // first end point row1 = newY; col1 = newX; midR = (row1 + row2) / 2; midC = (col1 + col2) / 2; break; case 1: // last end point row2 = newY; col2 = newX; midR = (row1 + row2) / 2; midC = (col1 + col2) / 2; break; case 2: // midpoint lenR = row1 - midR; lenC = col1 - midC; midR = newY; midC = newX; row1 = midR + lenR; col1 = midC + lenC; row2 = midR - lenR; col2 = midC - lenC; break; } updateArrowHandle(); } /// <summary> Auxiliary method </summary> private void updateArrowHandle() { double length,dr,dc, halfHW; double rrow1, ccol1,rowP1, colP1, rowP2, colP2; double headLength = 15; double headWidth = 15; arrowHandleXLD.Dispose(); arrowHandleXLD.GenEmptyObj(); rrow1 = row1 + (row2 - row1) * 0.8; ccol1 = col1 + (col2 - col1) * 0.8; length = HMisc.DistancePp(rrow1, ccol1, row2, col2); if (length == 0) length = -1; dr = (row2 - rrow1) / length; dc = (col2 - ccol1) / length; halfHW = headWidth / 2.0; rowP1 = rrow1 + (length - headLength) * dr + halfHW * dc; rowP2 = rrow1 + (length - headLength) * dr - halfHW * dc; colP1 = ccol1 + (length - headLength) * dc - halfHW * dr; colP2 = ccol1 + (length - headLength) * dc + halfHW * dr; if (length == -1) arrowHandleXLD.GenContourPolygonXld(rrow1, ccol1); else arrowHandleXLD.GenContourPolygonXld(new HTuple(new double[] { rrow1, row2, rowP1, row2, rowP2, row2 }), new HTuple(new double[] { ccol1, col2, colP1, col2, colP2, col2 })); } }//end of class }//end of namespace
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Utilities; using Roslyn.Utilities; using ShellInterop = Microsoft.VisualStudio.Shell.Interop; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; using VsThreading = Microsoft.VisualStudio.Threading; using Document = Microsoft.CodeAnalysis.Document; namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue { internal sealed class VsENCRebuildableProjectImpl { private readonly AbstractProject _vsProject; // number of projects that are in the debug state: private static int s_debugStateProjectCount; // number of projects that are in the break state: private static int s_breakStateProjectCount; // projects that entered the break state: private static readonly List<KeyValuePair<ProjectId, ProjectReadOnlyReason>> s_breakStateEnteredProjects = new List<KeyValuePair<ProjectId, ProjectReadOnlyReason>>(); // active statements of projects that entered the break state: private static readonly List<VsActiveStatement> s_pendingActiveStatements = new List<VsActiveStatement>(); private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker; internal static readonly TraceLog log = new TraceLog(2048, "EnC"); private static Solution s_breakStateEntrySolution; private static EncDebuggingSessionInfo s_encDebuggingSessionInfo; private readonly IEditAndContinueWorkspaceService _encService; private readonly IActiveStatementTrackingService _trackingService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider; private readonly IDebugEncNotify _debugEncNotify; private readonly INotificationService _notifications; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; #region Per Project State private bool _changesApplied; // maps VS Active Statement Id, which is unique within this project, to our id private Dictionary<uint, ActiveStatementId> _activeStatementIds; private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; private HashSet<uint> _activeMethods; private List<VsExceptionRegion> _exceptionRegions; private EmitBaseline _committedBaseline; private EmitBaseline _pendingBaseline; private Project _projectBeingEmitted; private ImmutableArray<DocumentId> _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; /// <summary> /// Initialized when the project switches to debug state. /// Null if the project has no output file or we can't read the MVID. /// </summary> private ModuleMetadata _metadata; private ISymUnmanagedReader3 _pdbReader; private IntPtr _pdbReaderObjAsStream; #endregion private bool IsDebuggable { get { return _metadata != null; } } internal VsENCRebuildableProjectImpl(AbstractProject project) { _vsProject = project; _encService = _vsProject.Workspace.Services.GetService<IEditAndContinueWorkspaceService>(); _trackingService = _vsProject.Workspace.Services.GetService<IActiveStatementTrackingService>(); _notifications = _vsProject.Workspace.Services.GetService<INotificationService>(); _debugEncNotify = (IDebugEncNotify)project.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); var componentModel = (IComponentModel)project.ServiceProvider.GetService(typeof(SComponentModel)); _diagnosticProvider = componentModel.GetService<EditAndContinueDiagnosticUpdateSource>(); _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>(); Debug.Assert(_encService != null); Debug.Assert(_trackingService != null); Debug.Assert(_diagnosticProvider != null); Debug.Assert(_editorAdaptersFactoryService != null); } // called from an edit filter if an edit of a read-only buffer is attempted: internal bool OnEdit(DocumentId documentId) { SessionReadOnlyReason sessionReason; ProjectReadOnlyReason projectReason; if (_encService.IsProjectReadOnly(documentId.ProjectId, out sessionReason, out projectReason)) { OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason); return true; } return false; } private void OnReadOnlyDocumentEditAttempt( DocumentId documentId, SessionReadOnlyReason sessionReason, ProjectReadOnlyReason projectReason) { if (sessionReason == SessionReadOnlyReason.StoppedAtException) { _debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState(); return; } var visualStudioWorkspace = _vsProject.Workspace as VisualStudioWorkspaceImpl; var hostProject = visualStudioWorkspace?.GetHostProject(documentId.ProjectId) as AbstractRoslynProject; if (hostProject?.EditAndContinueImplOpt?._metadata != null) { _debugEncNotify.NotifyEncEditDisallowedByProject(hostProject.Hierarchy); return; } // NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586). string message; if (sessionReason == SessionReadOnlyReason.Running) { message = "Changes are not allowed while code is running."; } else { Debug.Assert(sessionReason == SessionReadOnlyReason.None); switch (projectReason) { case ProjectReadOnlyReason.MetadataNotAvailable: message = "Changes are not allowed if the project wasn't built when debugging started."; break; case ProjectReadOnlyReason.NotLoaded: message = "Changes are not allowed if the assembly has not been loaded."; break; default: throw ExceptionUtilities.UnexpectedValue(projectReason); } } _notifications.SendNotification(message, title: FeaturesResources.EditAndContinue, severity: NotificationSeverity.Error); } /// <summary> /// Since we can't await asynchronous operations we need to wait for them to complete. /// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to /// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext /// that doesn't pump messages. We need to make sure though that the async methods we wait for /// don't dispatch to foreground thread, otherwise we would end up in a deadlock. /// </summary> private static VsThreading.SpecializedSyncContext NonReentrantContext { get { return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default); } } public bool HasCustomMetadataEmitter() { return true; } /// <summary> /// Invoked when the debugger transitions from Design mode to Run mode or Break mode. /// </summary> public int StartDebuggingPE() { try { log.Write("Enter Debug Mode: project '{0}'", _vsProject.DisplayName); // EnC service is global (per solution), but the debugger calls this for each project. // Avoid starting the debug session if it has already been started. if (_encService.DebuggingSession == null) { Debug.Assert(s_debugStateProjectCount == 0); Debug.Assert(s_breakStateProjectCount == 0); Debug.Assert(s_breakStateEnteredProjects.Count == 0); _encService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _encService.StartDebuggingSession(_vsProject.Workspace.CurrentSolution); s_encDebuggingSessionInfo = new EncDebuggingSessionInfo(); s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_encService, _editorAdaptersFactoryService, _vsProject); } string outputPath = _vsProject.TryGetObjOutputPath(); // The project doesn't produce a debuggable binary or we can't read it. // Continue on since the debugger ignores HResults and we need to handle subsequent calls. if (outputPath != null) { try { InjectFault_MvidRead(); _metadata = ModuleMetadata.CreateFromStream(new FileStream(outputPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)); _metadata.GetModuleVersionId(); } catch (FileNotFoundException) { // If the project isn't referenced by the project being debugged it might not be built. // In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state. log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _vsProject.DisplayName, outputPath); _metadata = null; } catch (Exception e) { log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _vsProject.DisplayName, outputPath, e.Message); _metadata = null; var descriptor = new DiagnosticDescriptor("Metadata", "Metadata", ServicesVSResources.ErrorWhileReading, DiagnosticCategory.EditAndContinue, DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue); _diagnosticProvider.ReportDiagnostics( new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId), _encService.DebuggingSession.InitialSolution, _vsProject.Id, new[] { Diagnostic.Create(descriptor, Location.None, outputPath, e.Message) }); } } else { log.Write("StartDebuggingPE: project has no output path '{0}'", _vsProject.DisplayName); _metadata = null; } if (_metadata != null) { // The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID. // However a project that's initially not loaded (but it might be in future) enters // both the debug and break states. s_debugStateProjectCount++; } _activeMethods = new HashSet<uint>(); _exceptionRegions = new List<VsExceptionRegion>(); _activeStatementIds = new Dictionary<uint, ActiveStatementId>(); // The HResult is ignored by the debugger. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } public int StopDebuggingPE() { try { log.Write("Exit Debug Mode: project '{0}'", _vsProject.DisplayName); Debug.Assert(s_breakStateEnteredProjects.Count == 0); // Clear the solution stored while projects were entering break mode. // It should be cleared as soon as all tracked projects enter the break mode // but if the entering break mode fails for some projects we should avoid leaking the solution. Debug.Assert(s_breakStateEntrySolution == null); s_breakStateEntrySolution = null; // EnC service is global (per solution), but the debugger calls this for each project. // Avoid ending the debug session if it has already been ended. if (_encService.DebuggingSession != null) { _encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); _encService.EndDebuggingSession(); LogEncSession(); s_encDebuggingSessionInfo = null; s_readOnlyDocumentTracker.Dispose(); s_readOnlyDocumentTracker = null; } if (_metadata != null) { _metadata.Dispose(); _metadata = null; s_debugStateProjectCount--; } else { // an error might have been reported: var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId); _diagnosticProvider.ClearDiagnostics(errorId, _vsProject.Workspace.CurrentSolution, _vsProject.Id, documentIdOpt: null); } _activeMethods = null; _exceptionRegions = null; _committedBaseline = null; _activeStatementIds = null; Debug.Assert((_pdbReaderObjAsStream == IntPtr.Zero) || (_pdbReader == null)); if (_pdbReader != null) { Marshal.ReleaseComObject(_pdbReader); _pdbReader = null; } // The HResult is ignored by the debugger. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static void LogEncSession() { var sessionId = DebugLogMessage.GetNextId(); Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo)); foreach (var editSession in s_encDebuggingSessionInfo.EditSessions) { var editSessionId = DebugLogMessage.GetNextId(); Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession)); if (editSession.EmitDeltaErrorIds != null) { foreach (var error in editSession.EmitDeltaErrorIds) { Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error)); } } foreach (var rudeEdit in editSession.RudeEdits) { Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits)); } } } /// <summary> /// Get MVID and file name of the project's output file. /// </summary> /// <remarks> /// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project. /// The path seems to be unused. /// /// The output file path might be different from the path of the module loaded into the process. /// For example, the binary produced by the C# compiler is stores in obj directory, /// and then copied to bin directory from which it is loaded to the debuggee. /// /// The binary produced by the compiler can also be rewritten by post-processing tools. /// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session /// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though. /// </remarks> public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName) { Debug.Assert(_encService.DebuggingSession != null); if (_metadata == null) { return VSConstants.E_FAIL; } if (pMVID != null && pMVID.Length != 0) { pMVID[0] = _metadata.GetModuleVersionId(); } if (pbstrPEName != null && pbstrPEName.Length != 0) { var outputPath = _vsProject.TryGetObjOutputPath(); Debug.Assert(outputPath != null); pbstrPEName[0] = Path.GetFileName(outputPath); } return VSConstants.S_OK; } /// <summary> /// Called by the debugger when entering a Break state. /// </summary> /// <param name="encBreakReason">Reason for transition to Break state.</param> /// <param name="pActiveStatements">Statements active when the debuggee is stopped.</param> /// <param name="cActiveStatements">Length of <paramref name="pActiveStatements"/>.</param> public int EnterBreakStateOnPE(Interop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements) { try { using (NonReentrantContext) { log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _vsProject.DisplayName, pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : ""); Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0)); Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount); Debug.Assert(s_breakStateProjectCount > 0 || _exceptionRegions.Count == 0); Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count); Debug.Assert(IsDebuggable); if (s_breakStateEntrySolution == null) { _encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); s_breakStateEntrySolution = _vsProject.Workspace.CurrentSolution; // TODO: This is a workaround for a debugger bug in which not all projects exit the break state. // Reset the project count. s_breakStateProjectCount = 0; } ProjectReadOnlyReason state; if (pActiveStatements != null) { AddActiveStatements(s_breakStateEntrySolution, pActiveStatements); state = ProjectReadOnlyReason.None; } else { // unfortunately the debugger doesn't provide details: state = ProjectReadOnlyReason.NotLoaded; } // If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding // to the project in the debuggee. We won't include such projects in the edit session. s_breakStateEnteredProjects.Add(KeyValuePair.Create(_vsProject.Id, state)); s_breakStateProjectCount++; // EnC service is global, but the debugger calls this for each project. // Avoid starting the edit session until all projects enter break state. if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) { Debug.Assert(_encService.EditSession == null); Debug.Assert(s_pendingActiveStatements.TrueForAll(s => s.Owner._activeStatementIds.Count == 0)); var byDocument = new Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>>(); // note: fills in activeStatementIds of projects that own the active statements: GroupActiveStatements(s_pendingActiveStatements, byDocument); // When stopped at exception: All documents are read-only, but the files might be changed outside of VS. // So we start an edit session as usual and report a rude edit for all changes we see. bool stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION; var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects); _encService.StartEditSession(s_breakStateEntrySolution, byDocument, projectStates, stoppedAtException); _trackingService.StartTracking(_encService.EditSession); s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); // When tracking is started the tagger is notified and the active statements are highlighted. // Add the handler that notifies the debugger *after* that initial tagger notification, // so that it's not triggered unless an actual change in leaf AS occurs. _trackingService.TrackingSpansChanged += TrackingSpansChanged; } } // The debugger ignores the result. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } finally { // TODO: This is a workaround for a debugger bug. // Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception. if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) { // we don't need these anymore: s_pendingActiveStatements.Clear(); s_breakStateEnteredProjects.Clear(); s_breakStateEntrySolution = null; } } } private void TrackingSpansChanged(bool leafChanged) { //log.Write("Tracking spans changed: {0}", leafChanged); //if (leafChanged) //{ // // fire and forget: // Application.Current.Dispatcher.InvokeAsync(() => // { // log.Write("Notifying debugger of active statement change."); // var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); // debugNotify.NotifyEncUpdateCurrentStatement(); // }); //} } private struct VsActiveStatement { public readonly DocumentId DocumentId; public readonly uint StatementId; public readonly ActiveStatementSpan Span; public readonly VsENCRebuildableProjectImpl Owner; public VsActiveStatement(VsENCRebuildableProjectImpl owner, uint statementId, DocumentId documentId, ActiveStatementSpan span) { this.Owner = owner; this.StatementId = statementId; this.DocumentId = documentId; this.Span = span; } } private struct VsExceptionRegion { public readonly uint ActiveStatementId; public readonly int Ordinal; public readonly uint MethodToken; public readonly LinePositionSpan Span; public VsExceptionRegion(uint activeStatementId, int ordinal, uint methodToken, LinePositionSpan span) { this.ActiveStatementId = activeStatementId; this.Span = span; this.MethodToken = methodToken; this.Ordinal = ordinal; } } // See InternalApis\vsl\inc\encbuild.idl private const int TEXT_POSITION_ACTIVE_STATEMENT = 1; private void AddActiveStatements(Solution solution, ShellInterop.ENC_ACTIVE_STATEMENT[] vsActiveStatements) { Debug.Assert(_activeMethods.Count == 0); Debug.Assert(_exceptionRegions.Count == 0); foreach (var vsActiveStatement in vsActiveStatements) { log.DebugWrite("+AS[{0}]: {1} {2} {3} {4} '{5}'", vsActiveStatement.id, vsActiveStatement.tsPosition.iStartLine, vsActiveStatement.tsPosition.iStartIndex, vsActiveStatement.tsPosition.iEndLine, vsActiveStatement.tsPosition.iEndIndex, vsActiveStatement.filename); // TODO (tomat): // Active statement is in user hidden code. The only information that we have from the debugger // is the method token. We don't need to track the statement (it's not in user code anyways), // but we should probably track the list of such methods in order to preserve their local variables. // Not sure what's exactly the scenario here, perhaps modifying async method/iterator? // Dev12 just ignores these. if (vsActiveStatement.posType != TEXT_POSITION_ACTIVE_STATEMENT) { continue; } var flags = (ActiveStatementFlags)vsActiveStatement.ASINFO; // Finds a document id in the solution with the specified file path. DocumentId documentId = solution.GetDocumentIdsWithFilePath(vsActiveStatement.filename) .Where(dId => dId.ProjectId == _vsProject.Id).SingleOrDefault(); if (documentId != null) { var document = solution.GetDocument(documentId); Debug.Assert(document != null); SourceText source = document.GetTextAsync(default(CancellationToken)).Result; LinePositionSpan lineSpan = vsActiveStatement.tsPosition.ToLinePositionSpan(); // If the PDB is out of sync with the source we might get bad spans. var sourceLines = source.Lines; if (lineSpan.End.Line >= sourceLines.Count || sourceLines.GetPosition(lineSpan.End) > sourceLines[sourceLines.Count - 1].EndIncludingLineBreak) { log.Write("AS out of bounds (line count is {0})", source.Lines.Count); continue; } SyntaxNode syntaxRoot = document.GetSyntaxRootAsync(default(CancellationToken)).Result; var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>(); s_pendingActiveStatements.Add(new VsActiveStatement( this, vsActiveStatement.id, document.Id, new ActiveStatementSpan(flags, lineSpan))); bool isLeaf = (flags & ActiveStatementFlags.LeafFrame) != 0; var ehRegions = analyzer.GetExceptionRegions(source, syntaxRoot, lineSpan, isLeaf); for (int i = 0; i < ehRegions.Length; i++) { _exceptionRegions.Add(new VsExceptionRegion( vsActiveStatement.id, i, vsActiveStatement.methodToken, ehRegions[i])); } } _activeMethods.Add(vsActiveStatement.methodToken); } } private static void GroupActiveStatements( IEnumerable<VsActiveStatement> activeStatements, Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>> byDocument) { var spans = new List<ActiveStatementSpan>(); foreach (var grouping in activeStatements.GroupBy(s => s.DocumentId)) { var documentId = grouping.Key; foreach (var activeStatement in grouping.OrderBy(s => s.Span.Span.Start)) { int ordinal = spans.Count; // register vsid with the project that owns the active statement: activeStatement.Owner._activeStatementIds.Add(activeStatement.StatementId, new ActiveStatementId(documentId, ordinal)); spans.Add(activeStatement.Span); } byDocument.Add(documentId, spans.AsImmutable()); spans.Clear(); } } /// <summary> /// Returns the number of exception regions around current active statements. /// This is called when the project is entering a break right after /// <see cref="EnterBreakStateOnPE"/> and prior to <see cref="GetExceptionSpans"/>. /// </summary> /// <remarks> /// Called by EnC manager. /// </remarks> public int GetExceptionSpanCount(out uint pcExceptionSpan) { pcExceptionSpan = (uint)_exceptionRegions.Count; return VSConstants.S_OK; } /// <summary> /// Returns information about exception handlers in the source. /// </summary> /// <remarks> /// Called by EnC manager. /// </remarks> public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched) { Debug.Assert(celt == rgelt.Length); Debug.Assert(celt == _exceptionRegions.Count); for (int i = 0; i < _exceptionRegions.Count; i++) { rgelt[i] = new ShellInterop.ENC_EXCEPTION_SPAN() { id = (uint)i, methodToken = _exceptionRegions[i].MethodToken, tsPosition = _exceptionRegions[i].Span.ToVsTextSpan() }; } pceltFetched = celt; return VSConstants.S_OK; } /// <summary> /// Called by the debugger whenever it needs to determine a position of an active statement. /// E.g. the user clicks on a frame in a call stack. /// </summary> /// <remarks> /// Called when applying change, when setting current IP, a notification is received from /// <see cref="IDebugEncNotify.NotifyEncUpdateCurrentStatement"/>, etc. /// In addition this API is exposed on IDebugENC2 COM interface so it can be used anytime by other components. /// </remarks> public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition) { try { using (NonReentrantContext) { Debug.Assert(IsDebuggable); var session = _encService.EditSession; var ids = _activeStatementIds; // Can be called anytime, even outside of an edit/debug session. // We might not have an active statement available if PDB got out of sync with the source. ActiveStatementId id; if (session == null || ids == null || !ids.TryGetValue(vsId, out id)) { log.Write("GetCurrentActiveStatementPosition failed for AS {0}.", vsId); return VSConstants.E_FAIL; } Document document = _vsProject.Workspace.CurrentSolution.GetDocument(id.DocumentId); SourceText text = document.GetTextAsync(default(CancellationToken)).Result; // Try to get spans from the tracking service first. // We might get an imprecise result if the document analysis hasn't been finished yet and // the active statement has structurally changed, but that's ok. The user won't see an updated tag // for the statement until the analysis finishes anyways. TextSpan span; LinePositionSpan lineSpan; if (_trackingService.TryGetSpan(id, text, out span) && span.Length > 0) { lineSpan = text.Lines.GetLinePositionSpan(span); } else { var activeSpans = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)).ActiveStatements; if (activeSpans.IsDefault) { // The document has syntax errors and the tracking span is gone. log.Write("Position not available for AS {0} due to syntax errors", vsId); return VSConstants.E_FAIL; } lineSpan = activeSpans[id.Ordinal]; } ptsNewPosition[0] = lineSpan.ToVsTextSpan(); log.DebugWrite("AS position: {0} {1} {2}", vsId, lineSpan, session.BaseActiveStatements[id.DocumentId][id.Ordinal].Flags); return VSConstants.S_OK; } } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } /// <summary> /// Returns the state of the changes made to the source. /// The EnC manager calls this to determine whether there are any changes to the source /// and if so whether there are any rude edits. /// </summary> public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState) { try { using (NonReentrantContext) { Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1); // GetENCBuildState is called outside of edit session (at least) in following cases: // 1) when the debugger is determining whether a source file checksum matches the one in PDB. // 2) when the debugger is setting the next statement and a change is pending // See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange): // // pENC2->ExitBreakState(); // >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true); // pENC2->EnterBreakState(m_pSession, GetEncBreakReason()); // // The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur. if (_changesApplied || _encService.EditSession == null) { _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; } else { // Fetch the latest snapshot of the project and get an analysis summary for any changes // made since the break mode was entered. var currentProject = _vsProject.Workspace.CurrentSolution.GetProject(_vsProject.Id); if (currentProject == null) { // If the project has yet to be loaded into the solution (which may be the case, // since they are loaded on-demand), then it stands to reason that it has not yet // been modified. // TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary. _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; log.Write($"Project '{_vsProject.DisplayName}' has not yet been loaded into the solution"); } else { _projectBeingEmitted = currentProject; _lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted); } _encService.EditSession.LogBuildState(_lastEditSessionSummary); } switch (_lastEditSessionSummary) { case ProjectAnalysisSummary.NoChanges: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED; break; case ProjectAnalysisSummary.CompilationErrors: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS; break; case ProjectAnalysisSummary.RudeEdits: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS; break; case ProjectAnalysisSummary.ValidChanges: case ProjectAnalysisSummary.ValidInsignificantChanges: // The debugger doesn't distinguish between these two. pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY; break; default: throw ExceptionUtilities.Unreachable; } log.Write("EnC state of '{0}' queried: {1}{2}", _vsProject.DisplayName, pENCBuildState[0], _encService.EditSession != null ? "" : " (no session)"); return VSConstants.S_OK; } } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project) { if (!IsDebuggable) { return ProjectAnalysisSummary.NoChanges; } var cancellationToken = default(CancellationToken); return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result; } public int ExitBreakStateOnPE() { try { using (NonReentrantContext) { // The debugger calls Exit without previously calling Enter if the project's MVID isn't available. if (!IsDebuggable) { return VSConstants.S_OK; } log.Write("Exit Break Mode: project '{0}'", _vsProject.DisplayName); // EnC service is global, but the debugger calls this for each project. // Avoid ending the edit session if it has already been ended. if (_encService.EditSession != null) { Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount); _encService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); _encService.EditSession.LogEditSession(s_encDebuggingSessionInfo); _encService.EndEditSession(); _trackingService.EndTracking(); s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); _trackingService.TrackingSpansChanged -= TrackingSpansChanged; } _exceptionRegions.Clear(); _activeMethods.Clear(); _activeStatementIds.Clear(); s_breakStateProjectCount--; Debug.Assert(s_breakStateProjectCount >= 0); _changesApplied = false; _diagnosticProvider.ClearDiagnostics( new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId), _vsProject.Workspace.CurrentSolution, _vsProject.Id, _documentsWithEmitError); _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; } // HResult ignored by the debugger return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } public unsafe int BuildForEnc(object pUpdatePE) { try { log.Write("Applying changes to {0}", _vsProject.DisplayName); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); // Non-debuggable project has no changes. Debug.Assert(IsDebuggable); if (_changesApplied) { log.Write("Changes already applied to {0}, can't apply again", _vsProject.DisplayName); throw ExceptionUtilities.Unreachable; } // The debugger always calls GetENCBuildState right before BuildForEnc. Debug.Assert(_projectBeingEmitted != null); Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted)); // The debugger should have called GetENCBuildState before calling BuildForEnc. // Unfortunately, there is no way how to tell the debugger that the changes were not significant, // so we'll to emit an empty delta. See bug 839558. Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges || _lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges); var updater = (IDebugUpdateInMemoryPE2)pUpdatePE; if (_committedBaseline == null) { var hr = MarshalPdbReader(updater, out _pdbReaderObjAsStream); if (hr != VSConstants.S_OK) { return hr; } _committedBaseline = EmitBaseline.CreateInitialBaseline(_metadata, GetBaselineEncDebugInfo); } // ISymUnmanagedReader can only be accessed from an MTA thread, // so dispatch it to one of thread pool threads, which are MTA. var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default); Deltas delta; using (NonReentrantContext) { delta = emitTask.Result; if (delta == null) { // Non-fatal Watson has already been reported by the emit task return VSConstants.E_FAIL; } } var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId); // Clear diagnostics, in case the project was built before and failed due to errors. _diagnosticProvider.ClearDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, _documentsWithEmitError); if (!delta.EmitResult.Success) { var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error); _documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, errors); _encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id)); return VSConstants.E_FAIL; } _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; SetFileUpdates(updater, delta.LineEdits); updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length); updater.SetDeltaPdb(SymUnmanagedStreamFactory.CreateStream(delta.Pdb.Stream)); updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length); updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length); _pendingBaseline = delta.EmitResult.Baseline; #if DEBUG fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0]) { var reader = new System.Reflection.Metadata.MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length); var moduleDef = reader.GetModuleDefinition(); log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}", moduleDef.Generation, reader.GetGuid(moduleDef.Mvid), reader.GetGuid(moduleDef.BaseGenerationId), reader.GetGuid(moduleDef.GenerationId)); } #endif return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private unsafe void SetFileUpdates( IDebugUpdateInMemoryPE2 updater, List<KeyValuePair<DocumentId, ImmutableArray<LineChange>>> edits) { int totalEditCount = edits.Sum(e => e.Value.Length); if (totalEditCount == 0) { return; } var lineUpdates = new LINEUPDATE[totalEditCount]; fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates) { int index = 0; var fileUpdates = new FILEUPDATE[edits.Count]; for (int f = 0; f < fileUpdates.Length; f++) { var documentId = edits[f].Key; var deltas = edits[f].Value; fileUpdates[f].FileName = _vsProject.GetDocumentOrAdditionalDocument(documentId).FilePath; fileUpdates[f].LineUpdateCount = (uint)deltas.Length; fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index); for (int l = 0; l < deltas.Length; l++) { lineUpdates[index + l].Line = (uint)deltas[l].OldLine; lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine; } index += deltas.Length; } // The updater makes a copy of all data, we can release the buffer after the call. updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length); } } private Deltas EmitProjectDelta() { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, _committedBaseline, default(CancellationToken)); return emitTask.Result; } /// <summary> /// Returns EnC debug information for initial version of the specified method. /// </summary> /// <exception cref="InvalidDataException">The debug information data is corrupt or can't be retrieved from the debugger.</exception> private EditAndContinueMethodDebugInformation GetBaselineEncDebugInfo(MethodDefinitionHandle methodHandle) { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); if (_pdbReader == null) { // Unmarshal the symbol reader (being marshalled cross thread from STA -> MTA). Debug.Assert(_pdbReaderObjAsStream != IntPtr.Zero); object pdbReaderObjMta; var exception = Marshal.GetExceptionForHR(NativeMethods.GetObjectForStream(_pdbReaderObjAsStream, out pdbReaderObjMta)); if (exception != null) { // likely a bug in the compiler/debugger FatalError.ReportWithoutCrash(exception); throw new InvalidDataException(exception.Message, exception); } _pdbReaderObjAsStream = IntPtr.Zero; _pdbReader = (ISymUnmanagedReader3)pdbReaderObjMta; } int methodToken = MetadataTokens.GetToken(methodHandle); byte[] debugInfo; try { debugInfo = _pdbReader.GetCustomDebugInfoBytes(methodToken, methodVersion: 1); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger { throw new InvalidDataException(e.Message, e); } try { ImmutableArray<byte> localSlots, lambdaMap; if (debugInfo != null) { localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap); lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap); } else { localSlots = lambdaMap = default(ImmutableArray<byte>); } return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap); } catch (InvalidOperationException e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger { // TODO: CustomDebugInfoReader should throw InvalidDataException throw new InvalidDataException(e.Message, e); } } public int EncApplySucceeded(int hrApplyResult) { try { log.Write("Change applied to {0}", _vsProject.DisplayName); Debug.Assert(IsDebuggable); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); Debug.Assert(_pendingBaseline != null); // Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges. _changesApplied = true; _committedBaseline = _pendingBaseline; _pendingBaseline = null; return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } /// <summary> /// Called when changes are being applied. /// </summary> /// <param name="exceptionRegionId"> /// The value of <see cref="ShellInterop.ENC_EXCEPTION_SPAN.id"/>. /// Set by <see cref="GetExceptionSpans(uint, ShellInterop.ENC_EXCEPTION_SPAN[], ref uint)"/> to the index into <see cref="_exceptionRegions"/>. /// </param> /// <param name="ptsNewPosition">Output value holder.</param> public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition) { try { using (NonReentrantContext) { Debug.Assert(IsDebuggable); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); Debug.Assert(ptsNewPosition.Length == 1); var exceptionRegion = _exceptionRegions[(int)exceptionRegionId]; var session = _encService.EditSession; var asid = _activeStatementIds[exceptionRegion.ActiveStatementId]; var document = _projectBeingEmitted.GetDocument(asid.DocumentId); var analysis = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)); var regions = analysis.ExceptionRegions; // the method shouldn't be called in presence of errors: Debug.Assert(!analysis.HasChangesAndErrors); Debug.Assert(!regions.IsDefault); // Absence of rude edits guarantees that the exception regions around AS haven't semantically changed. // Only their spans might have changed. ptsNewPosition[0] = regions[asid.Ordinal][exceptionRegion.Ordinal].ToVsTextSpan(); } return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static int MarshalPdbReader(IDebugUpdateInMemoryPE2 updater, out IntPtr pdbReaderPointer) { // ISymUnmanagedReader can only be accessed from an MTA thread, however, we need // fetch the IUnknown instance (call IENCSymbolReaderProvider.GetSymbolReader) here // in the STA. To further complicate things, we need to return synchronously from // this method. Waiting for the MTA thread to complete so we can return synchronously // blocks the STA thread, so we need to make sure the CLR doesn't try to marshal // ISymUnmanagedReader calls made in an MTA back to the STA for execution (if this // happens we'll be deadlocked). We'll use CoMarshalInterThreadInterfaceInStream to // achieve this. First, we'll marshal the object in a Stream and pass a Stream pointer // over to the MTA. In the MTA, we'll get the Stream from the pointer and unmarshal // the object. The reader object was originally created on an MTA thread, and the // instance we retrieved in the STA was a proxy. When we unmarshal the Stream in the // MTA, it "unwraps" the proxy, allowing us to directly call the implementation. // Another way to achieve this would be for the symbol reader to implement IAgileObject, // but the symbol reader we use today does not. If that changes, we should consider // removing this marshal/unmarshal code. IENCDebugInfo debugInfo; updater.GetENCDebugInfo(out debugInfo); var symbolReaderProvider = (IENCSymbolReaderProvider)debugInfo; object pdbReaderObjSta; symbolReaderProvider.GetSymbolReader(out pdbReaderObjSta); int hr = NativeMethods.GetStreamForObject(pdbReaderObjSta, out pdbReaderPointer); Marshal.ReleaseComObject(pdbReaderObjSta); return hr; } #region Testing #if DEBUG // Fault injection: // If set we'll fail to read MVID of specified projects to test error reporting. internal static ImmutableArray<string> InjectMvidReadingFailure; private void InjectFault_MvidRead() { if (!InjectMvidReadingFailure.IsDefault && InjectMvidReadingFailure.Contains(_vsProject.DisplayName)) { throw new IOException("Fault injection"); } } #else [Conditional("DEBUG")] private void InjectFault_MvidRead() { } #endif #endregion } }
/** * Copyright (C) 2012 Fredrik Holmstrom * * 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. **/ #if UNITY_EDITOR using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using System; public class HairyPlotter : MonoBehaviour { List<HairyPlotterVertex> vertices; List<HairyPlotterTriangle> triangles; Vector3 selectionPosition = Vector3.zero; HairyPlotterTriangle triangleHover = null; HashSet<HairyPlotterTriangle> triangleSelection = new HashSet<HairyPlotterTriangle>(); HashSet<HairyPlotterVertex> verticeSelection = new HashSet<HairyPlotterVertex>(); HairyPlotterVertex uvEditVertex = null; public bool Dirty; public Mesh EditMesh; public string OriginalMesh; public HairyPlotterActions CurrentAction = HairyPlotterActions.None; public int VertexCount { get { return vertices == null ? 0 : vertices.Count; } } public int TriangleCount { get { return triangles == null ? 0 : triangles.Count; } } public int VertexSelectionCount { get { return verticeSelection.Count; } } public int TriangleSelectionCount { get { return triangleSelection.Count; } } public List<HairyPlotterVertex> SelectedVertices { get { return verticeSelection.ToList(); } } public List<HairyPlotterTriangle> SelectedTriangles { get { return triangleSelection.ToList(); } } public Vector3 SelectionPosition { get { return selectionPosition; } set { selectionPosition = value; } } public HairyPlotterVertex LastVertex { get { return VertexCount > 0 ? vertices[VertexCount - 1] : null; } } public HairyPlotterTriangle LastTriangle { get { return TriangleCount > 0 ? triangles[TriangleCount - 1] : null; } } public HairyPlotterTriangle HoveredTriangle { get { return triangleHover; } } public HairyPlotterVertex UvEditVertex { get { return uvEditVertex; } } public IEnumerable<HairyPlotterVertex> UnusedVertices { get { return vertices.Where(x => x.TriangleCount == 0).ToArray(); } } public int UnusedVerticesCount { get { return vertices == null ? 0 : vertices.Where(x => x.TriangleCount == 0).Count(); } } public void ToggleSelected(HairyPlotterVertex vertex) { if (vertex == null) return; if (IsSelected(vertex)) { RemoveSelection(vertex); } else { AddSelection(vertex); } ResetSelectionPosition(); } public bool ToggleSelected(HairyPlotterTriangle triangle) { if (triangle == null) return false; if (IsSelected(triangle)) { RemoveSelection(triangle); } else { AddSelection(triangle); } return true; } public HairyPlotterVertex GetVertex(int index) { return index < vertices.Count ? vertices[index] : null; } public bool IsSelected(HairyPlotterVertex vertex) { return vertex != null && verticeSelection.Contains(vertex); } public bool IsSelected(int index) { return index < vertices.Count && IsSelected(vertices[index]); } public bool IsSelected(HairyPlotterTriangle triangle) { return triangle != null && triangleSelection.Contains(triangle); } public void AddSelection(HairyPlotterVertex vertex) { if (vertex == null) return; verticeSelection.Add(vertex); ResetSelectionPosition(); } public void AddSelection(HairyPlotterTriangle triangle) { if (triangle == null) return; if (triangleHover == triangle) { triangleHover = null; } triangleSelection.Add(triangle); } public void AddSelection(int index) { if (index < vertices.Count) AddSelection(vertices[index]); } public void RemoveSelection(HairyPlotterVertex vertex) { if (uvEditVertex == vertex) uvEditVertex = null; verticeSelection.Remove(vertex); ResetSelectionPosition(); } public void RemoveSelection(HairyPlotterTriangle triangle) { if (triangle == null) return; triangleSelection.Remove(triangle); } public void RemoveSelection(int index) { if (index < vertices.Count) RemoveSelection(vertices[index]); } public void ResetSelectionPosition() { selectionPosition = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); } public void ClearVertexSelection() { uvEditVertex = null; verticeSelection.Clear(); ResetSelectionPosition(); } public void ClearTriangleSelection() { triangleSelection.Clear(); } public void SetTriangleHover(HairyPlotterTriangle triangle) { triangleHover = triangle; } public void SetUvEditVertex(HairyPlotterVertex vertex) { uvEditVertex = vertex; } public void ToEachSelection(Action<HairyPlotterVertex> action) { foreach (HairyPlotterVertex vertex in verticeSelection) { action(vertex); } Dirty = true; } public HairyPlotterVertex CreateVertex() { return CreateVertex(Vector3.zero, Vector2.zero); } public HairyPlotterVertex CreateVertex(Vector3 pos, Vector2 uv) { // Create vertex HairyPlotterVertex vertex = new HairyPlotterVertex(pos, uv, this); // Set index vertex.Index = vertices.Count; // Add to list vertices.Add(vertex); // Return return vertex; } public HairyPlotterTriangle CreateTriangle(HairyPlotterVertex v0, HairyPlotterVertex v1, HairyPlotterVertex v2) { // Create tri HairyPlotterTriangle triangle = new HairyPlotterTriangle(this); // Set vertices for triangle triangle.SetVertices(v0, v1, v2); // Add to triangle list triangles.Add(triangle); // Return return triangle; } public HairyPlotterTriangle CreateTriangle(int i0, int i1, int i2) { return CreateTriangle(vertices[i0], vertices[i1], vertices[i2]); } public HairyPlotterTriangle GetTriangle(int index) { return triangles[index]; } public void DestroyVertex(HairyPlotterVertex vertex) { if (vertex != null) { if (uvEditVertex == vertex) uvEditVertex = null; // Mark dirty Dirty = true; // Remove from vertices and selection vertices.Remove(vertex); verticeSelection.Remove(vertex); for (int i = 0; i < vertex.TriangleCount; ++i) { DestroyTriangle(vertex.GetTriangle(i)); } // Update UpdateVertexIndexes(); } } public void DestroyTriangle(HairyPlotterTriangle triangle) { if (triangle != null) { // Mark dirty Dirty = true; // Clear hover state if (triangleHover == triangle) triangleHover = null; // Remove selection triangleSelection.Remove(triangle); // Remove triangle from mesh triangles.Remove(triangle); // Remove triangle from it's three vertices triangle.GetVertex(0).RemoveTriangle(triangle); triangle.GetVertex(1).RemoveTriangle(triangle); triangle.GetVertex(2).RemoveTriangle(triangle); // Clear link between triangle and vertices triangle.ClearVertices(); // Update UpdateVertexIndexes(); } } public void ClearVertices() { vertices.Clear(); verticeSelection.Clear(); ClearTriangles(); uvEditVertex = null; Dirty = true; } public void ClearTriangles() { triangles.Clear(); triangleHover = null; Dirty = true; } public void InitEditing() { if (!EditMesh) { // Grab filter MeshFilter filter = GetComponent<MeshFilter>(); // Copy original mesh EditMesh = CloneMesh(filter.sharedMesh); // If it's an asset if (AssetDatabase.IsMainAsset(filter.sharedMesh)) { // Store original mesh OriginalMesh = AssetDatabase.GetAssetPath(filter.sharedMesh); } // Overwrite shared mesh filter.sharedMesh = EditMesh; // Create temp asset AssetDatabase.CreateAsset(EditMesh, "Assets/HairyPlotterMesh.asset"); AssetDatabase.SaveAssets(); vertices = null; triangles = null; verticeSelection = null; } if (EditMesh) { if (vertices == null || triangles == null) { Vector2[] meshUv = EditMesh.uv; Vector3[] meshVertices = EditMesh.vertices; int[] meshTriangles = EditMesh.triangles; triangles = new List<HairyPlotterTriangle>(); vertices = new List<HairyPlotterVertex>(); verticeSelection = new HashSet<HairyPlotterVertex>(); // Add verts for (int i = 0; i < meshVertices.Length; i += 1) { CreateVertex(meshVertices[i], i < meshUv.Length ? meshUv[i] : Vector2.zero); } // Add tris for (int i = 0; i < meshTriangles.Length; i += 3) { CreateTriangle(meshTriangles[i + 0], meshTriangles[i + 1], meshTriangles[i + 2]); } } } } public void UpdateVertexIndexes() { // Re-index all vertices for (int i = 0; i < vertices.Count; ++i) { vertices[i].Index = i; } } public void UpdateMesh() { if (Dirty) { // Re-index all vertices UpdateVertexIndexes(); // Update edit mesh EditMesh.Clear(); EditMesh.vertices = vertices.Select(x => x.Position).ToArray(); EditMesh.uv = vertices.Select(x => x.Uv).ToArray(); EditMesh.triangles = triangles.SelectMany(x => x.VertexIndexes).ToArray(); EditMesh.RecalculateBounds(); EditMesh.RecalculateNormals(); } } public static Mesh CloneMesh(Mesh mesh) { if (!mesh) { mesh = new Mesh(); mesh.name = "Empty Mesh"; } Mesh clone = new Mesh(); clone.vertices = mesh.vertices; clone.uv = mesh.uv; clone.triangles = mesh.triangles; clone.normals = mesh.normals; clone.name = mesh.name; clone.RecalculateBounds(); clone.RecalculateNormals(); return clone; } public static bool RayIntersectsVertex(Ray ray, Vector3 vertex, float epsilon) { // First version: if ray XY origin position is near to XY vertex position then return true if (Mathf.Abs(ray.origin.x - vertex.x) < epsilon && Mathf.Abs(ray.origin.y - vertex.y) < epsilon) return true; return false; } public static bool RayIntersectsTriangle(Ray ray, Vector3 vertex1, Vector3 vertex2, Vector3 vertex3) { //Compute vectors along two edges of the triangle. Vector3 edge1, edge2; //Edge 1 edge1.x = vertex2.x - vertex1.x; edge1.y = vertex2.y - vertex1.y; edge1.z = vertex2.z - vertex1.z; //Edge2 edge2.x = vertex3.x - vertex1.x; edge2.y = vertex3.y - vertex1.y; edge2.z = vertex3.z - vertex1.z; //Cross product of ray direction and edge2 - first part of determinant. Vector3 directioncrossedge2; directioncrossedge2.x = (ray.direction.y * edge2.z) - (ray.direction.z * edge2.y); directioncrossedge2.y = (ray.direction.z * edge2.x) - (ray.direction.x * edge2.z); directioncrossedge2.z = (ray.direction.x * edge2.y) - (ray.direction.y * edge2.x); //Compute the determinant. float determinant; //Dot product of edge1 and the first part of determinant. determinant = (edge1.x * directioncrossedge2.x) + (edge1.y * directioncrossedge2.y) + (edge1.z * directioncrossedge2.z); //If the ray is parallel to the triangle plane, there is no collision. //This also means that we are not culling, the ray may hit both the //back and the front of the triangle. if (determinant > -1e-6f && determinant < 1e-6f) { return false; } float inversedeterminant = 1.0f / determinant; //Calculate the U parameter of the intersection point. Vector3 distanceVector; distanceVector.x = ray.origin.x - vertex1.x; distanceVector.y = ray.origin.y - vertex1.y; distanceVector.z = ray.origin.z - vertex1.z; float triangleU; triangleU = (distanceVector.x * directioncrossedge2.x) + (distanceVector.y * directioncrossedge2.y) + (distanceVector.z * directioncrossedge2.z); triangleU *= inversedeterminant; //Make sure it is inside the triangle. if (triangleU < 0f || triangleU > 1f) { return false; } //Calculate the V parameter of the intersection point. Vector3 distancecrossedge1; distancecrossedge1.x = (distanceVector.y * edge1.z) - (distanceVector.z * edge1.y); distancecrossedge1.y = (distanceVector.z * edge1.x) - (distanceVector.x * edge1.z); distancecrossedge1.z = (distanceVector.x * edge1.y) - (distanceVector.y * edge1.x); float triangleV; triangleV = ((ray.direction.x * distancecrossedge1.x) + (ray.direction.y * distancecrossedge1.y)) + (ray.direction.z * distancecrossedge1.z); triangleV *= inversedeterminant; //Make sure it is inside the triangle. if (triangleV < 0f || triangleU + triangleV > 1f) { return false; } //Compute the distance along the ray to the triangle. float raydistance; raydistance = (edge2.x * distancecrossedge1.x) + (edge2.y * distancecrossedge1.y) + (edge2.z * distancecrossedge1.z); raydistance *= inversedeterminant; //Is the triangle behind the ray origin? if (raydistance < 0f) { return false; } return true; } } #pragma warning disable 0414 public class HairyPlotterVertex { static int hashCodeCounter = 0; int hashCode = ++hashCodeCounter; HairyPlotter plotter; List<HairyPlotterTriangle> triangles = new List<HairyPlotterTriangle>(); public int Index = -1; public Vector2 Uv; public Vector3 Position; public int TriangleCount { get { return triangles.Count; } } public HashSet<HairyPlotterTriangle> TriangleSet { get { return new HashSet<HairyPlotterTriangle>(triangles); }} public HairyPlotterVertex(Vector3 pos, Vector2 uv, HairyPlotter hairyPlotter) { Uv = uv; Position = pos; plotter = hairyPlotter; } public void AddTriangle(HairyPlotterTriangle triangle) { triangles.Add(triangle); } public HairyPlotterTriangle GetTriangle(int index) { return triangles[index]; } public void RemoveTriangle(HairyPlotterTriangle triangle) { triangles.Remove(triangle); } public override bool Equals(object obj) { return ReferenceEquals(obj, this); } public override int GetHashCode() { return hashCode; } } #pragma warning restore 0414 public class HairyPlotterTriangle { static int hashCodeCounter = 0; int hashCode = ++hashCodeCounter; HairyPlotter plotter; HairyPlotterVertex[] vertices; public int[] VertexIndexes { get { return new int[3] { vertices[0].Index, vertices[1].Index, vertices[2].Index }; } } public HairyPlotterVertex[] VertexObjects { get { return vertices.Select(v => v).ToArray(); } } public HairyPlotterTriangle(HairyPlotter hairyPlotter) { plotter = hairyPlotter; vertices = new HairyPlotterVertex[3]; } public void ClearVertices() { vertices = new HairyPlotterVertex[3]; } public HairyPlotterVertex GetVertex(int index) { return vertices[index]; } public void SetVertices(HairyPlotterVertex v0, HairyPlotterVertex v1, HairyPlotterVertex v2) { vertices = new HairyPlotterVertex[3] { v0, v1, v2 }; v0.AddTriangle(this); v1.AddTriangle(this); v2.AddTriangle(this); plotter.Dirty = true; } public void ReplaceVertex(HairyPlotterVertex vertex, int index) { vertices[index].RemoveTriangle(this); vertices[index] = vertex; vertices[index].AddTriangle(this); plotter.Dirty = true; } public void SwitchVertices(int a, int b) { SwitchVertices(vertices[a], vertices[b]); } public void SwitchVertices(HairyPlotterVertex a, HairyPlotterVertex b) { int aIndex = Array.IndexOf(vertices, a); int bIndex = Array.IndexOf(vertices, b); if (aIndex == -1 && bIndex == -1) { return; } // Switch both if (aIndex > -1 && bIndex > -1) { vertices[bIndex] = a; vertices[aIndex] = b; } // Switch a for b if (aIndex > -1) { vertices[aIndex] = b; a.RemoveTriangle(this); b.AddTriangle(this); } // Switch b for a if (bIndex > -1) { vertices[bIndex] = a; b.RemoveTriangle(this); a.AddTriangle(this); } plotter.Dirty = true; } public override bool Equals(object obj) { return ReferenceEquals(obj, this); } public override int GetHashCode() { return hashCode; } } public enum HairyPlotterActions { None, VertexDelete, VertexMove, VertexClear, VertexClearUnused, VertexUvEdit, TriangleAdd, TriangleDelete, TriangleClear, TriangleSwitch } #endif
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F09Level11111Child (editable child object).<br/> /// This is a generated base class of <see cref="F09Level11111Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="F08Level1111"/> collection. /// </remarks> [Serializable] public partial class F09Level11111Child : BusinessBase<F09Level11111Child> { #region State Fields [NotUndoable] [NonSerialized] internal int cNarentID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F09Level11111Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="F09Level11111Child"/> object.</returns> internal static F09Level11111Child NewF09Level11111Child() { return DataPortal.CreateChild<F09Level11111Child>(); } /// <summary> /// Factory method. Loads a <see cref="F09Level11111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="F09Level11111Child"/> object.</returns> internal static F09Level11111Child GetF09Level11111Child(SafeDataReader dr) { F09Level11111Child obj = new F09Level11111Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F09Level11111Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private F09Level11111Child() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F09Level11111Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F09Level11111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_Child_Name")); cNarentID1 = dr.GetInt32("CNarentID1"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="F09Level11111Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddF09Level11111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="F09Level11111Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(F08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateF09Level11111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="F09Level11111Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(F08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteF09Level11111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2009 Stephen M. McKamey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*---------------------------------------------------------------------------------*/ #endregion License using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Reflection; #if WINDOWS_STORE using TP = System.Reflection.TypeInfo; #else using TP = System.Type; #endif namespace Pathfinding.Serialization.JsonFx { /// <summary> /// Utility for forcing conversion between types /// </summary> internal class TypeCoercionUtility { #region Constants private const string ErrorNullValueType = "{0} does not accept null as a value"; private const string ErrorDefaultCtor = "Only objects with default constructors can be deserialized. ({0})"; private const string ErrorCannotInstantiate = "Interfaces, Abstract classes, and unsupported ValueTypes cannot be deserialized. ({0})"; #endregion Constants #region Fields private Dictionary<Type, Dictionary<string, MemberInfo>> memberMapCache; private bool allowNullValueTypes = true; #endregion Fields #region Properties private Dictionary<Type, Dictionary<string, MemberInfo>> MemberMapCache { get { if (this.memberMapCache == null) { // instantiate space for cache this.memberMapCache = new Dictionary<Type, Dictionary<string, MemberInfo>>(); } return this.memberMapCache; } } /// <summary> /// Gets and sets if ValueTypes can accept values of null /// </summary> /// <remarks> /// Only affects deserialization: if a ValueType is assigned the /// value of null, it will receive the value default(TheType). /// Setting this to false, throws an exception if null is /// specified for a ValueType member. /// </remarks> public bool AllowNullValueTypes { get { return this.allowNullValueTypes; } set { this.allowNullValueTypes = value; } } #endregion Properties #region Object Methods /// <summary> /// If a Type Hint is present then this method attempts to /// use it and move any previously parsed data over. /// </summary> /// <param name="result">the previous result</param> /// <param name="typeInfo">the type info string to use</param> /// <param name="objectType">reference to the objectType</param> /// <param name="memberMap">reference to the memberMap</param> /// <returns></returns> internal object ProcessTypeHint( IDictionary result, string typeInfo, out Type objectType, out Dictionary<string, MemberInfo> memberMap) { if (String.IsNullOrEmpty(typeInfo)) { objectType = null; memberMap = null; return result; } Type hintedType = Type.GetType(typeInfo, false); if (hintedType == null) { objectType = null; memberMap = null; return result; } objectType = hintedType; return this.CoerceType(hintedType, result, out memberMap); } internal Object InstantiateObject(Type objectType, out Dictionary<string, MemberInfo> memberMap) { if (objectType.IsInterface || objectType.IsAbstract || objectType.IsValueType) { throw new JsonTypeCoercionException( String.Format(TypeCoercionUtility.ErrorCannotInstantiate, objectType.FullName)); } ConstructorInfo ctor = objectType.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new JsonTypeCoercionException( String.Format(TypeCoercionUtility.ErrorDefaultCtor, objectType.FullName)); } Object result; try { // always try-catch Invoke() to expose real exception result = ctor.Invoke(null); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { throw new JsonTypeCoercionException(ex.InnerException.Message, ex.InnerException); } throw new JsonTypeCoercionException("Error instantiating " + objectType.FullName, ex); } memberMap = GetMemberMap (objectType); return result; } /** Returns a member map if suitable for the object type. * Dictionary types will make this method return null */ public Dictionary<string, MemberInfo> GetMemberMap (Type objectType) { // don't incurr the cost of member map for dictionaries if (typeof(IDictionary).IsAssignableFrom(objectType)) { return null; } else { return this.CreateMemberMap(objectType); } } /** Creates a member map for the type */ private Dictionary<string, MemberInfo> CreateMemberMap(Type objectType) { Dictionary<string, MemberInfo> memberMap; if (this.MemberMapCache.TryGetValue(objectType, out memberMap)) { // map was stored in cache return memberMap; } // create a new map memberMap = new Dictionary<string, MemberInfo>(); // load properties into property map PropertyInfo[] properties = objectType.GetProperties( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance ); foreach (PropertyInfo info in properties) { if (!info.CanRead || !info.CanWrite) { continue; } if (JsonIgnoreAttribute.IsJsonIgnore(info)) { continue; } string jsonName = JsonNameAttribute.GetJsonName(info); if (String.IsNullOrEmpty(jsonName)) { memberMap[info.Name] = info; } else { memberMap[jsonName] = info; } } // load public fields into property map FieldInfo[] fields = objectType.GetFields( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance ); foreach (FieldInfo info in fields) { if (!info.IsPublic && info.GetCustomAttributes(typeof(JsonMemberAttribute),true).Length == 0) { continue; } if (JsonIgnoreAttribute.IsJsonIgnore(info)) { continue; } string jsonName = JsonNameAttribute.GetJsonName(info); if (String.IsNullOrEmpty(jsonName)) { memberMap[info.Name] = info; } else { memberMap[jsonName] = info; } } // store in cache for repeated usage this.MemberMapCache[objectType] = memberMap; return memberMap; } internal static Type GetMemberInfo( Dictionary<string, MemberInfo> memberMap, string memberName, out MemberInfo memberInfo) { if (memberMap != null && memberMap.TryGetValue(memberName, out memberInfo)) { // Check properties for object member //memberInfo = memberMap[memberName]; if (memberInfo is PropertyInfo) { // maps to public property return ((PropertyInfo)memberInfo).PropertyType; } else if (memberInfo is FieldInfo) { // maps to public field return ((FieldInfo)memberInfo).FieldType; } } memberInfo = null; return null; } /// <summary> /// Helper method to set value of either property or field /// </summary> /// <param name="result"></param> /// <param name="memberType"></param> /// <param name="memberInfo"></param> /// <param name="value"></param> internal void SetMemberValue(Object result, Type memberType, MemberInfo memberInfo, object value) { if (memberInfo is PropertyInfo) { // set value of public property ((PropertyInfo)memberInfo).SetValue( result, this.CoerceType(memberType, value), null); } else if (memberInfo is FieldInfo) { // set value of public field ((FieldInfo)memberInfo).SetValue( result, this.CoerceType(memberType, value)); } // all other values are ignored } #endregion Object Methods #region Type Methods internal object CoerceType(Type targetType, object value) { bool isNullable = TypeCoercionUtility.IsNullable(targetType); if (value == null) { if (!allowNullValueTypes && targetType.IsValueType && !isNullable) { throw new JsonTypeCoercionException(String.Format(TypeCoercionUtility.ErrorNullValueType, targetType.FullName)); } return value; } if (isNullable) { // nullable types have a real underlying struct Type[] genericArgs = targetType.GetGenericArguments(); if (genericArgs.Length == 1) { targetType = genericArgs[0]; } } Type actualType = value.GetType(); if (targetType.IsAssignableFrom(actualType)) { return value; } if (targetType.IsEnum) { if (value is String) { if (!Enum.IsDefined(targetType, value)) { // if isn't a defined value perhaps it is the JsonName foreach (FieldInfo field in targetType.GetFields()) { string jsonName = JsonNameAttribute.GetJsonName(field); if (((string)value).Equals(jsonName)) { value = field.Name; break; } } } return Enum.Parse(targetType, (string)value); } else { value = this.CoerceType(Enum.GetUnderlyingType(targetType), value); return Enum.ToObject(targetType, value); } } if (value is IDictionary) { Dictionary<string, MemberInfo> memberMap; return this.CoerceType(targetType, (IDictionary)value, out memberMap); } if (typeof(IEnumerable).IsAssignableFrom(targetType) && typeof(IEnumerable).IsAssignableFrom(actualType)) { return this.CoerceList(targetType, actualType, (IEnumerable)value); } if (value is String) { if (targetType == typeof(DateTime)) { DateTime date; if (DateTime.TryParse( (string)value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault, out date)) { return date; } } else if (targetType == typeof(Guid)) { // try-catch is pointless since will throw upon generic conversion return new Guid((string)value); } else if (targetType == typeof(Char)) { if (((string)value).Length == 1) { return ((string)value)[0]; } } else if (targetType == typeof(Uri)) { Uri uri; if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri)) { return uri; } } else if (targetType == typeof(Version)) { // try-catch is pointless since will throw upon generic conversion return new Version((string)value); } } else if (targetType == typeof(TimeSpan)) { return new TimeSpan((long)this.CoerceType(typeof(Int64), value)); } #if !WINPHONE_8 TypeConverter converter = TypeDescriptor.GetConverter(targetType); if (converter.CanConvertFrom(actualType)) { return converter.ConvertFrom(value); } converter = TypeDescriptor.GetConverter(actualType); if (converter.CanConvertTo(targetType)) { return converter.ConvertTo(value, targetType); } #endif try { // fall back to basics return Convert.ChangeType(value, targetType); } catch (Exception ex) { throw new JsonTypeCoercionException( String.Format("Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), ex); } } private object CoerceType(Type targetType, IDictionary value, out Dictionary<string, MemberInfo> memberMap) { object newValue = this.InstantiateObject(targetType, out memberMap); if (memberMap != null) { // copy any values into new object foreach (object key in value.Keys) { MemberInfo memberInfo; Type memberType = TypeCoercionUtility.GetMemberInfo(memberMap, key as String, out memberInfo); this.SetMemberValue(newValue, memberType, memberInfo, value[key]); } } return newValue; } private object CoerceList(Type targetType, Type arrayType, IEnumerable value) { if (targetType.IsArray) { return this.CoerceArray(targetType.GetElementType(), value); } // targetType serializes as a JSON array but is not an array // assume is an ICollection / IEnumerable with AddRange, Add, // or custom Constructor with which we can populate it // many ICollection types take an IEnumerable or ICollection // as a constructor argument. look through constructors for // a compatible match. ConstructorInfo[] ctors = targetType.GetConstructors(); ConstructorInfo defaultCtor = null; foreach (ConstructorInfo ctor in ctors) { ParameterInfo[] paramList = ctor.GetParameters(); if (paramList.Length == 0) { // save for in case cannot find closer match defaultCtor = ctor; continue; } if (paramList.Length == 1 && paramList[0].ParameterType.IsAssignableFrom(arrayType)) { try { // invoke first constructor that can take this value as an argument return ctor.Invoke( new object[] { value } ); } catch { // there might exist a better match continue; } } } if (defaultCtor == null) { throw new JsonTypeCoercionException( String.Format(TypeCoercionUtility.ErrorDefaultCtor, targetType.FullName)); } object collection; try { // always try-catch Invoke() to expose real exception collection = defaultCtor.Invoke(null); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { throw new JsonTypeCoercionException(ex.InnerException.Message, ex.InnerException); } throw new JsonTypeCoercionException("Error instantiating " + targetType.FullName, ex); } // many ICollection types have an AddRange method // which adds all items at once MethodInfo method = targetType.GetMethod("AddRange"); ParameterInfo[] parameters = (method == null) ? null : method.GetParameters(); Type paramType = (parameters == null || parameters.Length != 1) ? null : parameters[0].ParameterType; if (paramType != null && paramType.IsAssignableFrom(arrayType)) { try { // always try-catch Invoke() to expose real exception // add all members in one method method.Invoke( collection, new object[] { value }); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { throw new JsonTypeCoercionException(ex.InnerException.Message, ex.InnerException); } throw new JsonTypeCoercionException("Error calling AddRange on " + targetType.FullName, ex); } return collection; } else { // many ICollection types have an Add method // which adds items one at a time method = targetType.GetMethod("Add"); parameters = (method == null) ? null : method.GetParameters(); paramType = (parameters == null || parameters.Length != 1) ? null : parameters[0].ParameterType; if (paramType != null) { // loop through adding items to collection foreach (object item in value) { try { // always try-catch Invoke() to expose real exception method.Invoke( collection, new object[] { this.CoerceType(paramType, item) }); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { throw new JsonTypeCoercionException(ex.InnerException.Message, ex.InnerException); } throw new JsonTypeCoercionException("Error calling Add on " + targetType.FullName, ex); } } return collection; } } try { // fall back to basics return Convert.ChangeType(value, targetType); } catch (Exception ex) { throw new JsonTypeCoercionException(String.Format("Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), ex); } } private Array CoerceArray(Type elementType, IEnumerable value) { //ArrayList target = new ArrayList(); int count = 0; foreach (object item in value) { count++; } Array arr = Array.CreateInstance (elementType, count); int i=0; foreach (object item in value) { //target.Add(this.CoerceType(elementType, item)); arr.SetValue ( this.CoerceType(elementType, item), i ); i++; } return arr;//target.ToArray(elementType); } private static bool IsNullable(Type type) { return type.IsGenericType && (typeof(Nullable<>) == type.GetGenericTypeDefinition()); } #endregion Type Methods } }
// ******************************************************************************************************** // Product Name: DotSpatial.Positioning.Forms.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://gps3.codeplex.com/ version 3.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 GPS.Net 3.0 // | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper. // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.Threading; using System.Windows.Forms; #if !PocketPC || DesignTime || Framework20 using System.ComponentModel; #endif #if PocketPC using DotSpatial.Positioning.Licensing; #endif namespace DotSpatial.Positioning.Forms { /// <summary> /// Controls whether controls are rotated to show the current bearing straight up. /// </summary> public enum RotationOrientation { /// <summary> /// The control will be rotated so that North always points to the top of the screen. /// </summary> NorthUp = 0, /// <summary> /// The control will be rotated so the the current bearing points to the top of the screen. /// </summary> TrackUp = 1 } #if !PocketPC || DesignTime /// <summary> /// Represents a user control used to display the location and signal strength of GPS satellites. /// </summary> [ToolboxBitmap(typeof(SatelliteViewer), "Resources.SatelliteViewer.bmp")] [DefaultProperty("Satellites")] #endif #if Framework20 #if !PocketPC [ToolboxItem(true)] #endif #endif //[CLSCompliant(false)] public sealed class SatelliteViewer : PolarControl { private Azimuth _bearing = Azimuth.North; #if PocketPC private Angle _MinorTickInterval = new Angle(5); #if Framework20 private Pen _MajorTickPen = new Pen(Color.Black, 2.0f); #else private Pen _MajorTickPen = new Pen(Color.Black); #endif #else private Angle _minorTickInterval = new Angle(2); private Pen _majorTickPen = new Pen(Color.Black, 2.0f); #endif private Angle _majorTickInterval = new Angle(15); private Pen _minorTickPen = new Pen(Color.Black); private Angle _directionLabelInterval = new Angle(45); private string _directionLabelFormat = "c"; private SolidBrush _directionLabelBrush = new SolidBrush(Color.Black); private Pen _halfwayUpPen = new Pen(Color.Gray); #if PocketPC private Font _DirectionLabelFont = new Font("Tahoma", 7.0f, FontStyle.Regular); private Font _PseudorandomNumberFont = new Font("Tahoma", 7.0f, FontStyle.Bold); private SolidBrush _SatelliteFixBrush = new SolidBrush(Color.LimeGreen); #else private Font _directionLabelFont = new Font("Tahoma", 12.0f, FontStyle.Bold); private Font _pseudorandomNumberFont = new Font("Tahoma", 9.0f, FontStyle.Regular); #endif private SolidBrush _pseudorandomNumberBrush = new SolidBrush(Color.Black); private bool _isUsingRealTimeData = true; #if !PocketPC private SolidBrush _satelliteShadowBrush = new SolidBrush(Color.FromArgb(32, 0, 0, 0)); private Color _satelliteFixColor = Color.LightGreen; #endif private Color _satelliteNoSignalFillColor = Color.Transparent; private Color _satellitePoorSignalFillColor = Color.Red; private Color _satelliteModerateSignalFillColor = Color.Orange; private Color _satelliteGoodSignalFillColor = Color.Green; private Color _satelliteExcellentSignalFillColor = Color.LightGreen; private Color _satelliteNoSignalOutlineColor = Color.Transparent; private Color _satellitePoorSignalOutlineColor = Color.Black; private Color _satelliteModerateSignalOutlineColor = Color.Black; private Color _satelliteGoodSignalOutlineColor = Color.Black; private Color _satelliteExcellentSignalOutlineColor = Color.Black; private readonly ColorInterpolator _fillNone = new ColorInterpolator(Color.Transparent, Color.Red, 10); private readonly ColorInterpolator _fillPoor = new ColorInterpolator(Color.Red, Color.Orange, 10); private readonly ColorInterpolator _pFillModerate = new ColorInterpolator(Color.Orange, Color.Green, 10); private readonly ColorInterpolator _pFillGood = new ColorInterpolator(Color.Green, Color.LightGreen, 10); private readonly ColorInterpolator _pFillExcellent = new ColorInterpolator(Color.LightGreen, Color.White, 10); private readonly ColorInterpolator _pOutlineNone = new ColorInterpolator(Color.Transparent, Color.Gray, 10); private readonly ColorInterpolator _pOutlinePoor = new ColorInterpolator(Color.Gray, Color.Gray, 10); private readonly ColorInterpolator _pOutlineModerate = new ColorInterpolator(Color.Gray, Color.Gray, 10); private readonly ColorInterpolator _pOutlineGood = new ColorInterpolator(Color.Gray, Color.Gray, 10); private readonly ColorInterpolator _pOutlineExcellent = new ColorInterpolator(Color.Gray, Color.LightGreen, 10); private List<Satellite> _satellites; private RotationOrientation _rotationOrientation = RotationOrientation.TrackUp; //private object RenderSyncLock = new object(); private static readonly PointD[] _icon = new[] { new PointD(0, 0), new PointD(0, 10), new PointD(3, 10), new PointD(3, 5), new PointD(4, 5), new PointD(4, 10), new PointD(8, 10), new PointD(8, 5), new PointD(10, 5), new PointD(10, 6), new PointD(12, 8), new PointD(14, 8), new PointD(16, 6), new PointD(16, 5), new PointD(18, 5), new PointD(18, 10), new PointD(22, 10), new PointD(22, 5), new PointD(23, 5), new PointD(23, 10), new PointD(26, 10), new PointD(26, 0), new PointD(23, 0), new PointD(23, 5), new PointD(22, 5), new PointD(22, 0), new PointD(18, 0), new PointD(18, 5), new PointD(16, 5), new PointD(16, 4), new PointD(14, 2), new PointD(12, 2), new PointD(10, 4), new PointD(10, 5), new PointD(8, 5), new PointD(8, 0), new PointD(4, 0), new PointD(4, 5), new PointD(3, 5), new PointD(3, 0), new PointD(0, 0) }; private static PointD _iconCenter = new PointD(13, 5); /// <summary> /// Creates a new instance. /// </summary> public SatelliteViewer() : base("DotSpatial.Positioning Multithreaded Satellite Viewer Control (http://dotspatial.codeplex.com)") { //MessageBox.Show("SatelliteViewer Initialization started."); _satellites = new List<Satellite>(); Orientation = PolarCoordinateOrientation.Clockwise; Origin = Azimuth.North; // Set the max and min CenterR = 0; MaximumR = 90; #if PocketPC #if Framework20 _HalfwayUpPen.DashStyle = DashStyle.Dash; #endif #else _halfwayUpPen.DashStyle = DashStyle.DashDotDot; #endif #if PocketPC && !Framework20 && !DesignTime // Bind global events when GPS data changes DotSpatial.Positioning.Gps.IO.Devices.SatellitesChanged += new SatelliteCollectionEventHandler(Devices_CurrentSatellitesChanged); DotSpatial.Positioning.Gps.IO.Devices.BearingChanged += new EventHandler<AzimuthEventArgs>(Devices_CurrentBearingChanged); #endif } #if !PocketPC || Framework20 /// <inheritdocs/> protected override void OnHandleCreated(EventArgs e) { // Subscribe to events try { base.OnHandleCreated(e); // Only hook into events if we're at run-time. Hooking events // at design-time can actually cause errors in the WF Designer. if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) { Devices.SatellitesChanged += Devices_CurrentSatellitesChanged; Devices.BearingChanged += Devices_CurrentBearingChanged; } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } /// <inheritdocs/> protected override void OnHandleDestroyed(EventArgs e) { try { // Only hook into events if we're at run-time. Hooking events // at design-time can actually cause errors in the WF Designer. if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) { Devices.SatellitesChanged -= Devices_CurrentSatellitesChanged; Devices.BearingChanged -= Devices_CurrentBearingChanged; } } finally { base.OnHandleDestroyed(e); } } #endif /// <inheritdocs/> protected override void OnInitialize() { //MessageBox.Show("SatelliteViewer OnInitialize."); base.OnInitialize(); // Set the collection if it's design mode if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) { // TODO: How to Randomize satellites? _satellites = new List<Satellite>(); // SatelliteCollection.Random(45); } else { if (_isUsingRealTimeData) { // Merge it with live satellite data _satellites = Devices.Satellites; } } //MessageBox.Show("SatelliteViewer OnInitialize completed."); } /// <inheritdocs/> protected override void Dispose(bool disposing) { #if PocketPC && !Framework20 && !DesignTime //MessageBox.Show("SatelliteViewer Dispose."); // Bind global events when GPS data changes try { DotSpatial.Positioning.Gps.IO.Devices.SatellitesChanged -= new SatelliteCollectionEventHandler(Devices_CurrentSatellitesChanged); } catch { } try { DotSpatial.Positioning.Gps.IO.Devices.BearingChanged -= new EventHandler<AzimuthEventArgs>(Devices_CurrentBearingChanged); } catch { } #endif #if PocketPC if (_SatelliteFixBrush != null) { try { _SatelliteFixBrush.Dispose(); } catch { } finally { _SatelliteFixBrush = null; } } #endif if (_minorTickPen != null) { try { _minorTickPen.Dispose(); } finally { _minorTickPen = null; } } if (_majorTickPen != null) { try { _majorTickPen.Dispose(); } finally { _majorTickPen = null; } } if (_directionLabelBrush != null) { try { _directionLabelBrush.Dispose(); } finally { _directionLabelBrush = null; } } if (_directionLabelFont != null) { try { _directionLabelFont.Dispose(); } finally { _directionLabelFont = null; } } #if !PocketPC if (_satelliteShadowBrush != null) { _satelliteShadowBrush.Dispose(); _satelliteShadowBrush = null; } #endif if (_pseudorandomNumberFont != null) { try { _pseudorandomNumberFont.Dispose(); } finally { _pseudorandomNumberFont = null; } } if (_pseudorandomNumberBrush != null) { try { _pseudorandomNumberBrush.Dispose(); } finally { _pseudorandomNumberBrush = null; } } if (_halfwayUpPen != null) { try { _halfwayUpPen.Dispose(); } finally { _halfwayUpPen = null; } } base.Dispose(disposing); } private Color GetFillColor(SignalToNoiseRatio signal) { if (signal.Value < 10) return _fillNone[signal.Value]; if (signal.Value < 20) return _fillPoor[signal.Value - 10]; if (signal.Value < 30) return _pFillModerate[signal.Value - 20]; if (signal.Value < 40) return _pFillGood[signal.Value - 30]; if (signal.Value < 50) return _pFillExcellent[signal.Value - 40]; return _pFillExcellent[9]; } private Color GetOutlineColor(SignalToNoiseRatio signal) { if (signal.Value < 10) return _pOutlineNone[signal.Value]; if (signal.Value < 20) return _pOutlinePoor[signal.Value - 10]; if (signal.Value < 30) return _pOutlineModerate[signal.Value - 20]; if (signal.Value < 40) return _pOutlineGood[signal.Value - 30]; if (signal.Value < 50) return _pOutlineExcellent[signal.Value - 40]; return _pOutlineExcellent[9]; } #if !PocketPC || DesignTime /// <summary> /// Controls the amount of rotation applied to the entire control to indicate the current direction of travel. /// </summary> [Category("Behavior")] [DefaultValue(typeof(Azimuth), "0")] [Description("Controls the amount of rotation applied to the entire control to indicate the current direction of travel.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Azimuth Bearing { get { return _bearing; } set { if (_bearing.Equals(value)) return; _bearing = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls whether the Satellites property is set manually, or automatically read from any available GPS device. /// </summary> [Category("Behavior")] [DefaultValue(typeof(bool), "True")] [Description("Controls whether the Satellites property is set manually, or automatically read from any available GPS device.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public bool IsUsingRealTimeData { get { return _isUsingRealTimeData; } set { if (_isUsingRealTimeData == value) return; //MessageBox.Show("IsUsingRealTimeData started."); _isUsingRealTimeData = value; #if !DesignTime if (_isUsingRealTimeData) { // Use current satellite information _satellites = Devices.Satellites; // Also set the bearing if (_rotationOrientation == RotationOrientation.TrackUp) Rotation = new Angle(-Devices.Bearing.DecimalDegrees); } else { _satellites.Clear(); // Clear the rotation if (_rotationOrientation == RotationOrientation.TrackUp) Rotation = Angle.Empty; } #endif InvokeRepaint(); } } #if !PocketPC || DesignTime #if PocketPC [DefaultValue(typeof(Angle), "5")] #else /// <summary> /// Controls the number of degrees in between each smaller tick mark around the control. /// </summary> [DefaultValue(typeof(Angle), "2")] #endif [Category("Tick Marks")] [Description("Controls the number of degrees in between each smaller tick mark around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Angle MinorTickInterval { get { return _minorTickInterval; } set { if (_minorTickInterval.Equals(value)) return; _minorTickInterval = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the format of compass directions drawn around the control. /// </summary> [Category("Direction Labels")] [DefaultValue(typeof(string), "c")] [Description("Controls the format of compass directions drawn around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public string DirectionLabelFormat { get { return _directionLabelFormat; } set { if (_directionLabelFormat == value) return; _directionLabelFormat = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the number of degrees in between each larger tick mark around the control. /// </summary> [DefaultValue(typeof(Angle), "15")] [Category("Tick Marks")] [Description("Controls the number of degrees in between each larger tick mark around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Angle MajorTickInterval { get { return _majorTickInterval; } set { if (_majorTickInterval.Equals(value)) return; _majorTickInterval = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color used to draw smaller tick marks around the control. /// </summary> [Category("Tick Marks")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color used to draw smaller tick marks around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color MinorTickColor { get { return _minorTickPen.Color; } set { lock (_minorTickPen) { if (_minorTickPen.Color.Equals(value)) return; _minorTickPen.Color = value; } Thread.Sleep(0); InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color used to draw larger tick marks around the control. /// </summary> [Category("Tick Marks")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color used to draw larger tick marks around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color MajorTickColor { get { return _majorTickPen.Color; } set { lock (_majorTickPen) { if (_majorTickPen.Color.Equals(value)) return; _majorTickPen.Color = value; } Thread.Sleep(0); InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the number of degrees in between each compass label around the control. /// </summary> [Category("Direction Labels")] [DefaultValue(typeof(Angle), "45")] [Description("Controls the number of degrees in between each compass label around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif ////[CLSCompliant(false)] public Angle DirectionLabelInterval { get { return _directionLabelInterval; } set { if (_directionLabelInterval.Equals(value)) return; _directionLabelInterval = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color used to display compass direction letters around the control. /// </summary> [Category("Direction Labels")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color used to display compass direction letters around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color DirectionLabelColor { get { return _directionLabelBrush.Color; } set { lock (_directionLabelBrush) { if (_directionLabelBrush.Color.Equals(value)) return; _directionLabelBrush.Color = value; } Thread.Sleep(0); InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the font used to draw compass labels around the control. /// </summary> [Category("Direction Labels")] #if PocketPC [DefaultValue(typeof(Font), "Tahoma, 7pt")] #else [DefaultValue(typeof(Font), "Tahoma, 12pt, style=Bold")] #endif [Description("Controls the font used to draw compass labels around the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Font DirectionLabelFont { get { return _directionLabelFont; } set { if (_directionLabelFont.Equals(value)) return; _directionLabelFont = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color inside of satellite icons with no signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Transparent")] [Description("Controls the color inside of satellite icons with no signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color NoSignalFillColor { get { return _satelliteNoSignalFillColor; } set { if (_satelliteNoSignalFillColor.Equals(value)) return; _satelliteNoSignalFillColor = value; _fillNone.EndColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color inside of satellite icons with a weak signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Red")] [Description("Controls the color inside of satellite icons with a weak signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color PoorSignalFillColor { get { return _satellitePoorSignalFillColor; } set { if (_satellitePoorSignalFillColor.Equals(value)) return; _satellitePoorSignalFillColor = value; _fillNone.EndColor = value; _fillPoor.StartColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color inside of satellite icons with a moderate signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Orange")] [Description("Controls the color inside of satellite icons with a moderate signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color ModerateSignalFillColor { get { return _satelliteModerateSignalFillColor; } set { if (_satelliteModerateSignalFillColor.Equals(value)) return; _satelliteModerateSignalFillColor = value; _pFillModerate.StartColor = value; _fillPoor.EndColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color inside of satellite icons with a strong signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Green")] [Description("Controls the color inside of satellite icons with a strong signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color GoodSignalFillColor { get { return _satelliteGoodSignalFillColor; } set { if (_satelliteGoodSignalFillColor.Equals(value)) return; _satelliteGoodSignalFillColor = value; _pFillGood.StartColor = value; _pFillModerate.EndColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color inside of satellite icons with a very strong signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "LightGreen")] [Description("Controls the color inside of satellite icons with a very strong signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color ExcellentSignalFillColor { get { return _satelliteExcellentSignalFillColor; } set { if (_satelliteExcellentSignalFillColor.Equals(value)) return; _satelliteExcellentSignalFillColor = value; _pFillGood.EndColor = value; _pFillExcellent.StartColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color around satellite icons with no signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Transparent")] [Description("Controls the color around satellite icons with no signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color NoSignalOutlineColor { get { return _satelliteNoSignalOutlineColor; } set { if (_satelliteNoSignalOutlineColor.Equals(value)) return; _satelliteNoSignalOutlineColor = value; _pOutlineNone.EndColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color around satellite icons with a weak signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color around satellite icons with a weak signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color PoorSignalOutlineColor { get { return _satellitePoorSignalOutlineColor; } set { if (_satellitePoorSignalOutlineColor.Equals(value)) return; _satellitePoorSignalOutlineColor = value; _pOutlineNone.EndColor = value; _pOutlinePoor.StartColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color around satellite icons with a moderate signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color around satellite icons with a moderate signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color ModerateSignalOutlineColor { get { return _satelliteModerateSignalOutlineColor; } set { if (_satelliteModerateSignalOutlineColor.Equals(value)) return; _satelliteModerateSignalOutlineColor = value; _pOutlinePoor.EndColor = value; _pOutlineModerate.StartColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color around satellite icons with a strong signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color around satellite icons with a strong signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color GoodSignalOutlineColor { get { return _satelliteGoodSignalOutlineColor; } set { if (_satelliteGoodSignalOutlineColor.Equals(value)) return; _satelliteGoodSignalOutlineColor = value; _pOutlineModerate.EndColor = value; _pOutlineGood.StartColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color around satellite icons with a very strong signal. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color around satellite icons with a very strong signal.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color ExcellentSignalOutlineColor { get { return _satelliteExcellentSignalOutlineColor; } set { if (_satelliteExcellentSignalOutlineColor.Equals(value)) return; _satelliteExcellentSignalOutlineColor = value; _pOutlineGood.EndColor = value; _pOutlineExcellent.StartColor = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color of the ellipse drawn around fixed satellites. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "LimeGreen")] [Description("Controls the color of the ellipse drawn around fixed satellites.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color FixColor { get { #if PocketPC return _SatelliteFixBrush.Color; #else return _satelliteFixColor; #endif } set { #if PocketPC if (_SatelliteFixBrush.Color.Equals(value)) return; _SatelliteFixBrush.Color = value; #else if (_satelliteFixColor.Equals(value)) return; _satelliteFixColor = value; #endif InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls which bearing points straight up on the screen. /// </summary> [Category("Behavior")] [DefaultValue(typeof(RotationOrientation), "TrackUp")] [Description("Controls which bearing points straight up on the screen.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public RotationOrientation RotationOrientation { get { return _rotationOrientation; } set { if (_rotationOrientation == value) return; _rotationOrientation = value; // If this becomes active, set the current bearing Rotation = _rotationOrientation == RotationOrientation.TrackUp ? new Angle(-Devices.Bearing.DecimalDegrees) : Angle.Empty; //InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Contains the list of satellites drawn inside of the control. /// </summary> [Category("Satellites")] [Description("Contains the list of satellites drawn inside of the control.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public List<Satellite> Satellites { get { return _satellites; } set { _satellites = value; // Redraw the control if (_satellites != null) InvokeRepaint(); } } #if Framework20 && !PocketPC /// <summary> /// The Origin Azimuth angle /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override Azimuth Origin { get { return base.Origin; } set { base.Origin = value; } } /// <summary> /// The rotation angle /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override Angle Rotation { get { return base.Rotation; } set { base.Rotation = value; } } #endif /// <inheritdocs/> protected override void OnPaintOffScreen(PaintEventArgs e) { PolarGraphics f = CreatePolarGraphics(e.Graphics); // Cache drawing intervals and such to prevent a race condition double minorInterval = _minorTickInterval.DecimalDegrees; double majorInterval = _majorTickInterval.DecimalDegrees; double directionInterval = _directionLabelInterval.DecimalDegrees; // Draw tick marks if (minorInterval > 0) { for (double angle = 0; angle < 360; angle += minorInterval) { // And draw a line f.DrawLine(_minorTickPen, new PolarCoordinate(88.0f, angle), new PolarCoordinate(90, angle)); } } // Draw tick marks if (majorInterval > 0) { for (double angle = 0; angle < 360; angle += majorInterval) { // And draw a line f.DrawLine(_majorTickPen, new PolarCoordinate(85.0f, angle), new PolarCoordinate(90, angle)); } } if (directionInterval > 0) { for (double angle = 0; angle < 360; angle += directionInterval) { // Get the coordinate of the line's start PolarCoordinate start = new PolarCoordinate(70, angle, Azimuth.North, PolarCoordinateOrientation.Clockwise); #if PocketPC f.DrawCenteredString(((Azimuth)angle).ToString(_DirectionLabelFormat, CultureInfo.CurrentCulture), _DirectionLabelFont, _DirectionLabelBrush, start); #else f.DrawRotatedString(((Azimuth)angle).ToString(_directionLabelFormat, CultureInfo.CurrentCulture), _directionLabelFont, _directionLabelBrush, start); #endif } } // Draw an ellipse at the center f.DrawEllipse(_halfwayUpPen, PolarCoordinate.Empty, 45); // Now draw each satellite int satelliteCount = 0; if (Satellites != null) { satelliteCount = Satellites.Count; #if !PocketPC for (int index = 0; index < satelliteCount; index++) { Satellite satellite = _satellites[index]; // Don't draw if the satellite is stale if (!satellite.IsActive && !DesignMode) continue; // Is the satellite transparent? if (GetFillColor(satellite.SignalToNoiseRatio).A < _satelliteShadowBrush.Color.A) continue; // Get the coordinate for this satellite PolarCoordinate center = new PolarCoordinate(Convert.ToSingle(90.0f - satellite.Elevation.DecimalDegrees), satellite.Azimuth.DecimalDegrees, Azimuth.North, PolarCoordinateOrientation.Clockwise); PointD centerPoint = f.ToPointD(center); // Each icon is 30x30, so we'll translate it by half the distance double pShadowSize = Math.Sin(Radian.FromDegrees(satellite.Elevation.DecimalDegrees).Value) * 7; f.Graphics.TranslateTransform((float)(centerPoint.X - _iconCenter.X + pShadowSize), (float)(centerPoint.Y - _iconCenter.Y + pShadowSize)); // Draw each satellite PointF[] satelliteIcon = new PointF[_icon.Length]; for (int iconIndex = 0; iconIndex < _icon.Length; iconIndex++) { satelliteIcon[iconIndex] = new PointF((float)_icon[iconIndex].X, (float)_icon[iconIndex].Y); } using (Matrix y = new Matrix()) { y.RotateAt(Convert.ToSingle(satellite.Azimuth.DecimalDegrees - f.Rotation.DecimalDegrees + Origin.DecimalDegrees), new PointF((float)_iconCenter.X, (float)_iconCenter.Y), MatrixOrder.Append); y.TransformPoints(satelliteIcon); } f.Graphics.FillPolygon(_satelliteShadowBrush, satelliteIcon); f.Graphics.ResetTransform(); } #endif } // Now draw each satellite if (_satellites != null) { List<Satellite> fixedSatellites = Satellite.GetFixedSatellites(_satellites); int fixedSatelliteCount = fixedSatellites.Count; for (int index = 0; index < fixedSatelliteCount; index++) { Satellite satellite = fixedSatellites[index]; if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { #if PocketPC // Don't draw if the satellite is stale if (!satellite.IsActive) continue; #else // Don't draw if the satellite is stale if (!satellite.IsActive && !DesignMode) continue; #endif } // Get the coordinate for this satellite PolarCoordinate center = new PolarCoordinate(Convert.ToSingle(90.0 - satellite.Elevation.DecimalDegrees), satellite.Azimuth.DecimalDegrees, Azimuth.North, PolarCoordinateOrientation.Clockwise); #if PocketPC f.FillEllipse(_SatelliteFixBrush, Center, 16); #else using (SolidBrush fixBrush = new SolidBrush(Color.FromArgb(Math.Min(255, fixedSatellites.Count * 20), _satelliteFixColor))) { f.FillEllipse(fixBrush, center, 16); } #endif } // Now draw each satellite for (int index = 0; index < satelliteCount; index++) { Satellite satellite = _satellites[index]; if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { #if PocketPC // Don't draw if the satellite is stale if (!satellite.IsActive) continue; #else // Don't draw if the satellite is stale if (!satellite.IsActive && !DesignMode) continue; #endif } // Get the coordinate for this satellite PolarCoordinate center = new PolarCoordinate(Convert.ToSingle(90.0 - satellite.Elevation.DecimalDegrees), satellite.Azimuth.DecimalDegrees, Azimuth.North, PolarCoordinateOrientation.Clockwise); PointD centerPoint = f.ToPointD(center); #if PocketPC // Manually rotate each point of the icon Point[] SatelliteIcon = new Point[Icon.Length]; for (int index2 = 0; index2 < Icon.Length; index2++) { PointD point = Icon[index2] .RotateAt(satellite.Azimuth.DecimalDegrees - Rotation.DecimalDegrees + Origin.DecimalDegrees, IconCenter) .Add(CenterPoint.X - IconCenter.X, CenterPoint.Y - IconCenter.Y); SatelliteIcon[index2] = new Point((int)point.X, (int)point.Y); } Color SatelliteColor = GetFillColor(satellite.SignalToNoiseRatio); SolidBrush FillBrush = new SolidBrush(SatelliteColor); f.Graphics.FillPolygon(FillBrush, SatelliteIcon); FillBrush.Dispose(); #else // Each icon is 30x30, so we'll translate it by half the distance double pShadowSize = Math.Sin(Radian.FromDegrees(satellite.Elevation.DecimalDegrees).Value) * 7; f.Graphics.TranslateTransform((float)(centerPoint.X - _iconCenter.X - pShadowSize * 0.1), (float)(centerPoint.Y - _iconCenter.Y - pShadowSize * 0.1)); // Draw each satellite PointF[] satelliteIcon = new PointF[_icon.Length]; for (int iconIndex = 0; iconIndex < _icon.Length; iconIndex++) { satelliteIcon[iconIndex] = new PointF((float)_icon[iconIndex].X, (float)_icon[iconIndex].Y); } Matrix y = new Matrix(); y.RotateAt(Convert.ToSingle(satellite.Azimuth.DecimalDegrees - f.Rotation.DecimalDegrees + Origin.DecimalDegrees), new PointF((float)_iconCenter.X, (float)_iconCenter.Y), MatrixOrder.Append); y.TransformPoints(satelliteIcon); y.Dispose(); SolidBrush fillBrush = new SolidBrush(GetFillColor(satellite.SignalToNoiseRatio)); f.Graphics.FillPolygon(fillBrush, satelliteIcon); fillBrush.Dispose(); Pen fillPen = new Pen(GetOutlineColor(satellite.SignalToNoiseRatio), 1.0f); f.Graphics.DrawPolygon(fillPen, satelliteIcon); fillPen.Dispose(); f.Graphics.ResetTransform(); #endif #if PocketPC if (!SatelliteColor.Equals(Color.Transparent)) { f.DrawCenteredString(satellite.PseudorandomNumber.ToString(), _PseudorandomNumberFont, _PseudorandomNumberBrush, new PolarCoordinate(Center.R - 11, Center.Theta.DecimalDegrees, Azimuth.North, PolarCoordinateOrientation.Clockwise)); } #else f.DrawRotatedString(satellite.PseudorandomNumber.ToString(CultureInfo.CurrentCulture), _pseudorandomNumberFont, _pseudorandomNumberBrush, new PolarCoordinate(center.R - 11, center.Theta, Azimuth.North, PolarCoordinateOrientation.Clockwise)); #endif } } } #if !PocketPC /// <summary> /// Controls the color of the shadow cast by satellite icons. /// </summary> [Category("Appearance")] [DefaultValue(typeof(Color), "32, 0, 0, 0")] [Description("Controls the color of the shadow cast by satellite icons.")] public Color ShadowColor { get { return _satelliteShadowBrush.Color; } set { lock (_satelliteShadowBrush) { if (_satelliteShadowBrush.Color.Equals(value)) return; _satelliteShadowBrush.Color = value; } InvokeRepaint(); } } #endif #if !PocketPC || DesignTime /// <summary> /// Controls the font used to display the ID of each satellite. /// </summary> [Category("Satellite Colors")] #if PocketPC [DefaultValue(typeof(Font), "Tahoma, 7pt, style=Bold")] #else [DefaultValue(typeof(Font), "Tahoma, 9pt")] #endif [Description("Controls the font used to display the ID of each satellite.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Font PseudorandomNumberFont { get { return _pseudorandomNumberFont; } set { if (_pseudorandomNumberFont.Equals(value)) return; _pseudorandomNumberFont = value; InvokeRepaint(); } } #if !PocketPC || DesignTime /// <summary> /// Controls the color used to display the ID of each satellite. /// </summary> [Category("Satellite Colors")] [DefaultValue(typeof(Color), "Black")] [Description("Controls the color used to display the ID of each satellite.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Browsable(true)] [EditorBrowsable(EditorBrowsableState.Always)] #endif public Color PseudorandomNumberColor { get { return _pseudorandomNumberBrush.Color; } set { lock (_pseudorandomNumberBrush) { if (_pseudorandomNumberBrush.Color.Equals(value)) return; _pseudorandomNumberBrush.Color = value; } Thread.Sleep(0); InvokeRepaint(); } } private void Devices_CurrentSatellitesChanged(object sender, SatelliteListEventArgs e) { //TODO should this be done here or in a user defined event handler? if (_isUsingRealTimeData) Satellites = (List<Satellite>)e.Satellites; InvokeRepaint(); } private void Devices_CurrentBearingChanged(object sender, AzimuthEventArgs e) { if (_isUsingRealTimeData && _rotationOrientation == RotationOrientation.TrackUp) Rotation = new Angle(e.Azimuth.DecimalDegrees); } } }
//------------------------------------------------------------------------------ // <copyright file="PeerObject.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.PeerToPeer.Collaboration { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Runtime.InteropServices; using System.Text; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.ComponentModel; using System.Runtime.Serialization; using System.Security.Permissions; /// <summary> /// This class handles all the functionality and events associated with the Collaboration /// Peer Object /// </summary> [Serializable] public class PeerObject : IDisposable, IEquatable<PeerObject>, ISerializable { private const int c_16K = 16384; private Guid m_id; private byte[] m_data; private PeerScope m_peerScope; private ISynchronizeInvoke m_synchronizingObject; // // Initialize on first access of this class // // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.Initialize():System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] static PeerObject() { CollaborationHelperFunctions.Initialize(); } public PeerObject() { m_id = Guid.NewGuid(); } public PeerObject(Guid Id, byte[] data, PeerScope peerScope) { if ((data != null) && (data.Length > c_16K)) throw new ArgumentException(SR.GetString(SR.Collab_ObjectDataSizeFailed), "data"); m_id = Id; m_peerScope = peerScope; m_data = data; } /// <summary> /// Constructor to enable serialization /// </summary> [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] protected PeerObject(SerializationInfo serializationInfo, StreamingContext streamingContext) { m_id = (Guid) serializationInfo.GetValue("_Id", typeof(Guid)); m_data = (byte[])serializationInfo.GetValue("_Data", typeof(byte[])); m_peerScope = (PeerScope) serializationInfo.GetInt32("_Scope"); } public Guid Id { get{ if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_id; } set{ if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_id = value; } } public byte[] Data { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_data; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); if ((value != null) && (value.Length > c_16K)) throw new ArgumentException(SR.GetString(SR.Collab_ObjectDataSizeFailed)); m_data = value; } } public PeerScope PeerScope { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_peerScope; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_peerScope = value; } } /// <summary> /// Gets and set the object used to marshall event handlers calls for stand alone /// events /// </summary> [Browsable(false), DefaultValue(null), Description(SR.SynchronizingObject)] public ISynchronizeInvoke SynchronizingObject { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_synchronizingObject; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_synchronizingObject = value; } } private event EventHandler<ObjectChangedEventArgs> m_objectChanged; public event EventHandler<ObjectChangedEventArgs> ObjectChanged { // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: AddObjectChangedEvent(EventHandler`1<System.Net.PeerToPeer.Collaboration.ObjectChangedEventArgs>):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] add { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand(); AddObjectChangedEvent(value); } // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: RemoveObjectChangedEvent(EventHandler`1<System.Net.PeerToPeer.Collaboration.ObjectChangedEventArgs>):Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] remove { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand(); RemoveObjectChangedEvent(value); } } #region Object changed event variables private object m_lockObjChangedEvent; private object LockObjChangedEvent { get{ if (m_lockObjChangedEvent == null){ object o = new object(); Interlocked.CompareExchange(ref m_lockObjChangedEvent, o, null); } return m_lockObjChangedEvent; } } private RegisteredWaitHandle m_regObjChangedWaitHandle; private AutoResetEvent m_objChangedEvent; private SafeCollabEvent m_safeObjChangedEvent; #endregion // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="GCHandle.Alloc(System.Object,System.Runtime.InteropServices.GCHandleType):System.Runtime.InteropServices.GCHandle" /> // <SatisfiesLinkDemand Name="GCHandle.AddrOfPinnedObject():System.IntPtr" /> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <SatisfiesLinkDemand Name="GCHandle.Free():System.Void" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <ReferencesCritical Name="Method: ObjectChangedCallback(Object, Boolean):Void" Ring="1" /> // <ReferencesCritical Name="Field: m_safeObjChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] private void AddObjectChangedEvent(EventHandler<ObjectChangedEventArgs> callback) { // // Register a wait handle if one has not been registered already // Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddObjectChanged() called."); lock (LockObjChangedEvent){ if (m_objectChanged == null){ if (m_id.Equals(Guid.Empty)) throw (new PeerToPeerException(SR.GetString(SR.Collab_EmptyGuidError))); m_objChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // m_regObjChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(m_objChangedEvent, //Event that triggers the callback new WaitOrTimerCallback(ObjectChangedCallback), //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.EndPointObjectChanged; GUID guid = CollaborationHelperFunctions.ConvertGuidToGUID(m_id); GCHandle guidHandle = GCHandle.Alloc(guid, GCHandleType.Pinned); // // Register event with collab // pcer.pInstance = guidHandle.AddrOfPinnedObject(); try{ int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( m_objChangedEvent.SafeWaitHandle, 1, ref pcer, out m_safeObjChangedEvent); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_ObjectChangedRegFailed), errorCode); } } finally{ if (guidHandle.IsAllocated) guidHandle.Free(); } } m_objectChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddObjectChanged() successful."); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Field: m_safeObjChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.CleanEventVars(System.Threading.RegisteredWaitHandle&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&,System.Threading.AutoResetEvent&):System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] private void RemoveObjectChangedEvent(EventHandler<ObjectChangedEventArgs> callback) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveObjectChanged() called."); lock (LockObjChangedEvent){ m_objectChanged -= callback; if (m_objectChanged == null){ CollaborationHelperFunctions.CleanEventVars(ref m_regObjChangedWaitHandle, ref m_safeObjChangedEvent, ref m_objChangedEvent); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Clean ObjectChangedEvent variables successful."); } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveObjectChanged() successful."); } protected virtual void OnObjectChanged(ObjectChangedEventArgs objChangedArgs) { EventHandler<ObjectChangedEventArgs> handlerCopy = m_objectChanged; if (handlerCopy != null){ if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) SynchronizingObject.BeginInvoke(handlerCopy, new object[] { this, objChangedArgs }); else handlerCopy(this, objChangedArgs); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Fired the object changed event callback."); } } // // Handles the callback when there is an object changed event from native collaboration // // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStructure(System.IntPtr,System.Type):System.Object" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabGetEventData(System.Net.PeerToPeer.Collaboration.SafeCollabEvent,System.Net.PeerToPeer.Collaboration.SafeCollabData&):System.Int32" /> // <ReferencesCritical Name="Local eventData of type: SafeCollabData" Ring="1" /> // <ReferencesCritical Name="Field: m_safeObjChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_OBJECTToPeerObject(System.Net.PeerToPeer.Collaboration.PEER_OBJECT):System.Net.PeerToPeer.Collaboration.PeerObject" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(System.Net.PeerToPeer.Collaboration.PEER_ENDPOINT):System.Net.PeerToPeer.Collaboration.PeerEndPoint" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_CONTACTToPeerContact(System.Net.PeerToPeer.Collaboration.PEER_CONTACT):System.Net.PeerToPeer.Collaboration.PeerContact" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] private void ObjectChangedCallback(object state, bool timedOut) { SafeCollabData eventData = null ; int errorCode = 0; Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "ObjectChangedCallback() called."); while (true){ ObjectChangedEventArgs objectChangedArgs = null; // // Get the event data for the fired event // try{ lock (LockObjChangedEvent){ if (m_safeObjChangedEvent.IsInvalid) return; errorCode = UnsafeCollabNativeMethods.PeerCollabGetEventData(m_safeObjChangedEvent, out eventData); } if (errorCode == UnsafeCollabReturnCodes.PEER_S_NO_EVENT_DATA) break; else if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabGetEventData returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetObjectChangedDataFailed), errorCode); } PEER_COLLAB_EVENT_DATA ped = (PEER_COLLAB_EVENT_DATA)Marshal.PtrToStructure(eventData.DangerousGetHandle(), typeof(PEER_COLLAB_EVENT_DATA)); if (ped.eventType == PeerCollabEventType.EndPointObjectChanged){ PEER_EVENT_OBJECT_CHANGED_DATA objData = ped.objectChangedData; PEER_OBJECT po = (PEER_OBJECT)Marshal.PtrToStructure(objData.pObject, typeof(PEER_OBJECT)); PeerObject peerObject = CollaborationHelperFunctions.ConvertPEER_OBJECTToPeerObject(po); // // Check if the Guid of the fired app is indeed our guid // if (Guid.Equals(m_id, peerObject.Id)){ PeerContact peerContact = null; PeerEndPoint peerEndPoint = null; if (objData.pContact != IntPtr.Zero){ PEER_CONTACT pc = (PEER_CONTACT)Marshal.PtrToStructure(objData.pContact, typeof(PEER_CONTACT)); peerContact = CollaborationHelperFunctions.ConvertPEER_CONTACTToPeerContact(pc); } if (objData.pEndPoint != IntPtr.Zero){ PEER_ENDPOINT pe = (PEER_ENDPOINT)Marshal.PtrToStructure(objData.pEndPoint, typeof(PEER_ENDPOINT)); peerEndPoint = CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(pe); } objectChangedArgs = new ObjectChangedEventArgs(peerEndPoint, peerContact, objData.changeType, peerObject); } } } finally{ if (eventData != null) eventData.Dispose(); } // // Fire the callback with the marshalled event args data // if(objectChangedArgs != null) OnObjectChanged(objectChangedArgs); } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving ObjectChangedCallback()."); } public bool Equals(PeerObject other) { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); if (other != null){ return other.Id.Equals(Id); } return false; } public override bool Equals(object obj) { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); PeerObject comparandPeerObject = obj as PeerObject; if (comparandPeerObject != null){ return comparandPeerObject.Id.Equals(Id); } return false; } public new static bool Equals(object objA, object objB) { PeerObject comparandPeerObject1 = objA as PeerObject; PeerObject comparandPeerObject2 = objB as PeerObject; if ((comparandPeerObject1 != null) && (comparandPeerObject2 != null)){ return Guid.Equals(comparandPeerObject1.Id, comparandPeerObject2.Id); } return false; } public override int GetHashCode() { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return Id.GetHashCode(); } public override string ToString() { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return Id.ToString(); } private bool m_Disposed; // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: Dispose(Boolean):Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Field: m_safeObjChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.CleanEventVars(System.Threading.RegisteredWaitHandle&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&,System.Threading.AutoResetEvent&):System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] protected virtual void Dispose(bool disposing) { if (!m_Disposed){ CollaborationHelperFunctions.CleanEventVars(ref m_regObjChangedWaitHandle, ref m_safeObjChangedEvent, ref m_objChangedEvent); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Clean ObjectChangedEvent variables successful."); m_Disposed = true; } } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="GetObjectData(SerializationInfo, StreamingContext):Void" /> // </SecurityKernel> [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.Net.dll is still using pre-v4 security model and needs this demand")] [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter, SerializationFormatter = true)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { GetObjectData(info, context); } /// <summary> /// This is made virtual so that derived types can be implemented correctly /// </summary> [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("_Id", m_id); info.AddValue("_Data", m_data); info.AddValue("_Scope", m_peerScope); } internal void TracePeerObject() { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Contents of the PeerObject"); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tGuid: {0}", Id); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tPeerScope: {0}", PeerScope); if (Data != null){ if (Logging.P2PTraceSource.Switch.ShouldTrace(TraceEventType.Verbose)){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tObject data:"); Logging.DumpData(Logging.P2PTraceSource, TraceEventType.Verbose, Logging.P2PTraceSource.MaxDataSize, Data, 0, Data.Length); } else{ Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tObject data length {0}", Data.Length); } } } } // // Manages collection of peer objects // [Serializable] public class PeerObjectCollection : Collection<PeerObject> { internal PeerObjectCollection() { } protected override void SetItem(int index, PeerObject item) { // nulls not allowed if (item == null){ throw new ArgumentNullException("item"); } base.SetItem(index, item); } protected override void InsertItem(int index, PeerObject item) { // nulls not allowed if (item == null){ throw new ArgumentNullException("item"); } base.InsertItem(index, item); } public override string ToString() { bool first = true; StringBuilder builder = new StringBuilder(); foreach (PeerObject peerObject in this) { if (!first){ builder.Append(", "); } else{ first = false; } builder.Append(peerObject.ToString()); } return builder.ToString(); } } }
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 EZOper.TechTester.OWINOAuthWebSI.Areas.ZApi { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using Csla; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERCLevel; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F04_SubContinent (editable child object).<br/> /// This is a generated base class of <see cref="F04_SubContinent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="F05_CountryObjects"/> of type <see cref="F05_CountryColl"/> (1:M relation to <see cref="F06_Country"/>)<br/> /// This class is an item of <see cref="F03_SubContinentColl"/> collection. /// </remarks> [Serializable] public partial class F04_SubContinent : BusinessBase<F04_SubContinent> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_Continent_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> SubContinent_IDProperty = RegisterProperty<int>(p => p.SubContinent_ID, "SubContinents ID"); /// <summary> /// Gets the SubContinents ID. /// </summary> /// <value>The SubContinents ID.</value> public int SubContinent_ID { get { return GetProperty(SubContinent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="SubContinent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_NameProperty = RegisterProperty<string>(p => p.SubContinent_Name, "SubContinents Name"); /// <summary> /// Gets or sets the SubContinents Name. /// </summary> /// <value>The SubContinents Name.</value> public string SubContinent_Name { get { return GetProperty(SubContinent_NameProperty); } set { SetProperty(SubContinent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F05_SubContinent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<F05_SubContinent_Child> F05_SubContinent_SingleObjectProperty = RegisterProperty<F05_SubContinent_Child>(p => p.F05_SubContinent_SingleObject, "F05 SubContinent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the F05 Sub Continent Single Object ("parent load" child property). /// </summary> /// <value>The F05 Sub Continent Single Object.</value> public F05_SubContinent_Child F05_SubContinent_SingleObject { get { return GetProperty(F05_SubContinent_SingleObjectProperty); } private set { LoadProperty(F05_SubContinent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F05_SubContinent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<F05_SubContinent_ReChild> F05_SubContinent_ASingleObjectProperty = RegisterProperty<F05_SubContinent_ReChild>(p => p.F05_SubContinent_ASingleObject, "F05 SubContinent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the F05 Sub Continent ASingle Object ("parent load" child property). /// </summary> /// <value>The F05 Sub Continent ASingle Object.</value> public F05_SubContinent_ReChild F05_SubContinent_ASingleObject { get { return GetProperty(F05_SubContinent_ASingleObjectProperty); } private set { LoadProperty(F05_SubContinent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F05_CountryObjects"/> property. /// </summary> public static readonly PropertyInfo<F05_CountryColl> F05_CountryObjectsProperty = RegisterProperty<F05_CountryColl>(p => p.F05_CountryObjects, "F05 Country Objects", RelationshipTypes.Child); /// <summary> /// Gets the F05 Country Objects ("parent load" child property). /// </summary> /// <value>The F05 Country Objects.</value> public F05_CountryColl F05_CountryObjects { get { return GetProperty(F05_CountryObjectsProperty); } private set { LoadProperty(F05_CountryObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F04_SubContinent"/> object. /// </summary> /// <returns>A reference to the created <see cref="F04_SubContinent"/> object.</returns> internal static F04_SubContinent NewF04_SubContinent() { return DataPortal.CreateChild<F04_SubContinent>(); } /// <summary> /// Factory method. Loads a <see cref="F04_SubContinent"/> object from the given F04_SubContinentDto. /// </summary> /// <param name="data">The <see cref="F04_SubContinentDto"/>.</param> /// <returns>A reference to the fetched <see cref="F04_SubContinent"/> object.</returns> internal static F04_SubContinent GetF04_SubContinent(F04_SubContinentDto data) { F04_SubContinent obj = new F04_SubContinent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.LoadProperty(F05_CountryObjectsProperty, F05_CountryColl.NewF05_CountryColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F04_SubContinent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F04_SubContinent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F04_SubContinent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(SubContinent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(F05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<F05_SubContinent_Child>()); LoadProperty(F05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<F05_SubContinent_ReChild>()); LoadProperty(F05_CountryObjectsProperty, DataPortal.CreateChild<F05_CountryColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F04_SubContinent"/> object from the given <see cref="F04_SubContinentDto"/>. /// </summary> /// <param name="data">The F04_SubContinentDto to use.</param> private void Fetch(F04_SubContinentDto data) { // Value properties LoadProperty(SubContinent_IDProperty, data.SubContinent_ID); LoadProperty(SubContinent_NameProperty, data.SubContinent_Name); // parent properties parent_Continent_ID = data.Parent_Continent_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Loads child <see cref="F05_SubContinent_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(F05_SubContinent_Child child) { LoadProperty(F05_SubContinent_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="F05_SubContinent_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(F05_SubContinent_ReChild child) { LoadProperty(F05_SubContinent_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="F04_SubContinent"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F02_Continent parent) { var dto = new F04_SubContinentDto(); dto.Parent_Continent_ID = parent.Continent_ID; dto.SubContinent_Name = SubContinent_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IF04_SubContinentDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); LoadProperty(SubContinent_IDProperty, resultDto.SubContinent_ID); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="F04_SubContinent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; var dto = new F04_SubContinentDto(); dto.SubContinent_ID = SubContinent_ID; dto.SubContinent_Name = SubContinent_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IF04_SubContinentDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="F04_SubContinent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IF04_SubContinentDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(SubContinent_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
//! \file ImageALB.cs //! \date Fri Mar 11 18:27:42 2016 //! \brief SLG system obfuscated image format. // // Copyright (C) 2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using GameRes.Utility; namespace GameRes.Formats.Slg { internal class AlbMetaData : ImageMetaData { public int UnpackedSize; public ImageFormat Format; public ImageMetaData Info; } [Export(typeof(ImageFormat))] public class AlbFormat : ImageFormat { public override string Tag { get { return "ALB"; } } public override string Description { get { return "SLG system image format"; } } public override uint Signature { get { return 0x31424C41; } } // 'ALB1' static readonly Lazy<ImageFormat> Dds = new Lazy<ImageFormat> (() => ImageFormat.FindByTag ("DDS")); public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (0x10); int unpacked_size = header.ToInt32 (8); using (var alb = new AlbStream (stream, unpacked_size)) using (var s = new SeekableStream (alb)) using (var file = new BinaryStream (s, stream.Name)) { uint signature = file.Signature; ImageFormat format; if (Png.Signature == signature) format = ImageFormat.Png; else if (Dds.Value.Signature == signature) format = Dds.Value; else format = ImageFormat.Jpeg; file.Position = 0; var info = format.ReadMetaData (file); if (null == info) return null; return new AlbMetaData { Width = info.Width, Height = info.Height, OffsetX = info.OffsetX, OffsetY = info.OffsetY, BPP = info.BPP, Format = format, Info = info, UnpackedSize = unpacked_size, }; } } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { var meta = (AlbMetaData)info; stream.Position = 0x10; using (var alb = new AlbStream (stream, meta.UnpackedSize)) using (var s = new SeekableStream (alb)) using (var file = new BinaryStream (s, stream.Name)) return meta.Format.Read (file, meta.Info); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("AlbFormat.Write not implemented"); } } internal class AlbStream : Stream { IBinaryStream m_input; int m_unpacked_size; IEnumerator<int> m_iterator; byte[] m_output; int m_output_pos; int m_output_end; public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public AlbStream (IBinaryStream source, int unpacked_size) { m_input = source; m_unpacked_size = unpacked_size; m_iterator = ReadSeq(); } public override int Read (byte[] buffer, int offset, int count) { m_output = buffer; m_output_pos = offset; m_output_end = offset + count; if (!m_iterator.MoveNext()) return 0; return m_iterator.Current - offset; } byte[,] m_dict = new byte[256,2]; IEnumerator<int> ReadSeq () { var stack = new byte[256]; while (m_input.PeekByte() != -1) { int packed_size = UnpackDict(); int src = 0; int stack_pos = 0; for (;;) { byte s; if (stack_pos > 0) { s = stack[--stack_pos]; } else if (src < packed_size) { s = m_input.ReadUInt8(); src++; } else { break; } if (m_dict[s,0] == s) { while (m_output_pos == m_output_end) yield return m_output_pos; m_output[m_output_pos++] = s; } else { stack[stack_pos++] = m_dict[s,1]; stack[stack_pos++] = m_dict[s,0]; } } } yield return m_output_pos; } int UnpackDict () { if (m_input.ReadInt16() != 0x4850) // 'PH' throw new InvalidFormatException(); int table_size = m_input.ReadUInt16(); int packed_size = m_input.ReadUInt16(); bool is_packed = m_input.ReadUInt8() != 0; byte marker = m_input.ReadUInt8(); if (is_packed) { for (int i = 0; i < 256; ) { byte b = m_input.ReadUInt8(); if (marker == b) { int count = m_input.ReadUInt8(); for (int j = 0; j < count; ++j) { m_dict[i,0] = (byte)i; m_dict[i,1] = 0; ++i; } } else { m_dict[i,0] = b; m_dict[i,1] = m_input.ReadUInt8(); ++i; } } } else { for (int i = 0; i < 256; ++i) { m_dict[i,0] = m_input.ReadUInt8(); m_dict[i,1] = m_input.ReadUInt8(); } } return packed_size; } #region IO.Stream Members public override long Length { get { return m_unpacked_size; } } public override long Position { get { throw new NotSupportedException ("AlbStream.Position not supported"); } set { throw new NotSupportedException ("AlbStream.Position not supported"); } } public override void Flush() { } public override long Seek (long offset, SeekOrigin origin) { throw new NotSupportedException ("AlbStream.Seek method is not supported"); } public override void SetLength (long length) { throw new NotSupportedException ("AlbStream.SetLength method is not supported"); } public override void Write (byte[] buffer, int offset, int count) { throw new NotSupportedException ("AlbStream.Write method is not supported"); } public override void WriteByte (byte value) { throw new NotSupportedException ("AlbStream.WriteByte method is not supported"); } #endregion #region IDisposable Members bool _alb_disposed = false; protected override void Dispose (bool disposing) { if (!_alb_disposed) { if (disposing) { m_iterator.Dispose(); } _alb_disposed = true; } base.Dispose (disposing); } #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Algo File: OrderLogHelper.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// Reasons for orders cancelling in the orders log. /// </summary> public enum OrderLogCancelReasons { /// <summary> /// The order re-registration. /// </summary> ReRegistered, /// <summary> /// Cancel order. /// </summary> Canceled, /// <summary> /// Group canceling of orders. /// </summary> GroupCanceled, /// <summary> /// The sign of deletion of order residual due to cross-trade. /// </summary> CrossTrade, } /// <summary> /// Building order book by the orders log. /// </summary> public static class OrderLogHelper { /// <summary> /// To check, does the string contain the order registration. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contains the order registration, otherwise, <see langword="false" />.</returns> public static bool IsOrderLogRegistered(this ExecutionMessage item) { if (item == null) throw new ArgumentNullException(nameof(item)); return item.OrderState == OrderStates.Active && item.TradePrice == null; } /// <summary> /// To check, does the string contain the order registration. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contains the order registration, otherwise, <see langword="false" />.</returns> public static bool IsRegistered(this OrderLogItem item) { return item.ToMessage().IsOrderLogRegistered(); } /// <summary> /// To check, does the string contain the cancelled order. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contain the cancelled order, otherwise, <see langword="false" />.</returns> public static bool IsOrderLogCanceled(this ExecutionMessage item) { if (item == null) throw new ArgumentNullException(nameof(item)); return item.OrderState == OrderStates.Done && item.TradePrice == null; } /// <summary> /// To check, does the string contain the cancelled order. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contain the cancelled order, otherwise, <see langword="false" />.</returns> public static bool IsCanceled(this OrderLogItem item) { return item.ToMessage().IsOrderLogCanceled(); } /// <summary> /// To check, does the string contain the order matching. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contains order matching, otherwise, <see langword="false" />.</returns> public static bool IsOrderLogMatched(this ExecutionMessage item) { if (item == null) throw new ArgumentNullException(nameof(item)); return item.TradeId != null; } /// <summary> /// To check, does the string contain the order matching. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contains order matching, otherwise, <see langword="false" />.</returns> public static bool IsMatched(this OrderLogItem item) { return item.ToMessage().IsOrderLogMatched(); } /// <summary> /// To get the reason for cancelling order in orders log. /// </summary> /// <param name="item">Order log item.</param> /// <returns>The reason for order cancelling in order log.</returns> public static OrderLogCancelReasons GetOrderLogCancelReason(this ExecutionMessage item) { if (!item.IsOrderLogCanceled()) throw new ArgumentException(LocalizedStrings.Str937, nameof(item)); if (item.OrderStatus == null) throw new ArgumentException(LocalizedStrings.Str938, nameof(item)); var status = item.OrderStatus.Value; if (status.HasBits(0x100000)) return OrderLogCancelReasons.ReRegistered; else if (status.HasBits(0x200000)) return OrderLogCancelReasons.Canceled; else if (status.HasBits(0x400000)) return OrderLogCancelReasons.GroupCanceled; else if (status.HasBits(0x800000)) return OrderLogCancelReasons.CrossTrade; else throw new ArgumentOutOfRangeException(nameof(item), status, LocalizedStrings.Str939); } /// <summary> /// To get the reason for cancelling order in orders log. /// </summary> /// <param name="item">Order log item.</param> /// <returns>The reason for order cancelling in order log.</returns> public static OrderLogCancelReasons GetCancelReason(this OrderLogItem item) { return item.ToMessage().GetOrderLogCancelReason(); } private sealed class DepthEnumerable : SimpleEnumerable<QuoteChangeMessage>//, IEnumerableEx<QuoteChangeMessage> { private sealed class DepthEnumerator : IEnumerator<QuoteChangeMessage> { private readonly TimeSpan _interval; private readonly IEnumerator<ExecutionMessage> _itemsEnumerator; private readonly IOrderLogMarketDepthBuilder _builder; private readonly int _maxDepth; public DepthEnumerator(IEnumerable<ExecutionMessage> items, IOrderLogMarketDepthBuilder builder, TimeSpan interval, int maxDepth) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (items == null) throw new ArgumentNullException(nameof(items)); if (maxDepth < 1) throw new ArgumentOutOfRangeException(nameof(maxDepth), maxDepth, LocalizedStrings.Str941); _itemsEnumerator = items.GetEnumerator(); _builder = builder; _interval = interval; _maxDepth = maxDepth; } public QuoteChangeMessage Current { get; private set; } bool IEnumerator.MoveNext() { while (_itemsEnumerator.MoveNext()) { var item = _itemsEnumerator.Current; //if (_builder == null) // _builder = new OrderLogMarketDepthBuilder(new QuoteChangeMessage { SecurityId = item.SecurityId, IsSorted = true }, _maxDepth); if (!_builder.Update(item)) continue; if (Current != null && (_builder.Depth.ServerTime - Current.ServerTime) < _interval) continue; Current = (QuoteChangeMessage)_builder.Depth.Clone(); if (_maxDepth < int.MaxValue) { //Current.MaxDepth = _maxDepth; Current.Bids = Current.Bids.Take(_maxDepth).ToArray(); Current.Asks = Current.Asks.Take(_maxDepth).ToArray(); } return true; } Current = null; return false; } public void Reset() { _itemsEnumerator.Reset(); Current = null; } object IEnumerator.Current => Current; void IDisposable.Dispose() { Reset(); _itemsEnumerator.Dispose(); } } //private readonly IEnumerableEx<ExecutionMessage> _items; public DepthEnumerable(IEnumerable<ExecutionMessage> items, IOrderLogMarketDepthBuilder builder, TimeSpan interval, int maxDepth) : base(() => new DepthEnumerator(items, builder, interval, maxDepth)) { if (items == null) throw new ArgumentNullException(nameof(items)); if (interval < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(interval), interval, LocalizedStrings.Str940); //_items = items; } //int IEnumerableEx.Count => _items.Count; } /// <summary> /// Build market depths from order log. /// </summary> /// <param name="items">Orders log lines.</param> /// <param name="builder">Order log to market depth builder.</param> /// <param name="interval">The interval of the order book generation. The default is <see cref="TimeSpan.Zero"/>, which means order books generation at each new string of orders log.</param> /// <param name="maxDepth">The maximal depth of order book. The default is <see cref="Int32.MaxValue"/>, which means endless depth.</param> /// <returns>Market depths.</returns> public static IEnumerable<MarketDepth> ToMarketDepths(this IEnumerable<OrderLogItem> items, IOrderLogMarketDepthBuilder builder, TimeSpan interval = default(TimeSpan), int maxDepth = int.MaxValue) { var first = items.FirstOrDefault(); if (first == null) return Enumerable.Empty<MarketDepth>(); return items.ToMessages<OrderLogItem, ExecutionMessage>() .ToMarketDepths(builder, interval) .ToEntities<QuoteChangeMessage, MarketDepth>(first.Order.Security); } /// <summary> /// Build market depths from order log. /// </summary> /// <param name="items">Orders log lines.</param> /// <param name="builder">Order log to market depth builder.</param> /// <param name="interval">The interval of the order book generation. The default is <see cref="TimeSpan.Zero"/>, which means order books generation at each new string of orders log.</param> /// <param name="maxDepth">The maximal depth of order book. The default is <see cref="Int32.MaxValue"/>, which means endless depth.</param> /// <returns>Market depths.</returns> public static IEnumerable<QuoteChangeMessage> ToMarketDepths(this IEnumerable<ExecutionMessage> items, IOrderLogMarketDepthBuilder builder, TimeSpan interval = default(TimeSpan), int maxDepth = int.MaxValue) { return new DepthEnumerable(items, builder, interval, maxDepth); } private sealed class OrderLogTickEnumerable : SimpleEnumerable<ExecutionMessage>//, IEnumerableEx<ExecutionMessage> { private sealed class OrderLogTickEnumerator : IEnumerator<ExecutionMessage> { private readonly IEnumerator<ExecutionMessage> _itemsEnumerator; private readonly Dictionary<long, Tuple<long, Sides>> _trades = new Dictionary<long, Tuple<long, Sides>>(); public OrderLogTickEnumerator(IEnumerable<ExecutionMessage> items) { if (items == null) throw new ArgumentNullException(nameof(items)); _itemsEnumerator = items.GetEnumerator(); } public ExecutionMessage Current { get; private set; } bool IEnumerator.MoveNext() { while (_itemsEnumerator.MoveNext()) { var currItem = _itemsEnumerator.Current; var tradeId = currItem.TradeId; if (tradeId == null) continue; var prevItem = _trades.TryGetValue(tradeId.Value); if (prevItem == null) { _trades.Add(tradeId.Value, Tuple.Create(currItem.SafeGetOrderId(), currItem.Side)); } else { _trades.Remove(tradeId.Value); Current = new ExecutionMessage { ExecutionType = ExecutionTypes.Tick, SecurityId = currItem.SecurityId, TradeId = tradeId, TradePrice = currItem.TradePrice, TradeStatus = currItem.TradeStatus, TradeVolume = currItem.TradeVolume, ServerTime = currItem.ServerTime, LocalTime = currItem.LocalTime, OpenInterest = currItem.OpenInterest, OriginSide = prevItem.Item2 == Sides.Buy ? (prevItem.Item1 > currItem.OrderId ? Sides.Buy : Sides.Sell) : (prevItem.Item1 > currItem.OrderId ? Sides.Sell : Sides.Buy), }; return true; } } Current = null; return false; } void IEnumerator.Reset() { _itemsEnumerator.Reset(); Current = null; } object IEnumerator.Current => Current; void IDisposable.Dispose() { _itemsEnumerator.Dispose(); } } //private readonly IEnumerable<ExecutionMessage> _items; public OrderLogTickEnumerable(IEnumerable<ExecutionMessage> items) : base(() => new OrderLogTickEnumerator(items)) { if (items == null) throw new ArgumentNullException(nameof(items)); //_items = items; } //int IEnumerableEx.Count => _items.Count; } /// <summary> /// To build tick trades from the orders log. /// </summary> /// <param name="items">Orders log lines.</param> /// <returns>Tick trades.</returns> public static IEnumerable<Trade> ToTrades(this IEnumerable<OrderLogItem> items) { var first = items.FirstOrDefault(); if (first == null) return Enumerable.Empty<Trade>(); var ticks = items .Select(i => i.ToMessage()) .ToTicks(); return ticks.Select(m => m.ToTrade(first.Order.Security)); } /// <summary> /// To build tick trades from the orders log. /// </summary> /// <param name="items">Orders log lines.</param> /// <returns>Tick trades.</returns> public static IEnumerable<ExecutionMessage> ToTicks(this IEnumerable<ExecutionMessage> items) { return new OrderLogTickEnumerable(items); } } }
// 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Linq; using System.Net.Http.Headers; using System.Net.Test.Common; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; [ActiveIssue(20470, TargetFrameworkMonikers.UapAot)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core.")] public class DiagnosticsTest : HttpClientTestBase { [Fact] public static void EventSource_ExistsWithCorrectId() { Type esType = typeof(HttpClient).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false); Assert.NotNull(esType); Assert.Equal("Microsoft-System-Net-Http", EventSource.GetName(esType)); Assert.Equal(Guid.Parse("bdd9a83e-1929-5482-0d73-2fe5e1c0e16d"), EventSource.GetGuid(esType)); Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest")); } // Diagnostic tests are each invoked in their own process as they enable/disable // process-wide EventSource-based tracing, and other tests in the same process // could interfere with the tests, as well as the enabling of tracing interfering // with those tests. /// <remarks> /// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler /// DiagnosticSources, since the global logging mechanism makes them conflict inherently. /// </remarks> [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceLogging() { RemoteInvoke(useManagedHandlerString => { bool requestLogged = false; Guid requestGuid = Guid.Empty; bool responseLogged = false; Guid responseGuid = Guid.Empty; bool exceptionLogged = false; bool activityLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); requestGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId"); requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response"); responseGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.RanToCompletion, requestStatus); responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; } else if (kvp.Key.StartsWith("System.Net.Http.HttpRequestOut")) { activityLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable( s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.True(requestLogged, "Request was not logged."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout."); Assert.Equal(requestGuid, responseGuid); Assert.False(exceptionLogged, "Exception was logged for successful request"); Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } /// <remarks> /// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler /// DiagnosticSources, since the global logging mechanism makes them conflict inherently. /// </remarks> [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceNoLogging() { RemoteInvoke(useManagedHandlerString => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { LoopbackServer.CreateServerAsync(async (server, url) => { Task<List<string>> requestLines = LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer)); Task<HttpResponseMessage> response = client.GetAsync(url); await Task.WhenAll(response, requestLines); AssertNoHeadersAreInjected(requestLines.Result); response.Result.Dispose(); }).Wait(); } Assert.False(requestLogged, "Request was logged while logging disabled."); Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while logging disabled."); WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled."); Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled."); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [ActiveIssue(23771, TestPlatforms.AnyUnix)] [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_HttpTracingEnabled_Succeeds() { RemoteInvoke(async useManagedHandlerString => { using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose)) { var events = new ConcurrentQueue<EventWrittenEventArgs>(); await listener.RunWithCallbackAsync(events.Enqueue, async () => { // Exercise various code paths to get coverage of tracing using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { // Do a get to a loopback server await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server), client.GetAsync(url)); }); // Do a post to a remote server byte[] expectedData = Enumerable.Range(0, 20000).Select(i => unchecked((byte)i)).ToArray(); HttpContent content = new ByteArrayContent(expectedData); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.RemoteEchoServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }); // We don't validate receiving specific events, but rather that we do at least // receive some events, and that enabling tracing doesn't cause other failures // in processing. Assert.DoesNotContain(events, ev => ev.EventId == 0); // make sure there are no event source error messages Assert.InRange(events.Count, 1, int.MaxValue); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticExceptionLogging() { RemoteInvoke(useManagedHandlerString => { bool exceptionLogged = false; bool responseLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Faulted, requestStatus); responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response with exception was not logged within 1 second timeout."); Assert.True(exceptionLogged, "Exception was not logged"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [ActiveIssue(23209)] [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticCancelledLogging() { RemoteInvoke(useManagedHandlerString => { bool cancelLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Canceled, status); Volatile.Write(ref cancelLogged, true); } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { LoopbackServer.CreateServerAsync(async (server, url) => { CancellationTokenSource tcs = new CancellationTokenSource(); Task request = LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => { tcs.Cancel(); return LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer); }); Task response = client.GetAsync(url, tcs.Token); await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request)); }).Wait(); } } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1), "Cancellation was not logged within 1 second timeout."); diagnosticListenerObserver.Disable(); return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; bool exceptionLogged = false; Activity parentActivity = new Activity("parent"); parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString()); parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString()); parentActivity.AddTag("tag", "tag"); //add tag to ensure it is not injected into request parentActivity.Start(); var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true;} else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); Assert.True(Activity.Current.Duration != TimeSpan.Zero); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.RanToCompletion, requestStatus); activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { LoopbackServer.CreateServerAsync(async (server, url) => { Task<List<string>> requestLines = LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer)); Task<HttpResponseMessage> response = client.GetAsync(url); await Task.WhenAll(response, requestLines); AssertHeadersAreInjected(requestLines.Result, parentActivity); response.Result.Dispose(); }).Wait(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); Assert.False(requestLogged, "Request was logged when Activity logging was enabled."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.False(exceptionLogged, "Exception was logged for successful request"); Assert.False(responseLogged, "Response was logged when Activity logging was enabled."); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")){activityStartLogged = true;} else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) {activityStopLogged = true;} }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable((s, r, _) => { if (s.StartsWith("System.Net.Http.HttpRequestOut")) { var request = r as HttpRequestMessage; if (request != null) return !request.RequestUri.Equals(Configuration.Http.RemoteEchoServer); } return true; }); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled."); // Poll with a timeout since logging response is not synchronized with returning a response. Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled."); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticExceptionActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool exceptionLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Faulted, requestStatus); activityStopLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "Response with exception was not logged within 1 second timeout."); Assert.True(exceptionLogged, "Exception was not logged"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging() { RemoteInvoke(useManagedHandlerString => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true;} else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); Assert.True(requestLogged, "Request was not logged."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.True(responseLogged, "Response was not logged."); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool exceptionLogged = false; bool activityLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => exceptionLogged, TimeSpan.FromSeconds(1), "Exception was not logged within 1 second timeout."); Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticStopOnlyActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(Activity.Current); activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut")); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.False(activityStartLogged, "HttpRequestOut.Start was logged when start logging was disabled"); diagnosticListenerObserver.Disable(); } return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } [ActiveIssue(23209)] [OuterLoop] // TODO: Issue #11345 [Fact] public void SendAsync_ExpectedDiagnosticCancelledActivityLogging() { RemoteInvoke(useManagedHandlerString => { bool cancelLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop") { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Canceled, status); Volatile.Write(ref cancelLogged, true); } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useManagedHandlerString)) { LoopbackServer.CreateServerAsync(async (server, url) => { CancellationTokenSource tcs = new CancellationTokenSource(); Task request = LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => { tcs.Cancel(); return LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer); }); Task response = client.GetAsync(url, tcs.Token); await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request)); }).Wait(); } } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1), "Cancellation was not logged within 1 second timeout."); diagnosticListenerObserver.Disable(); return SuccessExitCode; }, UseManagedHandler.ToString()).Dispose(); } private static T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName) { Type t = obj.GetType(); PropertyInfo p = t.GetRuntimeProperty(propertyName); object propertyValue = p.GetValue(obj); Assert.NotNull(propertyValue); Assert.IsAssignableFrom<T>(propertyValue); return (T)propertyValue; } private static void WaitForTrue(Func<bool> p, TimeSpan timeout, string message) { // Assert that spin doesn't time out. Assert.True(SpinWait.SpinUntil(p, timeout), message); } private static void WaitForFalse(Func<bool> p, TimeSpan timeout, string message) { // Assert that spin times out. Assert.False(SpinWait.SpinUntil(p, timeout), message); } private void AssertHeadersAreInjected(List<string> requestLines, Activity parent) { string requestId = null; var correlationContext = new List<NameValueHeaderValue>(); foreach (var line in requestLines) { if (line.StartsWith("Request-Id")) { requestId = line.Substring("Request-Id".Length).Trim(' ', ':'); } if (line.StartsWith("Correlation-Context")) { var corrCtxString = line.Substring("Correlation-Context".Length).Trim(' ', ':'); foreach (var kvp in corrCtxString.Split(',')) { correlationContext.Add(NameValueHeaderValue.Parse(kvp)); } } } Assert.True(requestId != null, "Request-Id was not injected when instrumentation was enabled"); Assert.True(requestId.StartsWith(parent.Id)); Assert.NotEqual(parent.Id, requestId); List<KeyValuePair<string, string>> baggage = parent.Baggage.ToList(); Assert.Equal(baggage.Count, correlationContext.Count); foreach (var kvp in baggage) { Assert.Contains(new NameValueHeaderValue(kvp.Key, kvp.Value), correlationContext); } } private void AssertNoHeadersAreInjected(List<string> requestLines) { foreach (var line in requestLines) { Assert.False(line.StartsWith("Request-Id"), "Request-Id header was injected when instrumentation was disabled"); Assert.False(line.StartsWith("Correlation-Context"), "Correlation-Context header was injected when instrumentation was disabled"); } } } }